asp.net generic handler not sending images for the first time - asp.net

I created a generic handler (.ashx) in ASP.Net to load images from database & send it to browser.
I am using a colorbox to display this in a separate page which only has an image control & calls this handler via ImageUrl property.
For the first time, Image is not being shown in the color box. For the subsequent requests, Image is getting shown.
I tried debugging to find that for the subsequent requests browser is not using a round trip but showing from cache.
How do I make it show the first time as well ?
public class DocumentViewer : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string querystring = context.Request.QueryString.ToString();
try
{
if (querystring != null && querystring.Trim().Length == 0)
{
context.Response.ContentType = "text/plain";
context.Response.Write("Error");
context.Response.Write("No");
return;
}
string DocCode = querystring;
DocumentInfoBL bl = new DocumentInfoBL();
DataTable dt = bl.GetDocumentInfo(DocCode);
if (dt.Rows.Count == 0)
{
context.Response.ContentType = "text/plain";
context.Response.Write("Error");
context.Response.Write("No");
return;
}
context.Response.Clear();
context.Response.ClearContent();
context.Response.ClearHeaders();
context.Response.Cache.SetCacheability(HttpCacheability.Public);
context.Response.Cache.SetExpires(DateTime.MinValue);
// context.Response.ContentType = "application/octet-stream";
context.Response.ContentType = MimeMapping.GetMimeMapping(System.IO.Path.GetFileName(dt.Rows[0]["DocumentFileName"].ToString()));
context.Response.AddHeader("content-disposition", "inline; filename=" + System.IO.Path.GetFileName(dt.Rows[0]["DocumentFileName"].ToString()));
context.Response.BinaryWrite((Byte[])dt.Rows[0]["DocumentFile"]);
context.Response.Buffer = false;
context.Response.Flush();
}
catch (Exception ex)
{
context.Response.ContentType = "text/plain";
context.Response.Write("Error");
context.Response.Write("No");
return;
}
}
public bool IsReusable
{
get
{
return false;
}
}
}

Code that works.It is either charset or Buffer.
public void ProcessRequest(HttpContext context)
{
string querystring = context.Request.QueryString.ToString();
try
{
if (querystring != null && querystring.Trim().Length == 0)
{
context.Response.ContentType = "text/plain";
context.Response.Write("Error");
context.Response.Write("No");
return;
}
string DocCode = querystring;
DocumentInfoBL bl = new DocumentInfoBL();
DataTable dt = bl.GetDocumentInfo(DocCode);
if (dt.Rows.Count == 0)
{
context.Response.ContentType = "text/plain";
context.Response.Write("Error");
context.Response.Write("No");
return;
}
context.Response.Clear();
context.Response.ClearContent();
context.Response.ClearHeaders();
context.Response.Cache.SetCacheability(HttpCacheability.Public);
context.Response.Cache.SetExpires(DateTime.MinValue);
context.Response.ContentType = MimeMapping.GetMimeMapping(System.IO.Path.GetFileName(dt.Rows[0]["DocumentFileName"].ToString()));
context.Response.AddHeader("content-disposition", "inline; filename=" + System.IO.Path.GetFileName(dt.Rows[0]["DocumentFileName"].ToString()));
context.Response.Buffer = true;
context.Response.Charset = "";
context.Response.BinaryWrite((Byte[])dt.Rows[0]["DocumentFile"]);
context.Response.Flush();
}
catch (Exception ex)
{
//Manage here
context.Response.ContentType = "text/plain";
context.Response.Write("Error");
context.Response.Write("No");
return;
}
context.Response.End();
}

Related

Missing Loading Image From Database Use Handler.ashx

I use the Handler.ashx to get and display images from database.
But they didn't all display, only 100% after request few times.
I don't know how to solve.
Handler.ashx code:
public void ProcessRequest(HttpContext context)
{
if (context.Request.QueryString["ImageID"] != null)
{
Byte[] bytes;
string _strModelCode = context.Request.QueryString["ImageID"];
try
{
bytes = ModelBLL.GetImage(_strModelCode);
}
catch
{
bytes = null;
}
context.Response.ContentType = "Image/jpg";
if (bytes != null)
{
try
{
context.Response.BinaryWrite(bytes);
}
catch { }
}
context.Response.End();
return;
}
}
Image Loading Code:
foreach (GridViewRow _row in gridDispaly.Rows)
{
Image img = (Image)_row.FindControl("imgModel");
img.ImageUrl = "../Handler.ashx?ImageID=" + _row.Cells[0].Text;
}
Thank you!
Error Loading Image From Database

