database Image not getting displayed asp.net - 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();
}

Related

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

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();
}

Exceptional handling in ASP.NET file handler

I am processing PDF/JPG/GIF files using HTTP Handler.
A popup receives a btnId in query string and detects the file extension then calls the handler with btnId and processes the request.
Files are physical stored on server with file names in DB.
When there is an issue with the file like file not found or some error I want an alert to be displayed and opened window to be closed which is not working right now.
I know the reason and that is I am writing the alert into response which will eventually land in either object tag or Image tag.
Can some one please suggest how can this be achieved. Help will be appreciated. Thanks!!!
Public Class ViewHelpContent
Inherits System.Web.UI.Page
'Method that dynamically decides based on file extension which file viewer to render
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim embed As String = String.Empty
Dim count As Integer
Dim fileName As String = String.Empty
Dim extension As String = String.Empty
Try
If Not IsPostBack Then
If Not Request.QueryString("btnId") Is Nothing Then
Dim btnId As String = Request.QueryString("btnId").ToString()
count = GetFileAttachedToButton(btnId, fileName)
extension = Path.GetExtension(fileName)
If extension.ToLower() = ".pdf" Then
embed = "<object id=""objPDFViewer"" data=""{0}{1}"" type=""application/pdf"">"
embed &= "If you are unable to view file, you can download from here"
embed &= " or there is no file available to be viewed."
embed &= "</object>"
ElseIf extension.ToLower() = ".jpeg" OrElse extension.ToLower() = ".jpg" OrElse extension.ToLower() = ".gif" Then
embed = "<img id=""objImgViewer"" src=""{0}{1}"" alt=""No file is available to be viewed."" />"
Else
ClientScript.RegisterStartupScript(Me.GetType(), "alert", "alert('No help content uploaded for this button.');", True)
Return
End If
helpContent.Text = String.Format(embed, ResolveUrl("~/ProcessHelpContent.ashx?btnId="), btnId)
End If
End If
Catch ex As Exception
ExceptionHandler.LogError(ex)
JSHelper.ShowSystemError(Me)
End Try
End Sub
End Class
Public Class ProcessHelpContent
Implements System.Web.IHttpHandler
'Sub that processes the help request and generates the requested content based on button Id
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim btnId As String = String.Empty
Dim fileName As String = String.Empty
Dim contentType As String = String.Empty
Dim outputDir As String = String.Empty
Dim count As Integer
Dim strPath As FileInfo = Nothing
Dim extension As String = String.Empty
Try
If Not context.Request.QueryString("btnId") Is Nothing Then
btnId = context.Request.QueryString("btnId").ToString()
outputDir = ConfigurationManager.AppSettings("HelpContentFilesFolder")
count = GetFileAttachedToButton(btnId, fileName)
strPath = New FileInfo(outputDir & fileName)
If Not String.IsNullOrWhiteSpace(fileName) Then
If File.Exists(strPath.FullName) Then
extension = Path.GetExtension(strPath.FullName)
If context.Request.QueryString("download") = "1" Then
context.Response.AppendHeader("Content-Disposition", Convert.ToString("attachment; filename=") & fileName)
End If
context.Response.Cache.SetCacheability(HttpCacheability.NoCache)
If extension.ToLower() = ".pdf" Then
context.Response.ContentType = "application/pdf"
ElseIf extension.ToLower() = ".jpg" OrElse extension.ToLower() = ".jpeg" Then
context.Response.ContentType = "image/jpeg"
ElseIf extension.ToLower() = ".gif" Then
context.Response.ContentType = "image/gif"
End If
context.Response.TransmitFile(strPath.FullName)
context.Response.Flush()
Else
context.Response.Write("<script>alert('Uploaded help file is missing. Please re-upload or contact administrator.'); window.close();</script>")
End If
Else
context.Response.Write("<script>alert('Uploaded help file is missing. Please re-upload or contact administrator.'); window.close();</script>")
End If
End If
Catch ex As Exception
ExceptionHandler.LogError(ex)
context.Response.Write("<script>alert('Uploaded help file is missing. Please re-upload or contact administrator.'); window.close();</script>")
End Try
End Sub
ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class

Export Gridview to Excel but the whole aspx page exported instead

This is the code. But the Excel file is showing the whole aspx page instead of the gridview.
Protected Sub btnExport_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExport.Click
Try
Response.Clear()
Response.AddHeader("content-disposition", ("attachment;filename=HotelList_" & DateTime.Now.Year.ToString().Trim()) + DateTime.Now.Month.ToString().Trim().PadLeft(2, Convert.ToChar("0")) + DateTime.Now.Day.ToString().Trim().PadLeft(2, Convert.ToChar("0")) & ".xls")
Response.Charset = ""
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = "application/vnd.ms-excel"
Dim stringWrite As New System.IO.StringWriter
Dim htmlWrite As System.Web.UI.HtmlTextWriter = New HtmlTextWriter(stringWrite)
Dim selctedCountry As String = ddlCountry.SelectedItem.Text.ToString()
Dim selCity As String = ddlCity.SelectedItem.Text.ToString()
htmlWrite.Write("<div style='PADDING-RIGHT: 5px; PADDING-LEFT: 5px; PADDING-BOTTOM: 0px; PADDING-TOP: 0px'><h3>HOTEL LIST</h3>")
htmlWrite.Write("<table><tr><td colspan='2'> Country : " & selctedCountry & " </td></tr>")
htmlWrite.Write("<table><tr><td colspan='2'> City : " & selCity & " </td></tr>")
gvHotelMarkup.RenderControl(htmlWrite)
htmlWrite.Write("</div>")
Response.Write(stringWrite.ToString())
Response.End()
Catch ex As Exception
lblErrMessage.Message = ex.Message()
End Try
End Sub
Any idea how to solve this?
Thanks in advance.
I'm not sure what exactly the problem is but when I added this to codebehind it worked perfect
Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
' Confirms that an HtmlForm control is rendered for the specified ASP.NET
' server control at run time.
End Sub
Downoad ClosedXML Library
using ClosedXML.Excel;
using System.IO;
using System.Data;
Protected Sub btnExport_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExport.Click
DataTable dt = new DataTable("GridView_Data");
foreach(TableCell cell in GridView1.HeaderRow.Cells)
{
dt.Columns.Add(cell.Text);
}
foreach (GridViewRow row in GridView1.Rows)
{
dt.Rows.Add();
for (int i=0; i<row.Cells.Count; i++)
{
dt.Rows[dt.Rows.Count - 1][i] = row.Cells[i].Text;
}
}
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(dt);
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=GridView.xlsx");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}

