Long story short,
I want to create button that Print out PDF file to user Computer
So firstly, I create PDF file in server database / file and then I make it downloadable to user.
With this code I can create PDF file in server,
then I searched on how to make it downloadable to user..
So far no luck, most errors said "...is a physical path, but a virtual path was expected."
here's the code
private void cetak_pdf(string s_id, string CompanyCode , string zpath)
{
bool SUCCESS = true;
string sErrMsg = "";
string sFileName = "";
DiskFileDestinationOptions diskOpts = null;
try
{
sFileName = s_id;
diskOpts = new DiskFileDestinationOptions();
diskOpts.DiskFileName = Server.MapPath("~" + "\\pdf\\" + zpath + CompanyCode + "_" + sFileName + ".pdf");
//Response.Write(diskOpts.DiskFileName);Response.End();
// this is the file created E:\GIA_25\pdf\CompanyAddress00000003_003.pdf
rptDoc.ExportOptions.ExportFormatType = ExportFormatType.PortableDocFormat;
rptDoc.ExportOptions.ExportDestinationType = ExportDestinationType.DiskFile;
rptDoc.ExportOptions.DestinationOptions = diskOpts;
rptDoc.Export();
Response.ContentType = "application/pdf";
//Response.AppendHeader("Content-Disposition", "attachment; filename=MyFile.pdf");
Response.TransmitFile(Server.MapPath("E:\\GIA_25\\pdf\\CompanyAddress00000003_003.pdf"));
Response.End();
}
catch (Exception ex)
{
SUCCESS = false;
sErrMsg = ex.Message;
throw new Exception(sErrMsg);
}
}
help please, kinda new in this language
Sorry my fault :( here is the right code for make it downloadable
Response.ContentType = "APPLICATION/OCTET-STREAM";
// String Header = "Attachment; Filename=XMLFile.xml";
String Header = "Attachment; Filename=" + "CompanyAddress" + CompanyCode + "_" + sFileName + ".pdf";
Response.AppendHeader("Content-Disposition", Header);
System.IO.FileInfo Dfile = new System.IO.FileInfo(Server.MapPath("~" + "\\pdf\\" + "CompanyAddress" + CompanyCode + "_" + sFileName + ".pdf"));
Response.WriteFile(Dfile.FullName);
Related
I am trying to download sql back up file but getting error :
"Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack" near respone.end()
protected void btnDownload_Click(object sender, EventArgs e)
{
try
{
string backupDestination = backupPath;
string dbNAme = dbName;
string dateStamp = DateTime.Now.ToString("yy-MM-dd#HHmm");
string backupfile = backupDestination + '\\' + dbNAme + " of " + dateStamp + ".bak";
DataTable dt = blu.queryFunction("BACKUP database " + dbNAme + " to disk='" + backupDestination + "\\" + dbNAme + " of " + dateStamp + ".Bak'");
WebClient req = new WebClient();
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.ClearContent();
response.ClearHeaders();
response.Buffer = true;
response.AddHeader("content-disposition", "attachment; filename= " + dbNAme + ".bak");
byte[] data = req.DownloadData(backupfile);
response.ContentType = "application/sql";
response.BinaryWrite(data);
response.End();
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "alertscipt", "swal('Error!','Database Backup Failed." + ex.ToString() + "','warning')", true);
}
}
One issue that I see is the buffer - change the response.Buffer = true; to false
response.Buffer = false;
for big files this is wrong because its put it on a buffer but you want to send it direct to the user...
also remove the catch (Exception ex) to see other problems on your code - the ScriptManager.RegisterStartupScript is not run from the moment you have change the headers. So the issue is hidden from you.
One other better and more correct way is to create a handler and download the file from there.
If the backup file is present on the server running the application, you shouldn't be using a WebClient. Something that reads the file from local disk, e.g. TransmitFile(), would then be sufficient - like this:
string backupDestination = backupPath;
string dbNAme = dbName;
string dateStamp = DateTime.Now.ToString("yy-MM-dd#HHmm");
string backupfile = backupDestination + '\\' + dbNAme + " of " + dateStamp + ".bak";
DataTable dt = blu.queryFunction("BACKUP database " + dbNAme + " to disk='" + backupDestination + "\\" + dbNAme + " of " + dateStamp + ".Bak'");
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.ClearContent();
response.ClearHeaders();
response.Buffer = true;
response.AddHeader("content-disposition", "attachment; filename= " + dbNAme + ".bak");
response.ContentType = "application/octet-stream";
response.TransmitFile(backupfile);
response.Flush();
ok so after 72 hours i have found the error. the download button was inside update panel so i was getting "Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack"
protected void btnDownload_Click(object sender, EventArgs e)
{
try
{
string dbNAme = dbName;
string backupDestination = Server.MapPath("~/BackUp");
string dateStamp = DateTime.Now.ToString("yyyy-MM-dd#HH_mm");
string fileName = dbName + " of " + dateStamp + ".Bak";
if (!Directory.Exists(backupDestination))
{
Directory.CreateDirectory(backupDestination);
}
DataTable dt = blu.queryFunction("BACKUP database " + dbNAme + " to disk='" + backupDestination + "\\" + fileName + "'");
byte[] bytes = File.ReadAllBytes(Path.Combine(backupDestination, fileName));
// Delete .bak file from server folder.
if (Directory.Exists(backupDestination))
{
Directory.Delete(backupDestination, true);
}
Response.Clear();
Response.Buffer = false;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
catch(Exception ex)
{
string exception = ex.ToString();
}
}
protected void DownloadFile(object sender, EventArgs e)
{
string param = Request.QueryString["id"];
//int id = int.Parse((sender as LinkButton).CommandArgument);
//byte[] bytes;
string fileName;
SqlCommand cd = DbCon._dbConnection.CreateCommand();
cd.CommandType = CommandType.Text;
cd.CommandText = "select id from student_registration where id = '" + param + "'";
cd.ExecuteNonQuery();
SqlCommand cmd = DbCon._dbConnection.CreateCommand();
cmd.CommandText = "select books_pdf from books where id = '" + param + "'";
// cmd.Parameters.AddWithValue("#Id", param);
String s1 = cmd.ExecuteScalar().ToString();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
sdr.Read();
//bytes = (byte[])sdr["Data"];
//contentType = sdr["ContentType"].ToString();
fileName = sdr["books_pdf"].ToString();
}
Response.Clear();
Response.Buffer = true;
Response.Charset = "/";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
//Response.ContentType = contentType;
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName );
//Response.AppendHeader("Content-Disposition", "attachment; filename=" +fileName);
// Response.TransmitFile(Server.MapPath("~/Files/"+ fileName));
// Response.WriteFile(file.FullName);
Response.Flush();
Response.End();
}
This is the code where I have written to download the file. but the result what am getting correct file but '/' is replaced with 'underscore;
My question is how to remove that underscore and add '/' in place of underscore I have attached the image please check that and please help me in finding the solutionenter image description here
enter image description here
image shows the path stored in database and error what I am facing to download
fileName = "../librarian/" + sdr["books_pdf"].ToString();
}
WebClient req = new WebClient();
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.ClearContent();
response.ClearHeaders();
response.Buffer = true;
response.AddHeader("Content-Disposition", "attachment;filename=\"" + Server.MapPath(fileName) + "\"");
byte[] data = req.DownloadData(Server.MapPath(fileName));
response.BinaryWrite(data);
response.End();
Proper Selection of File was not given later i corrected proper file location than i got proper output
currently i want to generate the report without showing in reportviewer. I search for the solution online but i only can find the MVC approach. I cant convert it to normal webform behavior.
public ActionResult Report(string id)
{
LocalReport lr = new LocalReport();
string path = Path.Combine(Server.MapPath("~/Report"), "ReportStateArea.rdlc");
if (System.IO.File.Exists(path))
{
lr.ReportPath = path;
}
else
{
return View("Index");
}
List<StateArea> cm = new List<StateArea>();
using (PopulationEntities dc = new PopulationEntities())
{
cm = dc.StateAreas.ToList();
}
ReportDataSource rd = new ReportDataSource("MyDataset", cm);
lr.DataSources.Add(rd);
string reportType = id;
string mimeType;
string encoding;
string fileNameExtension;
string deviceInfo =
"<DeviceInfo>" +
" <OutputFormat>" + id + "</OutputFormat>" +
" <PageWidth>8.5in</PageWidth>" +
" <PageHeight>11in</PageHeight>" +
" <MarginTop>0.5in</MarginTop>" +
" <MarginLeft>1in</MarginLeft>" +
" <MarginRight>1in</MarginRight>" +
" <MarginBottom>0.5in</MarginBottom>" +
"</DeviceInfo>";
Warning[] warnings;
string[] streams;
byte[] renderedBytes;
renderedBytes = lr.Render(
reportType,
deviceInfo,
out mimeType,
out encoding,
out fileNameExtension,
out streams,
out warnings);
return File(renderedBytes, mimeType);
}
enter code here
Here is the sample of code that can allow user to generate the report in different format such as PDF, excel, image. ( http://www.dotnetawesome.com/2013/09/microsoft-report-in-mvc-4.html ).
Anyone can help or provide me a website which have a simple tutorial of that by using the SQL select statement instead of LINQ ?
As far as returning the report from a WebForms page, what you have above is actually pretty close. You want to return the renderedBytes array through the Response object of your current Page context like:
protected void ReportPrint_Click(object sender, EventArgs e)
{
string id = "PDF"; // get this from another control on your page
LocalReport lr = new LocalReport();
string path = Path.Combine(Server.MapPath("~/Report"), "ReportStateArea.rdlc");
if (System.IO.File.Exists(path))
{
lr.ReportPath = path;
}
else
{
// handle error condition
}
List<StateArea> cm = new List<StateArea>();
using (PopulationEntities dc = new PopulationEntities())
{
cm = dc.StateAreas.ToList();
}
ReportDataSource rd = new ReportDataSource("MyDataset", cm);
lr.DataSources.Add(rd);
string reportType = id;
string mimeType;
string encoding;
string fileNameExtension;
string deviceInfo =
"<DeviceInfo>" +
" <OutputFormat>" + id + "</OutputFormat>" +
" <PageWidth>8.5in</PageWidth>" +
" <PageHeight>11in</PageHeight>" +
" <MarginTop>0.5in</MarginTop>" +
" <MarginLeft>1in</MarginLeft>" +
" <MarginRight>1in</MarginRight>" +
" <MarginBottom>0.5in</MarginBottom>" +
"</DeviceInfo>";
Warning[] warnings;
string[] streams;
byte[] renderedBytes;
renderedBytes = lr.Render(
reportType,
deviceInfo,
out mimeType,
out encoding,
out fileNameExtension,
out streams,
out warnings);
Response.Clear(); // we're going to override the default page response
Response.ContentType = mimeType;
Response.AddHeader("content-disposition", "attachment; filename=report." + fileNameExtension);
Response.BinaryWrite(renderedBytes);
Response.End();
}
This will replace the normal page response with your report content.
As far as SQL vs Linq, the DataSource object that ReportViewer uses is the old-style System.Data.DataTable so just look for information on populating a DataTable from SQL.
I am facing a strange problem.
I have a web page(Filelibrary.aspx) to download some word/pdf files, I can download the files from local machine and direct link from my local pc. but we have a server and we are usualy accessing the site by login into the server as remote desktop. If we try to download word/pdf files from remort desk top it is downloading the web page "Filelibrary.aspx" instead of the word/pdf. we are using https. I could able to download it before when it was http.
my code:
String strFile = String.Empty;
String[] filename;
strFile = Server.MapPath(ConfigurationManager.AppSettings["TemplatePath"].ToString()) + FileName;
filename = strFile.Split('\\');
Response.Clear();
Response.Buffer = true;// Read the original file from diskFileStream *
Response.AddHeader("Content-Disposition", "attachment; filename=" + filename[filename.Length-1]);
String ext = String.Empty;
if (strFile.IndexOf(".") > 0)
ext = (strFile.Split('.'))[1];
if (ext.ToLower() == "txt")
Response.ContentType = "text/html";
if (ext.ToLower() == "xls")
Response.ContentType = "xls/html";
if (ext.ToLower() == "pdf")
Response.ContentType = "application/pdf";
////combine the path and file name
if (File.Exists(strFile))//open the file and process it
{
FileStream sourceFile = new FileStream(strFile, FileMode.Open, FileAccess.Read);
long FileSize;
FileSize = sourceFile.Length;
Response.AddHeader("Content-Length", FileSize.ToString()); //*
byte[] getContent = new byte[(int)FileSize];
sourceFile.Read(getContent, 0, (int)FileSize);
sourceFile.Close();
Response.BinaryWrite(getContent);
}
Common.UserPageAudit(Session["User"].ToString(), "Download Templates", Session["ROLE"].ToString(), strFile + " Template downloaded");
Can anyone help me to resolve this strange issue..?
Thanks you friends...
at last I found the Problem.
I was not clearing the Header.. I have changed my code as below.
String strFile = String.Empty;
String[] filename;
strFile = Server.MapPath(ConfigurationManager.AppSettings["TemplatePath"].ToString()) + FileName;
filename = strFile.Split('\\');
// Added these two line
HttpContext.Current.Response.Cache.SetNoServerCaching();
Response.ClearHeaders();
Response.Clear();
Response.Buffer = true;// Read the original file from diskFileStream *
Response.AddHeader("Content-Disposition", "attachment; filename=" + filename[filename.Length-1]);
String ext = String.Empty;
if (strFile.IndexOf(".") > 0)
ext = (strFile.Split('.'))[1];
if (ext.ToLower() == "txt")
Response.ContentType = "text/html";
if (ext.ToLower() == "xls")
Response.ContentType = "xls/html";
if (ext.ToLower() == "pdf")
Response.ContentType = "application/pdf";
////combine the path and file name
if (File.Exists(strFile))//open the file and process it
{
FileStream sourceFile = new FileStream(strFile, FileMode.Open, FileAccess.Read);
long FileSize;
FileSize = sourceFile.Length;
Response.AddHeader("Content-Length", FileSize.ToString()); //*
byte[] getContent = new byte[(int)FileSize];
sourceFile.Read(getContent, 0, (int)FileSize);
sourceFile.Close();
Response.BinaryWrite(getContent);
}
Common.UserPageAudit(Session["User"].ToString(), "Download Templates", Session["ROLE"].ToString(), strFile + " Template downloaded");
I am using this code to download a excel file which exist in my solution. I have added a folder FileUpload and added a excel file UploadCWF.xlsx. My code is workin in local host. But not working when I host this to server.I am getting error - Could not find a part of the path. My code -
string filePath = HttpContext.Current.Server.MapPath("~/FileUpload/");
string _DownloadableProductFileName = "UploadCWF.xlsx";
System.IO.FileInfo FileName = new System.IO.FileInfo(filePath + "\\" + _DownloadableProductFileName);
FileStream myFile = new FileStream(filePath + "\\" + _DownloadableProductFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
//Reads file as binary values
BinaryReader _BinaryReader = new BinaryReader(myFile);
//Check whether file exists in specified location
if (FileName.Exists)
{
try
{
long startBytes = 0;
string lastUpdateTiemStamp = File.GetLastWriteTimeUtc(filePath).ToString("r");
string _EncodedData = HttpUtility.UrlEncode(_DownloadableProductFileName, Encoding.UTF8) + lastUpdateTiemStamp;
Response.Clear();
Response.Buffer = false;
Response.AddHeader("Accept-Ranges", "bytes");
Response.AppendHeader("ETag", "\"" + _EncodedData + "\"");
Response.AppendHeader("Last-Modified", lastUpdateTiemStamp);
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName.Name);
Response.AddHeader("Content-Length", (FileName.Length - startBytes).ToString());
Response.AddHeader("Connection", "Keep-Alive");
Response.ContentEncoding = Encoding.UTF8;
//Send data
_BinaryReader.BaseStream.Seek(startBytes, SeekOrigin.Begin);
//Dividing the data in 1024 bytes package
int maxCount = (int)Math.Ceiling((FileName.Length - startBytes + 0.0) / 1024);
//Download in block of 1024 bytes
int i;
for (i = 0; i < maxCount && Response.IsClientConnected; i++)
{
Response.BinaryWrite(_BinaryReader.ReadBytes(1024));
Response.Flush();
}
}
catch (Exception es)
{
throw es;
}
finally
{
Response.End();
_BinaryReader.Close();
myFile.Close();
}
}
else
System.Web.UI.ScriptManager.RegisterStartupScript(this, GetType(),
"FileNotFoundWarning", "alert('File is not available now!')", true);
Please some one help me.
You should first concat filepath and filename then get path using server.mappath.
You should write code like this
string filePath = HttpContext.Current.Server.MapPath("~/FileUpload/UploadCWF.xlsx");
System.IO.FileInfo FileName = new System.IO.FileInfo(filePath);