displaying an image in ASP.NET - asp.net

How to an image which is retrieved from MYSQL database.
To display a text in textbox we use textbox.TEXT --> We use .TEXT to display text
Likewise how to display an Image retrieved from MYSQL database??
Image1.[___] = dr[0].[_____];
What to be filled in the above blanks??...
I used blob to store image.

You can do it by creating a controller to serve up your image like and then in your view you can just add the call inline:
<img src='<%= Url.Action( "GetImage", "Image", new { id = yourImageIdHere } ) %>' />
public class ImageController
{
public ActionResult GetImage(int id)
{
var image = GetTheRawBinaryImageFromTheDB();
return File(image, "image/jpg" );
}
}

Add a Generic Handler to your Web Forms application and in the ProcessRequest method, you need to query the database for the relevant file/binary data. You would pick the right image via a querystring, usually. The following code shows how you can query the database and return the binary data:
using (DbConnection conn = new DbConnection(connect))
{
if (context.Request.QueryString["id"] != null)
{
DbCommand cmd = new DbCommand(qry, conn);
cmd.Parameters.AddWithValue("", context.Request.QueryString["id"]);
conn.Open();
using (DbDataReader rdr = cmd.ExecuteReader())
{
if (rdr.HasRows)
{
rdr.Read();
context.Response.AddHeader("content-disposition", "attachment; filename=" + rdr["FileName"]);
context.Response.ContentType = rdr["MimeType"].ToString();
context.Response.BinaryWrite((byte[])rdr["Blob"]);
}
}
}
}
You need to change the DbConnection, DbCommand and DbDataReader to the type that your provider likes (Odbc or MySql) and then point the ImageUrl property of your Image control to the HttpHandler:
Image1.ImageUrl = "MyHandler.ashx?id=" + whatever the image id is.

Related

Excel File Upload Working Locally But Not On Azure

Using ASP.net MVC on Azure. As subject states, it's working fine locally but not on Azure. The form renders properly. Upon submitting the form, I get my page header and a message stating "An error occurred while processing your request." I've checked the database and all the fields were carried over properly. I'm not sure what else to use to troubleshoot.
namespace WebApplication12.Controllers
{
[Authorize]
public class DashboardController : Controller
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
OleDbConnection Econ;
// GET: Dashboard
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
string filename = Guid.NewGuid() + Path.GetDirectoryName(file.FileName);
string filepath = "/excel/" + filename;
file.SaveAs(Path.Combine(Server.MapPath("/excel/"), filename));
InsertExcelData(filepath, filename);
ViewBag.Message = "File successfully uploaded.";
return View();
}
private void ExcelConn(string filepath)
{
string constr = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", filepath);
Econ = new OleDbConnection(constr);
}
private void InsertExcelData(string filepath, string filename)
{
string fullpath = Server.MapPath("/excel/") + filename;
ExcelConn(fullpath);
string query = string.Format("Select * from [{0}]", "Sheet1$");
OleDbCommand Ecom = new OleDbCommand(query, Econ);
Econ.Open();
DataSet ds = new DataSet();
OleDbDataAdapter oda = new OleDbDataAdapter(query, Econ);
Econ.Close();
oda.Fill(ds);
DataTable dt = ds.Tables[0];
dt.Columns.Add(new DataColumn("Email", typeof(System.String)));
dt.Columns.Add(new DataColumn("TimeStamp", typeof(System.DateTime)));
foreach (DataRow dr in dt.Rows)
{
dr["Email"] = User.Identity.GetUserId();
dr["TimeStamp"] = DateTime.Now.ToString();
}
SqlBulkCopy objbulk = new SqlBulkCopy(con);
objbulk.DestinationTableName = "Upload";
objbulk.ColumnMappings.Add("Email", "Email");
objbulk.ColumnMappings.Add("TimeStamp", "TimeStamp");
objbulk.ColumnMappings.Add("EmployeeId", "EmployeeId");
objbulk.ColumnMappings.Add("Name", "Name");
objbulk.ColumnMappings.Add("Title", "Title");
objbulk.ColumnMappings.Add("Department", "Department");
objbulk.ColumnMappings.Add("Race", "Race");
objbulk.ColumnMappings.Add("Gender", "Gender");
objbulk.ColumnMappings.Add("AnnualizedBase", "AnnualizedBase");
objbulk.ColumnMappings.Add("AnnualizedTCC", "AnnualizedTCC");
con.Open();
objbulk.WriteToServer(dt);
con.Close();
}
}
}
Thanks!
In a cloud environment you typically don't write to the web server file system. Rather, you save the upload off to blob storage and keep a record of the path where you saved it along with the persisted data record.
Here is an article where the author uses the Storage APIs to send an uploaded image off to a blob. But this is a rather standard challenge to solve with blob storage, so the Microsoft documentation will likely provide enough information for you to make progress. Here is an official Microsoft sample MVC controller that combines MVC and blob storage.

