How to get data from database and make download that content as pdf format in Asp.net MVC - sql

I have data in varbinary type in database from "Artifact" table like
ID CONTENT
1 Some data in varbinary type
Now i want to get the "Content" column data and should download as PDF format in Users Download folder with name "Report.PDF" file.
How should i this? I have tried like
public ActionResult DownloadFile(int fileId)
{
ResLandEntities reslandEntities = new ResLandEntities();
var content = reslandEntities.ARTIFACT.Where(m => m.ID== fileId).FirstOrDefault();
byte[] contents = content.CONTENT;
string text = Encoding.UTF8.GetString(contents);
return File(Server.MapPath("~/download/Report.PDF"), "application/pdf", text );
}
But, not getting, can anybody help me

Try This :
public ActionResult DownloadFile(int fileId)
{
ResLandEntities reslandEntities = new ResLandEntities();
var content = reslandEntities.ARTIFACT.Where(m => m.ID== fileId).FirstOrDefault();
byte[] contents = (byte[])content.CONTENT;
return File(contents, "application/pdf");
}

Related

Saving and Loading file definitions while using <generic> version of FileEngine

I've successfully use the SaveToXml and LoadFromXml methods on the ClassBuilder class to store and retrieve the file definitions while using the Standard version of the File Helper Engine.
However I'd really prefer to use the generic version of the File Helper Engine. In other words I'd like to instatiate the engine like so:
var eng = new DelimitedFileEngine<OutputClass>(params....);
OutputClass[] records = eng.ReadFile("Sample.csv");
So my results are strongly typed and not just an array of objects.
Does this save and load functionality exist for the generic file helper engine?
Sure, it works exactly as you'd expect.
[DelimitedRecord("|")]
public class OutputClass
{
public string First { get; set; }
public string Second { get; set; }
}
class Program
{
static void Main(string[] args)
{
var eng = new DelimitedFileEngine<OutputClass>();
// To read from a file use ReadFile()
//OutputClass[] records = eng.ReadFile("Sample.csv");
// Or to read from a string use ReadString()
OutputClass[] records = eng.ReadString("First|Second");
Debug.Assert(records.Length == 1);
Debug.Assert(records[0].First == "First");
Debug.Assert(records[0].Second == "Second");
Console.WriteLine("All OK");
Console.ReadKey();
}
}
Edit:
Based on your comment below, you want to map the results from your XML class to a concrete C# object. The easiest way is to use read into a DataTable and map the fields to the C# object.
var cb = new DelimitedClassBuilder(nameof(OutputClass), "|");
cb.AddField("First", typeof(string));
cb.AddField("Second", typeof(string));
var xmlString = cb.SaveToXmlString();
var outputClass = DelimitedClassBuilder.LoadFromXmlString(xmlString);
var eng = new FileHelperEngine(outputClass.CreateRecordClass());
OutputClass[] records = eng
.ReadStringAsDT("First|Second")
.Rows.OfType<DataRow>()
.Select(x => new OutputClass() {
First = x.Field<string>("First"),
Second = x.Field<string>("Second")
})
.ToArray();

How to pass the value inside Rotativa.ActionAsPdf

I am new asp .net .
I am using Rotativa to turn a Razor view into a PDF.
I am having a normal preview page which is working fine.
The same thing I want to print in PDF .
[HttpGet]
public ActionResult IdCardPreview(string empid)
{
int empid1 = Convert.ToInt32(empid);
var dataList = db.mstEmpInformations.Where(x => x.intEmpId == empid1).SingleOrDefault();
return View(dataList);
}
public ActionResult GeneratePDF(string empid)
{
int empid1 = Convert.ToInt32(empid);
return new Rotativa.ActionAsPdf("IdCardPreview", new { empid1 });
}
while running the generate pdf is is showing the error as Object reference not set to an instance of an object.
Can any1 tell how i can pass the empid from generate pdf to IDCardpreview ?
The code should look like this at the generatePDF Action.
public ActionResult GeneratePDF(string empid)
{
return new Rotativa.ActionAsPdf("IdCardPreview", new { empid = empid });
}
Rotavita is going into the IdCardPreview action itself, and the conversion from string to int will be at the IdCardPreview Action.

Localization With Database MVC

