trouble using httphandler to retrieve image url - asp.net

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 ...

Related

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

Populate web form edit page C# ASP.NET

I am trying to select a single row on a gridview and have that selection take me to a separate edit page with the data populated. I have the idea of using a session variable to hold the row id and then retrieving the data on page load and populating the text boxes. My question is whether or not this is the best method to go about doing this? I would prefer to not use the inline edit option in gridview as I have too many columns that would require scrolling horizontally. Here is my page load method using the session variable:
if (Session["editID"] != null)
{
dbCRUD db = new dbCRUD();
Recipe editRecipe = new Recipe();
var id = Convert.ToInt32(Session["editID"]);
Session.Remove("editID");
editRecipe = db.SelectRecord(id);
addName.Text = editRecipe.Name;
}
Here is the SelectRecord method that is used to retrieve the row:
public Recipe SelectRecord(int id)
{
Recipe returnedResult = new Recipe();
var dbConn = new SqlConnection(connString);
var dbCommand = new SqlCommand("dbo.selectRecipe", dbConn);
dbCommand.CommandType = CommandType.StoredProcedure;
dbCommand.Parameters.Add("#ID", SqlDbType.Int).Value = id;
dbConn.Open();
SqlDataReader reader = dbCommand.ExecuteReader();
while (reader.HasRows)
{
while (reader.Read())
{
returnedResult.Name = reader["Name"].ToString();
}
}
dbConn.Close();
return returnedResult;
}
I'm probably not utilizing the SQLDataReader appropriately, but my result is no data in the reader therefore no returned data when calling the method. Any help is appreciated - thanks in advance!
Few things you should be aware of here:
1.
You should use while (reader.HasRows) in case your stored procedure returns multiple resultsets. In that case you have to iterate through the result sets. See Retrieving Data Using a DataReader. So, if selectRecipe returns multiple resultsets (I am assuming this is not the case), change your code to this:
while (reader.HasRows)
{
while (reader.Read())
{
returnedResult.Name = reader["Name"].ToString();
}
reader.NextResult();
}
2.If selectRecipe returns single result set, change the while loop to if(){}:
if(reader.HasRows)
{
while (reader.Read())
{
returnedResult.Name = reader["Name"].ToString();
}
}
3. I would probably use using to manage the connection better (using Statement) :
public Recipe SelectRecord(int id)
{
Recipe returnedResult = new Recipe();
using (SqlConnection dbConn = new SqlConnection(connString))
{
var dbCommand = new SqlCommand("dbo.selectRecipe", dbConn);
dbCommand.CommandType = CommandType.StoredProcedure;
dbCommand.Parameters.AddWithValue("#ID", id);
dbConn.Open();
SqlDataReader reader = dbCommand.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
returnedResult.Name = reader["Name"].ToString();
}
}
reader.Close();
}
return returnedResult;
}

Returning JSON with ASP.NET and $.getJSON

I have a page that connects to the Northwind database to get a list of categories...
protected void Page_Load(object sender, EventArgs e)
{
var cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["cnnString"].ConnectionString);
var cmd = new SqlCommand("SELECT CategoryID, CategoryName FROM Categories ORDER BY CategoryName", cnn);
using (cnn)
{
cnn.Open();
var dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.HasRows)
{
var sb = new StringBuilder();
var sw = new StringWriter(sb);
using (JsonWriter jw = new JsonTextWriter(sw))
{
jw.Formatting = Formatting.Indented;
jw.WriteStartArray();
while (dr.Read())
{
jw.WriteStartObject();
jw.WritePropertyName("CategoryID");
jw.WriteValue(dr.GetInt32(0));
jw.WritePropertyName("CategoryName");
jw.WriteValue(dr.GetString(1));
jw.WriteEndObject();
}
jw.WriteEndArray();
jw.Flush();
Response.Write(sb);
}
}
}
}
This works just as expected. In my calling page I have a dropdownlist and I'm trying to use jQuery to populate it. Maybe I'm doing this wrong. I'm assuming that it takes the entire text from the .aspx file which includes the and strings and causes it to be invalid? If so, what is the correct way to do this, or what is it that I am doing wrong?
$.getJSON('GetCategories.aspx', function (data) {
alert('success!');
$.each(data, function (key, val) {
$('#ddlCategories').append('<option></option>').val(key).html(val);
});
});
The alert never happens so it craps out getting the file. The file name is correct as Chrome Inspector gives me no console errors.
You should look into HttpHandlers, as they have much lower overhead and can be restricted to just the output you want.
I use a HttpHandler as an example in another answer here Accessing Image from App_data folder

displaying an image in 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.

Resources