How do I change the format of a specific column in EPPlus?

I've used EPPlus to download my datatable from my website / database to an Excel sheet and the first picture is the result I get. The second picture is what I would like it to be.
Questions:
How do I change the format of my Timestamp to "time"?
Obviously title would still be a string format.
How do I make the width of the columns to match the longest word inside?
So that 80% of the message isn't hidden and you have to drag the column out to read the entire message.
Edit: Completely forgot to add my code...
public ActionResult ExportData()
{
DataTable dataTable = GetData();
using (ExcelPackage package = new ExcelPackage())
{
var ws = package.Workbook.Worksheets.Add("My Sheet");
//true generates headers
ws.Cells["1:1"].Style.Font.Bold = true;
ws.Cells["A1"].LoadFromDataTable(dataTable, true);
ws.Cells[ws.Dimension.Address].AutoFitColumns();
var stream = new MemoryStream();
package.SaveAs(stream);
string fileName = "Log.xlsx";
string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
stream.Position = 0;
return File(stream, contentType, fileName);
}
}
public DataTable GetData()
{
DataTable dt = new DataTable();
if (ModelState.IsValid)
{
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["MySqlConnection"].ConnectionString))
{
using (SqlCommand comm = conn.CreateCommand())
{
comm.Parameters.AddWithValue("#val1", Session["myID"]);
comm.Parameters.AddWithValue("#val2", "%" + Session["mySearchString"] + "%");
comm.CommandText = "SELECT * FROM dbo.Log WHERE CustomerId = #val1 AND Message LIKE #val2";
try
{
conn.Open();
dt.Load(comm.ExecuteReader());
}
catch (SqlException e)
{
throw new Exception(e.ToString());
}
}
}
}
return dt;
}
Just need to set the Numberformat.Format string. Like this:
ws.Column(2).Style.Numberformat.Format = "hh:mm:ss";
If you want to customize the actual just there are plenty of resource online like http://www.ozgrid.com/Excel/excel-custom-number-formats.htm. Or you can just open it in excel, set the format to Custom and experiment with the string.

Error while Image loading from database

I am using a generic handler for loading Image from data bases. Its work fine when when I hardcode the ImageID in the query string when call handler. But it's giving error of different type when I dynamically pass value from query string (from datatable):
ExecuteReader requires an open and available Connection. The connection's current state is open.
OR
Invalid operation. The connection is closed.
Here is the code of handler
public void ProcessRequest(HttpContext context)
{
Int64 id = Convert.ToInt64(context.Request.QueryString["adid"]);
dt = GetRecpDetailsByID(id);
if (dt.Rows.Count > 0)
{
//context.Response.ContentType = "image/jpeg";
context.Response.BinaryWrite((byte[])dt.Rows[0][2]);
}
}
public DataTable GetRecpDetailsByID(Int64 reid)
{
try
{
obj_DB.Open();
obj_sqlcmd = new SqlCommand("GetRecpDetailsByID", obj_DB.GetDBConnection());
obj_sqlcmd.CommandType = CommandType.StoredProcedure;
obj_sqlcmd.Parameters.Add(new SqlParameter("#rid", reid));
obj_sqlda = new SqlDataAdapter();
obj_dt = new DataTable();
obj_sqlda.SelectCommand = obj_sqlcmd;
obj_sqlda.Fill(obj_dt);
return obj_dt;
}
finally
{
obj_DB.Close();
}
}
And here is the HTML and server-side code on ASPX page of call handler
<img id="img2" alt="Image" runat="server" src='<%#"ImageReqHAndler.ashx?adid="+Eval("Reid")%>' width="179" height="148" />
This is shown when a connection object's open method is not called
u need something like:
SqlConnection conn = (SqlConnection)obj_DB.GetDBConnection();
conn.Open();

