Application End after saving PDF file in ASP.net - c#

I created one function which get HTML data from session and save that as PDF
for that I used NReco.PdfGenerator
private static string savePdf()
{
if (HttpContext.Current.Session["ReservationPrintHtml"] != null)
{
StringBuilder objStringBuilder = ((StringBuilder)HttpContext.Current.Session["ReservationPrintHtml"]);
string dir = HostingEnvironment.MapPath("~/Pdf");
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
string fileName = "PDF-" + DateTime.Now.ToString("yyyyMMdd-HHMMssffffff") + ".pdf";
string downloadFile = Path.Combine(dir, fileName);
string htmlContent = objStringBuilder.ToString();
byte[] pdfBytes = (new NReco.PdfGenerator.HtmlToPdfConverter()).GeneratePdf(htmlContent);
File.WriteAllBytes(downloadFile, pdfBytes);
return fileName;
}
else
{
return null;
}
}
I'm not facing any issue regarding PDF generation but, After this function execution it directly calls Application_End in Global.asax
I have tried if I get any error in application but Application_Error not execute.
Can anyone have idea what is the problem?
Thank you.

After long search and googling I found that I'm saving files in PDF folder which was included in my project.
So whenever new PDF file was generated AppDomain recycle on folder change run after every 15-20 changes in folders which are included in solution included projects.
so I found solution by adding fcnMode="Disabled" in web.cofig file like below.
<httpRuntime targetFramework="4.5.2" fcnMode="Disabled" />

Related

How to get the fullname of the file stored in the temp folder in asp.net mvc 5 app?

I have an app written using c# on the top on ASP.NET MVC 5 framework. One of my pages allow a user to upload file to the server. So I use HttpPostedFileBase to upload the file to the server.
However, instead on saving the file to a permanent place, I am hoping be able to extract the fullname of the file and work on it before moving it to a permanent place.
How can I get the temp full-name of the uploaded file?
I tried the following, but the check File.Exists(tempFullname) always fails.
public string GetFullname(HttpPostedFileBase file)
{
string tempFullname = Path.GetTempPath() + file.FileName;
if(File.Exists(tempFullname))
{
return tempFullname;
}
return string.Empty;
}
I also tried the following but temp.Length throw an exception as the file does not exists
public string GetFullname(HttpPostedFileBase file)
{
string temp = new FileInfo(file.FileName);
if(temp.Length > 0)
{
return tempFullname;
}
return string.Empty;
}
To get the full name of need to save the file first, i can't get the location of a file if you don't save it first!
var filePath = Path.Combine(Server.MapPath("<A folder you want>"), file.FileName);
file.Save(filePath);
In this way, filePath is the full path of your file

How to give an absolute path in sever map method?

I have a folder which contains several PDF files and inserting and viewing all these pdf's are dont by 2 methods. I have to move this folder to place this folder outside of the project file. Therefore I have to use the absolute path. I have tried some coeds in the internet but none of them worked for me.
Following code is in a button clcik event
string directoryPath = #"D:\competion\pdfFolder\";
string svrPath = Server.MapPath(directoryPath);
DataSet ds = new DataSet();
string extension = Path.GetExtension(FileUpload1.FileName);
if ((FileUpload1.HasFile))
{
if (extension == ".pdf")
{
if (grdPolicyDetails.Rows.Count > 0)
{
//Few methods are invoked in the body
}
}
}
There are else parts in the if else statements but i haven't added those codes.
The Server.MapPath method works only with relative paths that are part of the web application structure. If you need to serve PDF files that are located outside, you might need to have some endpoint that will read the file contents on the server and stream it to the client.
For example:
string pdfPath = #"D:\competion\pdfFolder\myfile.pdf";
this.Response.ContentType = "application/pdf";
this.Response.TransmitFile(pdfPath);
this.Response.End();
I created a test project without the folder 'testVirPath'.
In my iis, I added a Virtual Directory that pointed to a folder (testVirPath) on a different drive (other than my project or published drive).
I added the necessary permissions and the same user as my published site on the localhost.
I then added some pdf files to the testVirPath folder and published the project to iis.
Try it.
This will list the pdf files stored on the testVirPath folder.
[Home Controller]
public ActionResult Files()
{
ViewBag.TheFiles = GetFiles(Server.MapPath("/testVirPath/"));
return View();
}
private FileInfo[] GetFiles(string path)
{
DirectoryInfo di = new DirectoryInfo(path);
FileInfo[] files = di.GetFiles();
return files;
}
[Files View]
<div>
#foreach (FileInfo f in #ViewBag.TheFiles)
{
<p>#f.FullName</p>
}
</div>
string directoryPath = Server.MapPath("~/competion/pdfFolder/");
try this !!
Kindly Use these code for pdf upload.
if (fuDoc.HasFile)
{
string ext = "";
string fnm = Path.GetFileName(fuDoc.PostedFile.FileName).ToLower();
ext = Path.GetExtension(fuDoc.PostedFile.FileName).ToLower();
if ((ext != ".doc") & (ext != ".pdf") & (ext != ".docx"))
{
Page.ClientScript.RegisterStartupScript(GetType(), "msgbox", "alert('Please select .doc or .pdf or .docx files only');", true);
fuDoc.Focus();
return;
}
fuDoc.PostedFile.SaveAs(Server.MapPath("~/Upload/Documents/") + fuDoc.FileName);
strDoc = "Upload/Documents/" + fuDoc.FileName;
}