vb.net conversion of c# cast to Literal

I'm trying to use the password recovery using vb. I found the c# code online and am trying to convert it to vb. I'm getting "end of statement expected" error. Can anybody see the issue?
c# code:
protected void validateUserEmail(object sender, LoginCancelEventArgs e)
{
TextBox EmailAddressTB =
((TextBox)PWRecovery.UserNameTemplateContainer.FindControl("EmailAddressTB"));
Literal ErrorLiteral =
((Literal)PWRecovery.UserNameTemplateContainer.FindControl("ErrorLiteral"));
MembershipUser mu = Membership.GetUser(PWRecovery.UserName);
if (mu != null) // The username exists
{
if (mu.Email.Equals(EmailAddressTB.Text)) // Their email matches
{
ProfileCommon newProfile = Profile.GetProfile(PWRecovery.UserName);
HttpCookie appCookie = new HttpCookie("usernameCookie");
appCookie.Value = newProfile.FullName;
appCookie.Expires = DateTime.Now.AddMinutes(3);
Response.Cookies.Add(appCookie);
}
else
{
e.Cancel = true;
ErrorLiteral.Text = "Your username and password do not match";
}
}
else
{
e.Cancel = true;
ErrorLiteral.Text = "No such user found.";
}
}
vb code:
Protected Sub SubmitButton_Click(sender As Object, e As System.EventArgs)
Dim user As MembershipUser = Membership.GetUser(PasswordRecovery1.UserName)
Dim errorLiteral As Literal = (Literal)PasswordRecovery1.UserNameTemplateContainer.FindControl("FailureText")
If (user IsNot Nothing) Then
Dim password As String = user.GetPassword()
EmailPassword(user.Email, password, user.ToString())
Else
errorLiteral.Text = "No such user found."
End If
End Sub
Dim errorLiteral As Literal = (Literal)PasswordRecovery1.UserNameTemplateContainer.FindControl("FailureText")
can be just
Dim errorLiteral As Literal = PasswordRecovery1.UserNameTemplateContainer.FindControl("FailureText")
If you'd prefer, you can also use Ctype(object, type) or DirectCast(object, type) - example:
Dim errorLiteral As Literal = CType(PasswordRecovery1.UserNameTemplateContainer.FindControl("FailureText"), Literal)

Remove Image in excel header after exporting the gidview

Kindly help me on how to remove image in my excel header. I generate the excel using export command using gridview as source data
here is my code
Response.AddHeader("content-disposition", "attachment;filename=" & strFilename & ".xls")
Response.Clear()
Response.Charset = ""
Response.ContentType = "application/vnd.xls"
Dim sw As System.IO.StringWriter = New System.IO.StringWriter()
Dim htw As System.Web.UI.HtmlTextWriter = New System.Web.UI.HtmlTextWriter(sw)
grvData.AllowPaging = False
grvData.AllowSorting = False
PopulateGrid()
grvData.RenderControl(htw)
Response.Write(sw.ToString)
Response.End()
Everything was set -except that one my header had a blank header name because of the image that was now shown - the image is came from gridview (I'm using arrow for asc and desc) - sorry i cant post any image here now
Give this ClearControls method a shot. It should remove any controls from the Grid before exporting:
protected void btnExport_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.Charset = "";
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
this.ClearControls(DataGrid1);
DataGrid1.RenderControl(oHtmlTextWriter);
DataGrid1.GridLines = GridLines.Both;
DataGrid1.Style.Clear();
Response.Write(oStringWriter.ToString());
Response.End();
}
private void ClearControls(Control control)
{
for (int i = control.Controls.Count - 1; i >= 0; i--)
{
ClearControls(control.Controls[i]);
}
if (!(control is TableCell))
{
if (control.GetType().GetProperty("SelectedItem") != null)
{
LiteralControl literal = new LiteralControl();
control.Parent.Controls.Add(literal);
try
{
literal.Text = (string)control.GetType().GetProperty("SelectedItem").GetValue(control, null);
}
catch
{
//do nothing
}
finally
{
control.Parent.Controls.Remove(control);
}
}
else
{
if (control.GetType().GetProperty("Text") != null)
{
LiteralControl literal = new LiteralControl();
control.Parent.Controls.Add(literal);
literal.Text = (string)control.GetType().GetProperty("Text").GetValue(control, null);
control.Parent.Controls.Remove(control);
}
}
}
return;
}

Resources