Grid View Row Data Bound event - asp.net

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

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

how can i upload file to server in asp.net

I have 2 pages send.aspx and recive.aspx.
In send.aspx, I have FileUpload and Button that send selected file to recive.aspx page.
In below you can see recive.aspx.cs code in Page_Load
at the end .
How can I send file to this page?
protected void Page_Load(object sender, EventArgs e)
{
string action = Request.Params["action"];
if (action == null)
{
Response.StatusCode = 400;
Response.End();
}
if (action.Equals("upload"))
{
HttpPostedFile file = Request.Files["file"];
if (file != null && file.ContentLength > 0)
{
//string guid = Guid.NewGuid().ToString();
string ext = Path.GetExtension(file.FileName);
//2- Get and check file extension
string[] validExtesions = { ".e", ".jpg", ".gif", ".png", ".rar",
".zip",".3gp",".3gpp",".mp4",".mov",".wmv",".avi", "",".jpeg", ".mp3", ".ogg"};
if (Array.IndexOf(validExtesions, ext.ToLower()) < 0)
{
Response.Write("Invalid file extension!");
Response.End();
}
//3- Get and check file size
long fileSize = file.ContentLength;
fileSize /= 1024;
if (fileSize > 2048000)
{
Response.Write("Fiele size must be < 2GB");
Response.End();
}
//4- Get file name
string fileName = Path.GetFileName(file.FileName);
//5- Check file exist and if (true) generate new name
while (File.Exists(Path.Combine(UploadFolder, fileName)))
fileName = "1" + fileName;
string fname = fileName;
string path = Server.MapPath(Path.Combine(UploadFolder, fname));
file.SaveAs(path);
Response.Write(fname);
Response.End();
}
else
{
Response.StatusCode = 400;
Response.End();
}
}
}

How can I get link to include mailto: in aspx file?