How to create and save a temporary file on Microsoft Azure virtual server

I am using a free MS Azure virtual webserver for my site.
On my dev machine I can successfully create a CSV file, save it to a relative temp directory, and then download it to the browser client.
However, when I run it from the Azure site, I get the following error:
System.IO.DirectoryNotFoundException: Could not find a part of the
path 'D:\home\site\wwwroot\temp\somefile.csv'.
Does the free version of Azure Websites block us from saving files to disk? If not, where are we allowed to create/save files that we generate on the fly?
Code Example
private FilePathResult SaveVolunteersToCsvFile(List<Volunteer> volunteers)
{
string virtualPathToDirectory = "~/temp";
string physicalPathToDirectory = Server.MapPath(virtualPathToDirectory);
string fileName = "Volunteers.csv";
string pathToFile = Path.Combine(physicalPathToDirectory, fileName);
StringBuilder sb = new StringBuilder();
// Column Headers
sb.AppendLine("First Name,Last Name,Phone,Email,Approved,Has Background Check");
// CSV Rows
foreach (var volunteer in volunteers)
{
sb.AppendLine(string.Format("{0},{1},{2},{3},{4},{5},{6}",
volunteer.FirstName, volunteer.LastName, volunteer.MobilePhone.FormatPhoneNumber(), volunteer.EmailAddress, volunteer.IsApproved, volunteer.HasBackgroundCheckOnFile));
}
using (StreamWriter outfile = new StreamWriter(pathToFile))
{
outfile.Write(sb.ToString());
}
return File(Server.MapPath(virtualPathToDirectory + "/" + fileName), "text/csv", fileName);
}
Make sure that the ~/temp folder gets published to the server, as it's possible your publish process isn't including it.
Azure Websites provide environment variables that you can use to get to things like a temporary storage folder. For example, there is a "TEMP" variable you could access to get a path to the TEMP folder specific to your Website.
Change line 2 in your method to this:
//string physicalPathToDirectory = Server.MapPath(virtualPathToDirectory);
string physicalPathToDirectory = Environment.GetEnvironmentVariable("TEMP");
Then change the last line to this:
//return File(Server.MapPath(virtualPathToDirectory + "/" + fileName), "text/csv", fileName);
return File(pathToFile, "text/csv", fileName);

couldn't create files in my documents if my documents folder is redirect to another location in setup project

I'm creating a setup project, in the installation, I should create a file in My Documents folder, my code in Commit method looks like this:
base.Commit(savedState);
string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + #"\MyApp";
string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + #"\MyApp\Backup.xml";
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
if (!File.Exists(path))
{
File.Create(path).Close();
}
using (TextWriter file = new StreamWriter(path, true))
{
file.WriteLine("adfasdfafdasdfaf");
}
This works well. But if I redirect My Documents to another location, such as D:\TestFolder, the code couldn't create the file in my new location, and the installation complete successfully. Anyone can help?
Edit:
I found Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) return me a wrong value. In Console Application, this return me a correct value, but in setup project, it return me an empty string.

How to download a file in IIS?

I have written two methods such as FileUpLoad() and FileDownLoad() to Upload and Download a single file in my local system.
void FileUpLoad()
{
string hfBrowsePath = fuplGridDocs.PostedFile.FileName; //fuplGridDocs is a fileupload control
if (hfBrowsePath != string.Empty)
{
string destfile = string.Empty;
string FilePath = Path.Combine(#"E:\Documents\");
FileInfo FP = new FileInfo(hfBrowsePath);
hfFileNameAutoGen.Value = PONumber + FP.Extension;
destfile = FilePath + hfFileNameAutoGen.Value; //hfFileNameAutoGen is a hidden field
fuplGridDocs.PostedFile.SaveAs(destfile);
}
}
void FileDownLoad(LinkButton lnkFileName)
{
string filename = lnkFileName.Text;
string FilePath = Path.Combine(#"E:\Documents", filename);
fuplGridDocs.SaveAs(FilePath);
FileInfo fileToDownLoad = new FileInfo(FilePath);
if (fileToDownLoad.Exists)
{
Process.Start(fileToDownLoad.FullName);
}
else
{
lblMessage.Text = "File Not Saved!";
return;
}
}
While running the application before hosting it in IIS, I can upload a file to the desired location and can also retrieve a file from the saved location. But after publishing it in the localhost, I can only Upload a file. I could not download the saved file. There is no exception too. The Uploaded file is saved in the desired location. I don't know why it is not retrieving the file? Why I cant download the file in IIS? I have searched a lot in the internet, but couldn't find the solution. How to solve this? I am using Windows XP and IIS 5.1 version.
How do you expect your Web Application to do a Process.Start when you deploy this site to a server, your just going to be opening pictures on the server, not on the client PC.
I think this will answer your question: http://www.codeproject.com/Articles/74654/File-Download-in-ASP-NET-and-Tracking-the-Status-o
Also the download file is missing a slash after E:\Documents
another option is to add your wildcard to IIS MIME types

Categories

Resources