Grid View Row Data Bound event

I can't run on IIS Server. I write with dynamically create link button in gridvew row data bound and Link button can't redirect access to file server. I only can on visual studio. Please let me know, how to solve it.
protected void GVSample_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.`enter code here`RowType == DataControlRowType.DataRow)
{
string variable = e.Row.Cells[8].Text.ToString();
string[] stringSeparators = { ";" };
string[] result;
result = variable.Split(stringSeparators, StringSplitOptions.None);
foreach (string s in result)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton lb = new LinkButton();
lb.Text = s.ToString() + "<br />";
lb.CommandName = "ApproveVacation";
lb.Command += LinkButton_Command;
e.Row.Cells[8].Controls.Add(lb);
}
}
}
}
protected void LinkButton_Command(object sender, CommandEventArgs e)
{
string val = ((LinkButton)sender).Text;
int row = -1;
int.TryParse(e.CommandArgument as string, out row);
if (row == -1)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "displayalertmessage", "alert('Fail to Open File');", true);
return;
}
GridViewRow gdrow = GridView1.Rows[row];
DataRow dr = ((DataTable)this.GridView1.DataSource).Rows[gdrow.DataItemIndex];
if (e.CommandName == "ApproveVacation")
{
try
{
string username = "Bla";
string password = "bla";
System.Net.NetworkCredential readCredentials = new NetworkCredential(username, password);
string filepath = #"\\192.168.1.100\SAPAttachments\abc";
using (new NetworkConnection(filepath, readCredentials))
{
WebClient User = new WebClient();
string file = ((LinkButton)sender).Text;
string a = #"<br />";
file = file.Replace(a, "");
foreach (var item in file)
{
Byte[] FileBuffer = User.DownloadData(file);
string stringCutted = file.Substring(file.LastIndexOf(".") + 1);
if (stringCutted == "docx" || stringCutted == "DOCX")
{
if (FileBuffer != null)
{
Context.Response.Clear();
FileInfo Sourcefile = new FileInfo(file);
Context.Response.ContentType = "Application/msword";
Context.Response.AppendHeader("Content-Disposition", "inline; filename=" + Sourcefile.Name);
Context.Response.AppendHeader("Content-Length", Sourcefile.Length.ToString());
Context.Response.WriteFile(Sourcefile.FullName);
Context.Response.End();
}
}
if (stringCutted == "pdf" || stringCutted == "PDF")
{
if (FileBuffer != null)
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", FileBuffer.Length.ToString());
Response.BinaryWrite(FileBuffer);
Response.End();
}
}
if (stringCutted == "jpg" || stringCutted == "JPG" || stringCutted == "jpeg" || stringCutted == "JPEG")
{
if (FileBuffer != null)
{
Response.ContentType = "image/jpeg";
Response.AddHeader("content-length", FileBuffer.Length.ToString());
Response.BinaryWrite(FileBuffer);
Response.End();
}
}
}
ScriptManager.RegisterStartupScript(this, this.GetType(), "displayalertmessage", "alert('Success');", true);
}
}
catch
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "displayalertmessage", "alert('Fail to Open File');", true);
}
}
}

bulk data export to excel and download in ashx file