<tr>
<td style="border-bottom: 1px #c7c6c6 solid;">
<strong>
<asp:Label ID="Label6" runat="server" Text="Email:"></asp:Label>
</strong> </td>
<td style="border-bottom: 1px #c7c6c6 solid;">
<asp:HyperLink ID="EmailLink" runat="server"> <asp:Label ID="lblEmail" runat="server"></asp:Label></asp:HyperLink>
</td>
</tr>
Code Behind:
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.DirectoryServices;
using System.Data.SqlClient;
using System.Data;
using System.Text;
using System.Data.OracleClient;
using System.Configuration; //added
public partial class ADdata : System.Web.UI.Page
{
SqlConnection Conn;
DirectoryEntry dirEntry;
protected void Page_Load(object sender, EventArgs e)
{
lblStatus.Text = "";
string connOra =
ConfigurationManager.ConnectionStrings["UNHBannerPRODConnString"].ConnectionString;
//Conn = new SqlConnection(matrixDBConnectString);
//string ADUser = ConfigurationManager.AppSettings["ADUser"];
//string ADPassword = ConfigurationManager.AppSettings["ADPassword"];
//dirEntry = new DirectoryEntry(ADPath, ADUser, ADPassword, AuthenticationTypes.Secure);
string ADPath = ConfigurationManager.AppSettings["ADPath"];
dirEntry = new DirectoryEntry(ADPath);
FillFixed_DeptPhoneNo();
if (!Page.IsPostBack)
{
//-- fill up important phone numbers
//FillFixed_DeptPhoneNo();
string strSQL = "Select distinct(deptname) from UNH_ADDepartments order by deptname";
OracleConnection con = new OracleConnection(connOra);
OracleCommand cmd = new OracleCommand(strSQL, con);
cmd.Connection.Open();
OracleDataReader drfilldd = cmd.ExecuteReader();
//SqlCommand cmdfilldd = new SqlCommand("Select distinct(deptname) from UNH_ADDepartments order by deptname", Conn);
//Conn.Open();
//SqlDataReader drfilldd = cmdfilldd.ExecuteReader();
Dept.DataSource = drfilldd;
Dept.DataTextField = "deptname";
Dept.DataValueField = "deptname";
Dept.DataBind();
Dept.Items.Insert(0, new ListItem("-- Select Department -- ", "-1"));
drfilldd.Dispose();
cmd.Dispose();
con.Close();
con.Dispose();
//Conn.Close();
}
}
public void FillFixed_DeptPhoneNo()
{
//Add important phone numbers into panel pPhoneNo
}
public void FillGrid(string filter)
{
DirectorySearcher search = new DirectorySearcher(dirEntry);
search.Filter = filter;
search.PropertiesToLoad.Add("name");
search.PropertiesToLoad.Add("mail");
search.PropertiesToLoad.Add("department");
search.PropertiesToLoad.Add("title");
SearchResultCollection searchResultCollection = search.FindAll(); //Here FindAll()!
DataTable dataTableResults = new DataTable();
dataTableResults.Columns.Add("NAME");
dataTableResults.Columns.Add("Mail");
dataTableResults.Columns.Add("DEPARTMENT");
dataTableResults.Columns.Add("TITLE");
foreach (SearchResult sr in searchResultCollection)
{
DataRow dataRow = dataTableResults.NewRow();
DirectoryEntry de = sr.GetDirectoryEntry();
dataRow["name"] = de.Properties["Name"].Value;
dataRow["mail"] = de.Properties["mail"].Value;
dataRow["department"] = de.Properties["department"].Value;
dataRow["title"] = de.Properties["title"].Value;
string d = dataRow["Department"].ToString();
if (d == " " || d == "")
{
dataRow["Department"] = null;
}
dataTableResults.Rows.Add(dataRow);
de.Close();
}
if (dataTableResults.Rows.Count > 1)
{
lblFullName.Text = "";
lblDepartment.Text = "";
lblTitle.Text = "";
lblExtension.Text = "";
lblPhone.Text = "";
lblOffice.Text = "";
lbluserPrincipalName.Text = "";
lblEmail.Text = "";
EmailLink.NavigateUrl = "";
lblFax.Text = "";
//Select only rows with non empty email and properly formed name.
//Sort dataTableResults by Department, Name before binding to GridView2.
DataView dataView = new DataView(dataTableResults);
dataView.RowFilter = #"Mail LIKE '%newhaven.edu'
AND Mail NOT LIKE '%0#newhaven.edu'
AND Mail NOT LIKE '%1#newhaven.edu'
AND Mail NOT LIKE '%2#newhaven.edu'
AND Mail NOT LIKE '%3#newhaven.edu'
AND Mail NOT LIKE '%4#newhaven.edu'
AND Mail NOT LIKE '%5#newhaven.edu'
AND Mail NOT LIKE '%6#newhaven.edu'
AND Mail NOT LIKE '%7#newhaven.edu'
AND Mail NOT LIKE '%8#newhaven.edu'
AND Mail NOT LIKE '%9#newhaven.edu'
AND Name NOT LIKE '%0'
AND Name NOT LIKE '%1'
AND Name NOT LIKE '%2'
AND Name NOT LIKE '%3'
AND Name NOT LIKE '%4'
AND Name NOT LIKE '%5'
AND Name NOT LIKE '%6'
AND Name NOT LIKE '%7'
AND Name NOT LIKE '%8'
AND Name NOT LIKE '%9'";
dataView.Sort = "Department ASC, Name ASC";
GridView2.DataSource = dataView; // = dataTableResults;
GridView2.DataBind();
Panel4.Visible = false;
GridView2.Visible = true;
}
else
{
Panel4.Visible = true;
GridView2.Visible = false;
}
} //FillGrid()
protected void btnSearch_Click(object sender, EventArgs e)
{
lblStatus.Text = "";
//btnSearch.Visible = false;
if (txtLastName.Text.Trim() == "" && txtName.Text.Trim() == "" && Dept.SelectedIndex == 0)
{
lblStatus.Text = "Please enter either Firstname or Lastname or Department to search.";
return;
}
try
{
string filter = "(&";
if (txtLastName.Text.Trim().Length > 0)
filter += "(sn=" + txtLastName.Text.Trim() + "*)";
if (txtName.Text.Trim().Length > 0)
filter += "(givenName=" + txtName.Text.Trim() + "*)";
if (Dept.SelectedIndex > 0)
filter += "(department=" + Dept.SelectedValue.Trim() + ")"; //department comes from ddl
filter += ")";
//Response.Write("filter=[" + filter + "]<br/>");
DirectorySearcher dirSearcher = new DirectorySearcher(dirEntry);
dirSearcher.Filter = filter;
SearchResult searchResult = dirSearcher.FindOne();
DirectoryEntry oneDirEntry = searchResult.GetDirectoryEntry();
string v = oneDirEntry.Properties["userAccountControl"].Value.ToString();
if (v == "66050")
{
lblStatus.Text = "This person is not enabled in the System.";
Panel4.Visible = false;
GridView2.Visible = false;
return;
}
UnpackDirectoryEntry(oneDirEntry);
FillGrid(filter);
}
catch (Exception ex)
{
//lblStatus.Text = (ex.Message == null ? "No Record found" : ex.Message);
lblStatus.Text = "No Record found" ; //updated 3/24/2017 AChen. The message is not meaningful to the user
GridView2.Visible = false;
Panel4.Visible = false;
}
} //btnSearch_Click()
public void UnpackDirectoryEntry(DirectoryEntry dirEnt)
{
string FirstName;
string LastName;
if (dirEnt.Properties["givenName"].Value == null)
{
FirstName = "";
}
else
{
FirstName = dirEnt.Properties["givenName"].Value.ToString();
}
if (dirEnt.Properties["sn"].Value == null)
{
LastName = "";
}
else
{
LastName = dirEnt.Properties["sn"].Value.ToString();
lblFullName.Text = FirstName + " " + LastName;
}
if (dirEnt.Properties["department"].Value == null)
{
lblDepartment.Text = "";
}
else
{
string Department = dirEnt.Properties["department"].Value.ToString();
lblDepartment.Text = Department;
}
if (dirEnt.Properties["title"].Value == null)
{
lblTitle.Text = "";
}
else
{
string Title = dirEnt.Properties["title"].Value.ToString();
lblTitle.Text = Title;
}
if (dirEnt.Properties["ipPhone"].Value == null)
{
lblExtension.Text = "";
}
else
{
string Phone = dirEnt.Properties["ipPhone"].Value.ToString();
lblExtension.Text = Phone;
}
if (dirEnt.Properties["physicalDeliveryOfficeName"].Value == null)
{
lblOffice.Text = "";
}
else
{
string Location = dirEnt.Properties["physicalDeliveryOfficeName"].Value.ToString();
lblOffice.Text = Location;
}
if (dirEnt.Properties["mail"].Value == null)
{
lblEmail.Text = "";
EmailLink.NavigateUrl = "";
}
else
{
string Mail = dirEnt.Properties["mail"].Value.ToString();
lblEmail.Text = Mail;
EmailLink.NavigateUrl = Mail;
}
if (dirEnt.Properties["cn"].Value == null)
{
lblFullName.Text = "";
}
else
{
string cn = dirEnt.Properties["cn"].Value.ToString();
lblFullName.Text = cn;
}
if (dirEnt.Properties["streetAddress"].Value == null)
{
lbluserPrincipalName.Text = "";
}
else
{
string building = dirEnt.Properties["streetAddress"].Value.ToString();
lbluserPrincipalName.Text = building;
}
if (dirEnt.Properties["telephoneNumber"].Value == null)
{
lblPhone.Text = "";
}
else
{
string Phone = dirEnt.Properties["telephoneNumber"].Value.ToString();
lblPhone.Text = Phone;
}
if (dirEnt.Properties["facsimiletelephonenumber"].Value == null)
{
lblFax.Text = "";
}
else
{
string fax = dirEnt.Properties["facsimiletelephonenumber"].Value.ToString();
lblFax.Text = fax;
}
}
protected void GridView2_SelectedIndexChanged(object sender, EventArgs e)
{
string EmailID = Convert.ToString(GridView2.SelectedRow.Cells[2].Text);
//DirectoryEntry dirEntry = new DirectoryEntry("LDAP://AD-NHLOCAL-03/OU=UNH Users, OU=UNH, dc= newhaven, dc= local", "Administrator", "AlphAomegA", AuthenticationTypes.Secure);
DirectorySearcher ds = new DirectorySearcher(dirEntry);
ds.Filter = "(mail= " + EmailID + ")"; //use email to identify a person in Active Directory!
SearchResult emailResults = ds.FindOne();
if (emailResults == null)
{
lblStatus.Text = "This entry cannot be selected because email=[" + EmailID + "].";
Panel4.Visible = false;
return;
}
DirectoryEntry employee = emailResults.GetDirectoryEntry();
UnpackDirectoryEntry(employee);
Panel4.Visible = true;
} //GridView2_SelectedIndexChanged()
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onmouseover"] = "this.style.color='#0153a3';this.style.cursor='hand';";
e.Row.Attributes["onmouseout"] = "this.style.color='Black';";
}
}
protected void txtName_TextChanged(object sender, EventArgs e)
{
GridView2.Visible = false;
Panel4.Visible = false;
//btnSearch.Visible = true;
}
protected void txtLastName_TextChanged(object sender, EventArgs e)
{
GridView2.Visible = false;
Panel4.Visible = false;
//btnSearch.Visible = true;
}
protected void Dept_SelectedIndexChanged(object sender, EventArgs e)
{
GridView2.Visible = false;
Panel4.Visible = false;
//btnSearch.Visible = true;
}
protected void btnCancel_Click(object sender, EventArgs e)
{
txtLastName.Text = "";
txtName.Text = "";
Dept.SelectedValue = "-1";
GridView2.Visible = false;
Panel4.Visible = false;
//btnSearch.Visible = false;
}
protected void GridView2_RowCreated(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[2].Visible = false;
}
}
I have a directory being displayed correctly, but would like to have the email clickable as a mailto: The code is being embedded on a page as an iFrame, so its adding the whole directory as a link for example the link appears, but is actually clicking to https://server.com/folder/email#something.com.
Looking at your code, you'd need to change this code:
EmailLink.NavigateUrl = Mail;
To be:
EmailLink.NavigateUrl = "mailto:" + Mail;

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