I am working on a multilingual ASP.NET MVC application (MVC4).
I want to make my resource file strings to be editable at runtime without recompiling the application and without app pool recycling And it doesn't look possible with .resx file, so I migrate to store string resources in Database.
I have to Get Each Label/String Resource From Database, so there will be more hits to database for each request. How to fix that?
I have googled around and someone suggests to load the resource in a dictionary and store it as application variable, at login/Sign In page and use that dictionary as resource instead of database hit.
I am confused, what will be effective approach.Can someone guide me in right direction to avoid more database hits?
Any help/suggestions will be highly appreciated.
Thanks
I ran into the same concerns using .resx files for localization. They just did not work well when the persons doing the translation were not programmers. Now, we have a translation page in our admin area. Works great.
One area which we still don't have a good solution for are the data annotations, which still use the .resx files. I have trimmed the source below to remove any references to our actual database structures or tables.
There is a fallback to using the underlying .resx file, if an entry does not exist in the database. If there is not an entry in the .resx file, I split the word whenever a capitol letter is found ( CamelSpace is a string extension method ).
Lastly, depending on your implementation, you may need to remove the context caching, especially if you are caching out of process.
A few examples of usage:
#LanguageDb.Translate("Enter your first name below","FirstNamePrompt")
#LanguageDb.Me.FirstName
#String
.Format(LanguageDb
.Translate(#"You can be insured for
{0} down and {1} payments of {2}"),
Model.Down,Model.NumPayments,
Model.InstallmentAmount)
public class LanguageDb : DynamicObject
{
public static dynamic Me = new LanguageDb();
private LanguageDb() { }
public static string Translate(string englishPhrase, string resourceCode = null)
{
return GetTranslation(englishPhrase, resourceCode) ?? englishPhrase;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
result = GetTranslation(binder.Name);
return true;
}
private static string GetTranslation(string resourceName, string resourceCode = null)
{
resourceCode = resourceCode ?? resourceName;
if (resourceCode.Contains(" ") || resourceCode.Length > 50)
{
resourceCode = resourceName.GetHashCode().ToString(CultureInfo.InvariantCulture);
}
var lang = (string)HttpContext.Current.Request.RequestContext.RouteData.Values["lang"] ?? "en";
// cache entries for an hour
var result = Get(subagent + "_" + lang + "_" + resourceCode, 3600, () =>
{
// cache a datacontext object for 30 seconds.
var context = Get("_context", 30, () => new YourDataContext()) as YourDataContext;
var translation = context.Translations.FirstOrDefault(row => row.lang == lang && row.Code == resourceCode);
if (translation == null)
{
translation = new Lookup {
Code = resourceCode,
lang = lang,
Value = Language.ResourceManager.GetString(resourceName, Language.Culture)
?? resourceName.CamelSpace()
};
context.Translations.Add(translation);
context.SaveChanges();
}
return translation.Value;
});
return result;
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
// ignore this
return true;
}
public static T Get<T>(string cacheId, int secondsToCache, Func<T> getItemCallback) where T : class
{
T item = HttpRuntime.Cache.Get(cacheId) as T;
if (item == null)
{
item = getItemCallback();
if (secondsToCache > 0)
{
HttpRuntime.Cache.Insert(
cacheId, item, null, Cache.NoAbsoluteExpiration,
new TimeSpan(0, 0, secondsToCache), CacheItemPriority.Normal, null);
}
else
{
HttpRuntime.Cache.Insert(cacheId, item);
}
}
return item;
}
}

Kendo Upload- Change File Name and get it back

I use kendo upload on my mvc project. My user have to upload files and I have to change file name with the unique file name.
I change the file name in the controller :
public ActionResult Dosyayukle(IEnumerable<HttpPostedFileBase> files)
{
if (files != null)
{
foreach (var file in files)
{
var fileName = Path.GetFileName(file.FileName);
var ext = Path.GetExtension(fileName);
var physicalPath = Path.Combine(Server.MapPath("~/UploadedFiles"), fileName.Replace(ext, "") + Guid.NewGuid() + ext);
file.SaveAs(physicalPath);
}
}
// Return an empty string to signify success
return Content("");
}
I need to get file name and save this file name to db with unique name.
In JS onComplate event I can't found the file new file name.
this.onComplate = function (e) {
var dosyaAdi = self.dosyaAdi();
if (dosyaAdi.match(/rar$/)) {
alert('rar');
} else if (dosyaAdi.match(/zip$/)) {
alert('zip');
} else {
alert(dosyaAdi);
}
};
How can I pass the new file name to onComplate event handler?
Or how can I do this another way ?
You can use TempData to store key value object in which you can save file name and unique key. The same temp data you can get it in the save call.
Hope this solves your problem.
I've found a solution for your question.
http://www.telerik.com/support/kb/aspnet-ajax/editor/giving-the-uploaded-files-unique-names.aspx

RavenDB adds integer to ID when ends with a slash

I use RavenDB 1.0.0.426
I just experienced a weird scenario when importing data from an external source into RavenDB:
I chose to use the same unique ID as the external source uses, prefixed with a certain string. But. When I store a document with an ID that ends with a '/', raven automatically adds a number to the end of the ID, causing the document to NOT overwrite existing document stored with the same id.
I have recreated a simple scenario to cause the error:
The type I save:
public class Foo
{
public string Id { get; set; }
public Foo(string id)
{
Id = id;
}
}
Method saving a doc with the same id 10 times and afterwards checks the document count:
public void RunTest(string id)
{
for (int i = 0; i < 10; i++)
{
using (var doc = new DocumentStore() { Url = "http://pc-009:8080/" })
{
doc.Initialize();
using (var session = doc.OpenSession())
{
session.Store(new Foo(id));
session.SaveChanges();
}
}
}
// Wait for the data to be persisted
Thread.Sleep(2000);
using (var doc = new DocumentStore() { Url = "http://pc-009:8080/" })
{
doc.Initialize();
using (var session = doc.OpenSession())
{
var foos = session.Query<Foo>();
int fooCount = foos.Count();
// ASSERT HERE THAT fooCount is 1
}
}
}
Running the method with "id1" successfully overwrites existing documents:
RunTest("id1"); // Works fine
Running method with "id1/" ends up creating 10 documents in the database:
RunTest("id1/"); // Results in multiple documents to be created
I know that if you do not define your own ID, raven will autogenerate doc-ids on the fly, but is the behavior I describe above by design?
Thankyou in advance
Stephan,
This is expected, when your key ends with /, it asks ravendb to use identity generation strategy.
See the docs here:
http://ravendb.net/documentation/docs-api-key-generation
If you want a key that ends with /, you can url encode the keys