Hi guys,
I have recently been teacing myself .NET C# and i am currently working on a project to create an ecommerce site just as a learning experience more than anything.
I have created most of the site already however i have came accross with creating the product list (Gallery).
I would like to have a list of the products in my database to show on the screen with an image of each product. I have tried to do this several ways with no success. Below shows how my database is set out and also shows the code i am using. The problem i am having is showing the images of each product. I think the reason the image is not showing is due to the fact that i am creating the
Microsoft SQL Server
[U][B]Database:[/B][/U]
[B]Product[/B]
Product_id - Numeric
name - Varchar
Descr - Varchar
Price - Varchar
Quantity - Numeric
Brand - Varchar
Gender - Varchar
Image - Image
[U][B]Code:[/B][/U]
[B]Products.aspx.cs[/B]
[CODE]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.IO;
namespace WebApplication1
{
public partial class Products : System.Web.UI.Page
{
string connectionString =
WebConfigurationManager.ConnectionStrings["Test_1"].ConnectionString;
#region LoadProducts
protected void Page_Load(object sender, EventArgs e)
{
/* SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Product", conn);
DataTable dt = new DataTable();
da.Fill(dt);
conn.Close();
listView.DataSource = dt;
listView.DataBind(); */
lblResult.Text = "";
// Create a Select statement that searches for a record
// matching the specific author ID from the Value property.
string selectSQL;
selectSQL = "SELECT * FROM Product ";
selectSQL += "WHERE Gender=@Gender";
// Define the ADO.NET objects.
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataReader reader;
cmd.Parameters.AddWithValue("@Gender ", lstProducts.Text);
// Try to open database and read information.
try
{
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
// Build a string with the record information,
// and display that in a label.
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("");
sb.Append(reader["name"]);
sb.Append("
");
sb.Append("Description: ");
sb.Append(reader["Descr"]);
sb.Append("
");
sb.Append("Price: ");
sb.Append(reader["Price"]);
sb.Append("
");
sb.Append("Quantity: ");
sb.Append(reader["Quantity"]);
sb.Append("
");
sb.Append("Brand: ");
sb.Append(reader["Brand"]);
sb.Append("
");
sb.Append("Gender: ");
sb.Append(reader["Gender"]);
sb.Append("
sb.Append("
");
sb.Append("
");
lblResult.Text += sb.ToString();
}
reader.Close();
}
catch (Exception err)
{
lblResult.Text = "Error getting author. ";
lblResult.Text += err.Message;
}
finally
{
con.Close();
}
}
#endregion
#region Fill_Dropdown
private void FillProductList()
{
string selectSQL = "SELECT name, Price, Product_id FROM Product";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataReader reader;
// Try to open database and read information.
try
{
con.Open();
reader = cmd.ExecuteReader();
// For each item, add the author name to the displayed
// list box text, and store the unique ID in the Value property.
while (reader.Read())
{
ListItem newItem = new ListItem();
newItem.Text = reader["name"] + ", " + reader["Price"];
newItem.Value = reader["Product_id"].ToString();
lstProducts.Items.Add(newItem);
}
reader.Close();
}
catch (Exception err)
{
lblResult.Text = "Error reading list of names. ";
lblResult.Text += err.Message;
}
finally
{
con.Close();
}
}
#endregion
}
}
[/CODE]
[B]ImgHandler.ashx[/B]
[CODE]using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.IO;
using System.Configuration;
namespace WebApplication1
{
///
/// Summary description for ImgHandler
///
public class ImgHandler : IHttpHandler
{
string connectionString =
WebConfigurationManager.ConnectionStrings["Test_1"].ConnectionString;
public void ProcessRequest(HttpContext context)
{
Int32 prodno;
if (context.Request.QueryString["id"] != null)
prodno = Convert.ToInt32(context.Request.QueryString["id"]);
else
throw new ArgumentException("No parameter specified");
context.Response.ContentType = "image/jpeg";
Stream strm = ShowProdImage(prodno);
byte[] buffer = new byte[4096];
int byteSeq = strm.Read(buffer, 0, 4096);
while (byteSeq > 0)
{
context.Response.OutputStream.Write(buffer, 0, byteSeq);
byteSeq = strm.Read(buffer, 0, 4096);
}
//context.Response.BinaryWrite(buffer);
}
public Stream ShowProdImage(int prodno)
{
SqlConnection con = new SqlConnection(connectionString);
string sql = "SELECT Image FROM Product WHERE Product_id = @ID";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@ID", prodno);
con.Open();
object img = cmd.ExecuteScalar();
try
{
return new MemoryStream((byte[])img);
}
catch
{
return null;
}
finally
{
con.Close();
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}[/CODE]
Any help would be appreciated.
Thanks Boldonglen
Javeed M ShaikhPosted Nov 10, 2011, 9:39 AM
Good to know that the issue is fixed.
Happy Coding :)
Glen RobsonPosted Nov 10, 2011, 6:26 AM
The reason the code was not working was because i had rows inside my Product table with Null values for the Image column.
This therefore would not work.
I also had to change the
Thanks for all of your help anyway.
Boldonglen
Glen RobsonPosted Nov 8, 2011, 6:59 AM
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.IO;
using System.Configuration;
using System.Data;
namespace WebApplication1
{
public partial class Test : System.Web.UI.Page
{
string connectionString = WebConfigurationManager.ConnectionStrings["Test_1"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
}
public void ProcessRequest(HttpContext context)
{
if (context.Request.QueryString["id"] != null)
{
SqlConnection con = new SqlConnection(connectionString);
string strQuery = "SELECT Image FROM Product WHERE Product_id = @ID";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("@ID", SqlDbType.Int).Value = Convert.ToInt32(context.Request.QueryString["id"]);
con.Open();
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
con.Close();
if (dt != null)
{
Byte[] bytes = (Byte[])dt.Rows[0]["Image"];
context.Response.Buffer = true;
context.Response.Charset = "";
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
context.Response.ContentType = "image/jpeg";
//if you have the filename in the select that would be great,
//Response.AddHeader("content-disposition", "attachment;filename=" + dt.Rows[0]["Name"].ToString());
context.Response.BinaryWrite(bytes);
context.Response.Flush();
context.Response.End();
}
}
}
}
}
I also changed the Products.aspx page to read Test.aspx?id= and when debugging the code from test does not break. So for some reason the code is still not being called? I also checked the source of the page and the
Javeed M ShaikhPosted Nov 8, 2011, 6:46 AM
Glen RobsonPosted Nov 8, 2011, 4:25 AM
I also looked into why the handler was not being called and i am unsure why. My only guess could be that it is not being called because the code behind Products.aspx is dynamically creating the
Javeed M ShaikhPosted Nov 7, 2011, 12:27 PM
Also did you look into why the handler is not getting called?
Glen RobsonPosted Nov 7, 2011, 12:08 PM
<span id="MainContent_lblResult"><b>Denim Trousersb><br /> Description: Blue Trousers<br />Price: £19.50<br />Quantity: 100<br />Brand: Nike<br />Gender: Male<asp:Image ID='1' runat='server' ImageUrl='~/ImgHandler.ashx?id=103' /><br /><br /><b>Shoesb><br /> Description: Red Shoes<br />Price: £7.99<br />Quantity: 10<br />Brand: DKNY<br />Gender: Male<asp:Image ID='2' runat='server' ImageUrl='~/ImgHandler.ashx?id=104' /><br /><br /><b>Tshirtb><br /> Description: Dark Blue Tshirt<br />Price: £30.00<br />Quantity: 120<br />Brand: Elle<br />Gender: Male<asp:Image ID='3' runat='server' ImageUrl='~/ImgHandler.ashx?id=115' /><br /><br /><b>Shortsb><br /> Description: Black Shorts<br />Price: £30.00<br />Quantity: 110<br />Brand: Nike<br />Gender: Male<asp:Image ID='4' runat='server' ImageUrl='~/ImgHandler.ashx?id=116' /><br /><br /><b>Socksb><br /> Description: Black Socks<br />Price: £30.00<br />Quantity: 105<br />Brand: <br />Gender: Male<asp:Image ID='5' runat='server' ImageUrl='~/ImgHandler.ashx?id=117' /><br /><br /><b>Glenb><br /> Description: Pic Test<br />Price: £25.99<br />Quantity: 50<br />Brand: Lacoste<br />Gender: Male<asp:Image ID='6' runat='server' ImageUrl='~/ImgHandler.ashx?id=130' /><br /><br /><b>test2b><br /> Description: pictest2<br />Price: £30.00<br />Quantity: 80<br />Brand: Lacoste<br />Gender: Male<asp:Image ID='7' runat='server' ImageUrl='~/ImgHandler.ashx?id=131' /><br /><br /><b>test3b><br /> Description: pictest4<br />Price: £30.00<br />Quantity: 80<br />Brand: Lacoste<br />Gender: Male<asp:Image ID='8' runat='server' ImageUrl='~/ImgHandler.ashx?id=132' /><br /><br /><b>TestNewb><br /> Description: New Pic Test<br />Price: £30.00<br />Quantity: 80<br />Brand: Lacoste<br />Gender: Male<asp:Image ID='9' runat='server' ImageUrl='~/ImgHandler.ashx?id=323' /><br /><br />span>
Glen RobsonPosted Nov 7, 2011, 12:03 PM
Javeed M ShaikhPosted Nov 7, 2011, 12:02 PM
I see the ID 'test' is having the same name for all the asp:image tag, create a variable and append it to the name and increment that. like this
int varcounter=1;
sb.Append("
varcounter++;
Glen RobsonPosted Nov 7, 2011, 11:54 AM
<span id="MainContent_lblResult"><b>Denim Trousersb><br /> Description: Blue Trousers<br />Price: £19.50<br />Quantity: 100<br />Brand: Nike<br />Gender: Male<asp:Image ID='test' runat='server' ImageUrl='~/ImgHandler.ashx?id=103' /><br /><br /><b>Shoesb><br /> Description: Red Shoes<br />Price: £7.99<br />Quantity: 10<br />Brand: DKNY<br />Gender: Male<asp:Image ID='test' runat='server' ImageUrl='~/ImgHandler.ashx?id=104' /><br /><br /><b>Tshirtb><br /> Description: Dark Blue Tshirt<br />Price: £30.00<br />Quantity: 120<br />Brand: Elle<br />Gender: Male<asp:Image ID='test' runat='server' ImageUrl='~/ImgHandler.ashx?id=115' /><br /><br /><b>Shortsb><br /> Description: Black Shorts<br />Price: £30.00<br />Quantity: 110<br />Brand: Nike<br />Gender: Male<asp:Image ID='test' runat='server' ImageUrl='~/ImgHandler.ashx?id=116' /><br /><br /><b>Socksb><br /> Description: Black Socks<br />Price: £30.00<br />Quantity: 105<br />Brand: <br />Gender: Male<asp:Image ID='test' runat='server' ImageUrl='~/ImgHandler.ashx?id=117' /><br /><br /><b>Glenb><br /> Description: Pic Test<br />Price: £25.99<br />Quantity: 50<br />Brand: Lacoste<br />Gender: Male<asp:Image ID='test' runat='server' ImageUrl='~/ImgHandler.ashx?id=130' /><br /><br /><b>test2b><br /> Description: pictest2<br />Price: £30.00<br />Quantity: 80<br />Brand: Lacoste<br />Gender: Male<asp:Image ID='test' runat='server' ImageUrl='~/ImgHandler.ashx?id=131' /><br /><br /><b>test3b><br /> Description: pictest4<br />Price: £30.00<br />Quantity: 80<br />Brand: Lacoste<br />Gender: Male<asp:Image ID='test' runat='server' ImageUrl='~/ImgHandler.ashx?id=132' /><br /><br /><b>TestNewb><br /> Description: New Pic Test<br />Price: £30.00<br />Quantity: 80<br />Brand: Lacoste<br />Gender: Male<asp:Image ID='test' runat='server' ImageUrl='~/ImgHandler.ashx?id=323' /><br /><br />span>
As you can see: <asp:Image ID='test' runat='server' ImageUrl='~/ImgHandler.ashx?id=323' /> It is formatted correctly and picking up a valid id.
Javeed M ShaikhPosted Nov 7, 2011, 11:49 AM
Glen RobsonPosted Nov 7, 2011, 11:45 AM
Also when i use the code:
This does not bring back an image where as it did before the code change?
Javeed M ShaikhPosted Nov 7, 2011, 11:33 AM
using System;
using System.Collections.Generic;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.IO;
using System.Configuration;
namespace WebApplication1
{
///
/// Summary description for Handler1
///
public class Handler1 : IHttpHandler
{
string connectionString = WebConfigurationManager.ConnectionStrings["Test_1"].ConnectionString;
public void ProcessRequest(HttpContext context)
{
if (context.Request.QueryString["id"] != null)
{
SqlConnection con = new SqlConnection(connectionString);
string strQuery = "SELECT Image FROM Product WHERE Product_id = @ID";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("@ID", SqlDbType.Int).Value = Convert.ToInt32(context.Request.QueryString["id"]);
con.Open();
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
con.Close();
if (dt != null)
{
Byte[] bytes = (Byte[])dt.Rows[0]["Image"];
context.Response.Buffer = true;
context.Response.Charset = "";
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
context.Response.ContentType = "image/jpeg";
//if you have the filename in the select that would be great,
//Response.AddHeader("content-disposition", "attachment;filename=" + dt.Rows[0]["Name"].ToString());
context.Response.BinaryWrite(bytes);
context.Response.Flush();
context.Response.End();
}
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
Glen RobsonPosted Nov 7, 2011, 10:43 AM
context --> I dont think i have ever used this Object before
GetData --> I am unsure how i would write this function?
Response --> I am unsure what you mean by "try httpresponse in system.web namespace."
Javeed M ShaikhPosted Nov 7, 2011, 10:34 AM
GetData --> you can write this function which takes a command object and returns the datatable.
Response --> try httpresponse in system.web namespace.
Glen RobsonPosted Nov 7, 2011, 10:15 AM
if (context.Request.QueryString["id"] != null)
{
string strQuery = "SELECT Image FROM Product WHERE Product_id = @ID";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("@ID", SqlDbType.Int).Value = Convert.ToInt32 (context.Request.QueryString["id"]);
DataTable dt = GetData(cmd);
if (dt != null)
{
Byte[] bytes = (Byte[])dt.Rows[0]["Image"];
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "image/jpeg";
//if you have the filename in the select that would be great, Response.AddHeader("content-disposition", "attachment;filename=" + dt.Rows[0]["Name"].ToString());
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
}
May this have something to do with my Using statements? Am i missing any?
Javeed M ShaikhPosted Nov 7, 2011, 9:40 AM
Glen RobsonPosted Nov 7, 2011, 9:19 AM
And im still unsure where i would need to place that if statement that you have created and what it would replace?
Thanks
Javeed M ShaikhPosted Nov 7, 2011, 8:39 AM
What is meant is if you have file name you can use that in this line like this...
//if you have the filename in the select that would be great,
//Response.AddHeader("content-disposition", "attachment;filename=" + dt.Rows[0]["Name"].ToString());
what is the error and can you paste the modified code again.
Glen RobsonPosted Nov 7, 2011, 5:51 AM
I Tried this however i dont think it has worked. (I may have entered it wrong as i am a little confused on what the code actually does). Also i am a little confused on what you mean by "if you have the filename in the select that would be great" as the files do not have names, they are saved inside the database as images (BLOBS) and they are referenced using the product_id that they are linked to.
Sam HobbsPosted Nov 5, 2011, 1:26 PM
Note that there are many useful articles in this web site, many relevant to your question.
Also, there is a relevant Visual Studio Sample; see Duwamish 7.0 Overview. I don't know for sure that it does what you are asking about but I hope it is worth looking at.
Javeed M ShaikhPosted Nov 4, 2011, 12:04 PM
if (context.Request.QueryString["id"] != null)
{
string strQuery = "SELECT Image FROM Product WHERE Product_id = @ID";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("@ID", SqlDbType.Int).Value = Convert.ToInt32 (context.Request.QueryString["id"]);
DataTable dt = GetData(cmd);
if (dt != null)
{
Byte[] bytes = (Byte[])dt.Rows[0]["Image"];
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "image/jpeg";
//if you have the filename in the select that would be great, Response.AddHeader("content-disposition", "attachment;filename=" + dt.Rows[0]["Name"].ToString());
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
}
}