bind an image in c# using byte array

protected void Button2_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
try
{
string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
string ext = Path.GetExtension(filename);
if (ext == ".png" || ext == ".jpg" || ext == ".jpeg" || ext == ".PNG" || ext == ".JPG" || ext == ".JPEG" || ext == ".gif" || ext == ".GIF")
{
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
Image1.ImageUrl = "data:image/jpeg;base64," +base64String ;
}
else
{
Response.Write("<script>alert('unsupported format of photo file');</script>");
}
}
catch (Exception ex)
{
Response.Write("<script>alert('" + ex.Message + "');</script>");
}
}
}
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
Image1.ImageUrl = "data:image/jpeg;base64," +base64String ;
This code is working well ..
I assume you are trying to display image with base64 string in an System.Web.UI.WebControls.Image.
first, create a client JavaScript function to set src attribute of your <img /> tag:
function setImageData(imageBase64) {
document.getElementById("imageId").src = "data:image/png;base64," + imageBase64;
}
then, Invoke that method by
Response.Write("<script>setImageData("+ base64String +")</script>");
I would recommend you to create ImageHandler (inherited from IHttpHandler), register it in the web.config file, and modify your Button2_Click function:
public void Button2_Click(object sender, EventArgs e)
{
...
Image1.ImageUrl = "URL_TO_IMAGE_HANDLER.jpg";
...
}
You can read about http-handlers here: http://www.codeproject.com/Articles/34084/Generic-Image-Handler-Using-IHttpHandler
This solution is much better than Base64 approach, it's also possible to implement caching support here
See this Tutorial you can use byte array to get images
UPDATE: By the way you should use this function :
string imageDataParsed = imageData.Substring( imageData.IndexOf( ',' ) + 1 );
byte[] imageBytes = Convert.FromBase64String( imageDataParsed );
using ( var imageStream = new MemoryStream( imageBytes, false ) )
{
Bitmap image = new Bitmap( imageStream );
}
Edit
You can convert base64string to image by Image.FromStream. You will need to convert the base64string to stream first.
byte[] imageBytes = Convert.FromBase64String(imgBase64String);
MemoryStream ms1 = new MemoryStream(imageBytes);
Image img = Image.FromStream(ms1);
I have just solved this question..this is the updated code..
protected void Button2_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
try
{
string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
string ext = Path.GetExtension(filename);
if (ext == ".png" || ext == ".jpg" || ext == ".jpeg" || ext == ".PNG" || ext == ".JPG" || ext == ".JPEG" || ext == ".gif" || ext == ".GIF")
{
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
Image1.ImageUrl = "data:image/jpeg;base64," + base64String;
}
else
{
Response.Write("<script>alert('unsupported format of photo file');</script>");
}
}
catch (Exception ex)
{
Response.Write("<script>alert('" + ex.Message + "');</script>");
}
}
}

Resources