how to show image from database in asp:image with linq?

This is my table in database :
And I read the database like :
DataClassesDataContext db = new DataClassesDataContext();
usertable thisuser = db.usertables.First(p => p.username == User.Identity.Name);
So, thisuser.picture is a handle to the image. But how can I show it in asp:image control on my page ?
Edit
I save the picture with this code :
DataClassesDataContext db = new DataClassesDataContext();
usertable thisuser = db.usertables.First(p => p.username == User.Identity.Name);
byte[] filebyte = FileUpload1.FileBytes;
System.Data.Linq.Binary fileBinary = new System.Data.Linq.Binary(filebyte);
thisuser.picture = fileBinary;
db.SubmitChanges();
is there something wrong ?
The ASP.NET Image control loosely represents an <img> tag in HTML. As a result you can only get an image into an HTML doocument by setting the URL to the image content you want to embed in the page.
<img src="images/picture.png" />
This means that you need a mechanism to take an HTTP request asking for an image resource, and return a response containing the image binary data.
With ASP.NET Web API this becomes a trivial operation to implement:
public HttpResponseMessage GetImage(string username)
{
DataClassesDataContext db = new DataClassesDataContext();
usertable thisuser = db.usertables.FirstOrDefault(
p => p.username == username);
if (thisuser == null)
{
return new HttpResponseMessage(HttpStatusCode.NotFound));
}
// Create a stream to return to the user.
var stream = new MemoryStream(thisuser.picture.ToArray());
// Compose a response containing the image and return to the user.
var result = new HttpResponseMessage();
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType =
new MediaTypeHeaderValue("image/jpeg");
return result;
}
If you can't use Web API, you'll have to implement an HTTP Handler to do the same job.
In your ASP.NET page, you will have to set the property ImageUrl to the address configured for your controller/handler, including the username as part of the URL.
<asp:Image ImageUrl='<%# GetImage(Eval("IMG_DATA")) %>' />
Above we tell the ASPX engine that we want to take value of column [IMG_DATA], and pass it into method GetImage of the page, which should return a valid image. So, let's implement the method inside our page class:
public string GetImage(object img)
{
return "data:image/jpg;base64," + Convert.ToBase64String((byte[])img);
}
You'll need to create generic handler - lets call it ImageHandler.ashx, and it will be in the root of your web app.
public class ImageHandler : IHttpHandler {
public void ProcessRequest(HttpContext context) {
// here is the tricky part - you don't store image type anywhere (you should)
// assuming jpeg
context.Response.ContentType = "image/jpeg";
DataClassesDataContext db = new DataClassesDataContext();
if (HttpContext.Current.User != null && HttpContext.Current.User.Identity != null) {
var thisuser = db.usertables.First(p => p.username == HttpContext.Current.User.Identity.Name);
if (thisuser != null) {
byte[] buffer = thisuser.picture.ToArray();
context.Response.OutputStream.Write(buffer, 0, buffer.Length);
}
}
}
public bool IsReusable {
get { return false; }
}
}
Then in the page, add:
<asp:Image runat="server" ImageUrl="~/ImageHandler.ashx" />
Few notes:
you should consider caching of the image
you should switch from image sql type to varbinary (http://msdn.microsoft.com/en-us/library/ms187993.aspx)
you should store image mimetype somewhere (if it is jpeg, png, bmp) - preferably in the same table, and server the correct mimetype in the handler
-
if thisuser.picture has a proper path to your image, you can try something like this:
Image im = new Image();
im.ID = "myImg";
im.ImageUrl = thisuser.picture.toString();
this.Controls.Add(im);
I am assuming that you are using web forms (I don't think it makes a difference).
Also, this might require a page refresh. The 'this' is referring to the Page object (in my case).
You can't render it directly using the ASP.NET Image control (or at least not that I'm immediately aware of). Quickly of the top of my head:
Solution 1:
You need some HttpHandler for your images. In your asp:image tag you need an ImageUrl that will be picked up by this specific HttpHandler. There you can write out the image content from the database as bytes using the right MIME type and headers.
Solution 2:
Take a look into embedding data in URLs, perhaps you can write out your image like this and add it to the asp:image ImageUrl like that: https://en.wikipedia.org/wiki/Data_URI_scheme
create ashx page. On it use somthing like this
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "image/jpeg";
Stream strm = new MemoryStream(GetImage(ID));
long length = strm.Length;
byte[] buffer = new byte[length];
int byteSeq = strm.Read(buffer, 0, 2048);
while (byteSeq > 0)
{
context.Response.OutputStream.Write(buffer, 0, byteSeq);
byteSeq = strm.Read(buffer, 0, 2048);
}
}
ON get image method
public static byte[] GetImage(string ImageId)
{
byte[] img = null;
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "USP_SELECT_GLOBAL_METHOD";
cmd.Parameters.AddWithValue("#EVENT", 5);
cmd.Parameters.AddWithValue("#CODE", ImageId);
cmd.Connection = DL_CCommon.Connection();
SqlDataReader dr = null;
dr = cmd.ExecuteReader();
if (dr.Read())
{
img = (byte[])dr[0];
}
dr.Close();
return img;
}
this method return returns the image as ur ID.
on your aspx page..
Image1.ImageUrl = "somthing.ashx?ID="+userImageID;
I hope it will work. as i have found it worked in my own. Thank you