I have an asp.net application in which I have a js file and an ashx file. Here in a download button click Im calling handler file in ajax call and retrieving sql table data in a json formatted string/data table and Im trying to export json formated string/data table to excel/csv file and download it. Please help me to find a solution. (Need a solution which help to export large amount of data and download)
I tried the below code but its not downloading excel file.
public void ProcessRequest(HttpContext context)
{
context.Response.AddHeader("content-disposition", "attachment; filename=FileName.xls");
context.Response.ContentType = "application/csv";
HttpResponse response = context.Response;
string exportContent = ExportToSpreadsheet(JsonStringToDataTable(GetDataFromTable()),'excelfilename');
response.Write(exportContent);
context.Response.End();
}
public DataTable JsonStringToDataTable(string jsonString)
{
DataTable dt = new DataTable();
string[] jsonStringArray = Regex.Split(jsonString.Replace("[", "").Replace("]", ""), "},{");
List<string> ColumnsName = new List<string>();
foreach (string jSA in jsonStringArray)
{
string[] jsonStringData = Regex.Split(jSA.Replace("{", "").Replace("}", ""), ",");
foreach (string ColumnsNameData in jsonStringData)
{
try
{
int idx = ColumnsNameData.IndexOf(":");
string ColumnsNameString = ColumnsNameData.Substring(0, idx - 1).Replace("\"", "");
if (!ColumnsName.Contains(ColumnsNameString))
{
ColumnsName.Add(ColumnsNameString);
}
}
catch (Exception ex)
{
//throw new Exception(string.Format(ex.Message + "Error Parsing Column Name : {0}", ColumnsNameData));
throw ex;
}
}
break;
}
foreach (string AddColumnName in ColumnsName)
{
dt.Columns.Add(AddColumnName);
}
foreach (string jSA in jsonStringArray)
{
string[] RowData = Regex.Split(jSA.Replace("{", "").Replace("}", ""), ",");
DataRow nr = dt.NewRow();
foreach (string rowData in RowData)
{
try
{
int idx = rowData.IndexOf(":");
string RowColumns = rowData.Substring(0, idx - 1).Replace("\"", "");
string RowDataString = rowData.Substring(idx + 1).Replace("\"", "");
nr[RowColumns] = RowDataString;
}
catch (Exception ex)
{
continue;
}
}
dt.Rows.Add(nr);
}
return dt;
}
private static string GetDataFromTable()
{
string returnValue = string.Empty;
var serializer = new JavaScriptSerializer { MaxJsonLength = Int32.MaxValue };
try
{
var result = //get data from sql table;
returnValue = serializer.Serialize(result);
}
catch (Exception e)
{
returnValue = serializer.Serialize(e.Message);
}
return returnValue;
}
public string ExportToSpreadsheet(DataTable table, string name)
{
string res = string.Empty;
try
{
//var resp = Response;
System.Web.HttpResponse resp = System.Web.HttpContext.Current.Response;
resp.Clear();
if (table != null)
{
foreach (DataColumn column in table.Columns)
{
resp.Write(column.ColumnName + ",");
}
}
resp.Write(Environment.NewLine);
if (table != null)
{
foreach (DataRow row in table.Rows)
{
for (int i = 0; i < table.Columns.Count; i++)
{
resp.Write(row[i].ToString().Replace(",", string.Empty) + ",");
}
resp.Write(Environment.NewLine);
}
}
res = "successfully downloaded";
resp.ContentType = "text/csv";
resp.AppendHeader("Content-Disposition", "attachment; filename=" + name + ".csv");
// resp.End();
}
catch(Exception ex)
{
res = ex.Message;
}
return res;
}
Start using a specialized libary like EPPlus. It will create real Excel files.
private void exportToExcel(DataTable dataTable)
{
using (ExcelPackage excelPackage = new ExcelPackage())
{
//create the worksheet
ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.Add("Sheet 1");
//load the datatable into the sheet, with headers
worksheet.Cells["A1"].LoadFromDataTable(dataTable, true);
//send the file to the browser
byte[] bin = excelPackage.GetAsByteArray();
Response.ClearHeaders();
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-length", bin.Length.ToString());
Response.AddHeader("content-disposition", "attachment; filename=\"ExcelDemo.xlsx\"");
Response.OutputStream.Write(bin, 0, bin.Length);
Response.Flush();
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
}

asp.net - download files in specific folder

i'm trying download files that is located in specific folder. I'm using this code, but it gives me an error in Reponse.End(); -> Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack
if (m.Path.EndsWith(".txt"))
{
Response.ContentType = "application/txt";
}
else if (m.Path.EndsWith(".pdf"))
{
Response.ContentType = "application/pdf";
}
else if (m.Path.EndsWith(".docx"))
{
Response.ContentType = "application/docx";
}
else
{
Response.ContentType = "image/jpg";
}
string nameFile = m.Path;
Response.AppendHeader("Content-Disposition", "attachment;filename=" + nameFile);
Response.TransmitFile(Server.MapPath(ConfigurationManager.AppSettings["IMAGESPATH"]) + nameFile);
Response.End();
I also tried Response.Write, but it gives me the same error.
Response.End will throw ThreadAbortException and it's there only for compatibility with old ASP and you should use HttpApplication.CompleteRequest
here is the example :
public class Handler1 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.AppendHeader("Content-Disposition", "attachment;filename=pic.jpg");
context.Response.ContentType = "image/jpg";
context.Response.TransmitFile(context.Server.MapPath("/App_Data/pic.jpg"));
context.ApplicationInstance.CompleteRequest();
}
public bool IsReusable
{
get
{
return false;
}
}
}

database Image not getting displayed asp.net

trying to display an image from database in an image control... third day...no luck so far...
Displaybutton on Employee.aspx
Protected Sub DisplayButton_Click(ByVal sender As Object, ByVal e As EventArgs) Handles DisplayButton.Click
bind()
GridView1.Visible = "True"
If EmployeeIDTextBox.Text = "" Then
MsgBox("Please enter EmployeeID!")
Else
Image1.ImageUrl = "~/HttpHandler.ashx?EmployeeID=" & EmployeeIDTextBox.Text
End If
End Sub
This is the handler:
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
'context.Response.ContentType = "text/plain"
'context.Response.Write("Hello World!")
Dim EmployeeID As Integer
If (Not (context.Request.QueryString("EmployeeID")) Is Nothing) Then
EmployeeID = Convert.ToInt32(context.Request.QueryString("EmployeeID"))
Else
Throw New ArgumentException("No parameter specified")
End If
Dim imageData() As Byte = {}
' get the image data from the database using the employeeId Querystring
context.Response.ContentType = "image/jpeg"
' You can retrieve this also from the database
context.Response.BinaryWrite(imageData)
End Sub
this is the image control (on Employee.aspx) in which i wanna display the image
<asp:Image ID="Image1" runat="server" imageUrl="HttpHandler.ashx?EmployeeID=7" />
got a lotta help... seems wasnt enough...
These can be helpful. Scenario is similar and can be achieved for your situation:
Display image from a datatable in asp:image in code-behind
Showing an image in listview from datatable
This is in c# but will help someone.
public void ProcessRequest(HttpContext context)
{
string querystring = context.Request.QueryString.ToString();
try
{
if (querystring != null && querystring.Trim().Length == 0)
{
context.Response.ContentType = "text/plain";
context.Response.Write("Error");
context.Response.Write("No");
return;
}
string DocCode = querystring;
DataTable dt = GetDocumentInfo(DocCode); //Get Image From Database. I encapsulated it in other method.Implement it,
if (dt.Rows.Count == 0)
{
context.Response.ContentType = "text/plain";
context.Response.Write("Error");
context.Response.Write("No");
return;
}
context.Response.Clear();
context.Response.ClearContent();
context.Response.ClearHeaders();
context.Response.Cache.SetCacheability(HttpCacheability.Public);
context.Response.Cache.SetExpires(DateTime.MinValue);
context.Response.ContentType = MimeMapping.GetMimeMapping(System.IO.Path.GetFileName(dt.Rows[0]["DocumentFileName"].ToString()));
context.Response.AddHeader("content-disposition", "inline; filename=" + System.IO.Path.GetFileName(dt.Rows[0]["DocumentFileName"].ToString()));
context.Response.Buffer = true;
context.Response.Charset = "";
context.Response.BinaryWrite((Byte[])dt.Rows[0]["DocumentFile"]);
context.Response.Flush();
}
catch (Exception ex)
{
context.Response.ContentType = "text/plain";
context.Response.Write("Error");
context.Response.Write("No");
return;
}
context.Response.End();
}

Resources