trouble using httphandler to retrieve image url

I am trying to write a httphandler to retrieve image url and later display it on a image control i am using this code but its not working
OleDbConnection mDB = new OleDbConnection(
ConfigurationManager.ConnectionStrings["AccessConnection"].ConnectionString);
mDB.Open();
OleDbCommand cmd = new OleDbCommand("select pProductId from Products where pProductId=" + context.Request.QueryString["ImageID"], mDB);
OleDbDataReader rdr = cmd.ExecuteReader();
rdr.Read();
context.Response.BinaryWrite((byte[])rdr[0]);
mDB.Close();
context.Response.End(); */
sorry that i caused a confusion earlier in the SELECT statement the pProductId does not contain the URL of the image instead pProductImage is the field that contain the URL. i am using the Id to identify which image to display accordingly.
this is my expected output:
<img src="ImgHandler.ashx?pProductId=2" alt="" />
i cant place image this is the link to my error msg:http://imgur.com/Cix67
This is a two steps answer.
In the page, you can do something like this:
using (OleDbConnection mDB = new OleDbConnection(ConfigurationManager.ConnectionStrings["AccessConnection"].ConnectionString))
{
mDB.Open();
using (OleDbCommand cmd = new OleDbCommand("select pProductId from Products where pProductId=" + context.Request.QueryString["ImageID"], mDB))
{
using (OleDbDataReader rdr = cmd.ExecuteReader())
{
rdr.Read();
context.Response.Write("<img src=\"ImgHandler.ashx?pProductId=");
context.Response.Write((int)rdr[0]); // I suppose pProductId is an int, adapt accordingly
context.Response.Write("\" />");
}
}
}
and in the HTTP handler implicitly triggered, something like this:
public class MyHandler : IHttpHandler
{
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
using (OleDbConnection mDB = new OleDbConnection(ConfigurationManager.ConnectionStrings["AccessConnection"].ConnectionString))
{
mDB.Open();
// select the file data (I put pData here as a placeholder, and assume it will be a byte[])
using (OleDbCommand cmd = new OleDbCommand("select pData from Products where pProductId=" + context.Request.QueryString["ImageID"], mDB))
{
using (OleDbDataReader rdr = cmd.ExecuteReader())
{
rdr.Read();
context.Response.ContentType = "image/png";// put the content type here
context.Response.BinaryWrite((byte[])rdr[0]);
}
}
}
}
}
Note the using pattern which ensures proper resources cleanup once used. Also, ideally you could cache the data on the client using proper cache HTTP headers (like if-modified-since) but this is another story ...

Resources