protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
if (Request.InputStream.Length > 0)
{
using (StreamReader reader = new StreamReader(Request.InputStream))
{
string hexString = Server.UrlEncode(reader.ReadToEnd());
string imageName = DateTime.Now.ToString("dd-MM-yy hh-mm-ss");
string imagePath = string.Format("~/losefound/{0}.png", imageName);
string ItemName = txtItemName.Text;
string Place = txtPlace.Text;
byte[] bytes = ConvertHexToBytes(hexString);
File.WriteAllBytes(Server.MapPath(imagePath), bytes);
string VisitorManagementConnectionString = ConfigurationManager.ConnectionStrings["VisitorManagementConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(VisitorManagementConnectionString))
{
string query = "INSERT INTO LostFound (ItemName, FoundAt, TimeIn, ImageName, ContentType, Data) VALUES(#ItemName, #FoundAt, #TimeIn, #ImageName, #ContentType, #Data);SELECT SCOPE_IDENTITY()";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#ItemName", ItemName);
cmd.Parameters.AddWithValue("#FoundAt", Place);
cmd.Parameters.AddWithValue("#TimeIn", DateTime.Now);
cmd.Parameters.AddWithValue("#ImageName", imageName);
cmd.Parameters.AddWithValue("#ContentType", "image/png");
cmd.Parameters.AddWithValue("#Data", bytes);
con.Open();
Session["CapturedImageId"] = cmd.ExecuteScalar();
con.Close();
}
}
}
}
}
}
private static byte[] ConvertHexToBytes(string hex)
{
byte[] bytes = new byte[hex.Length / 2];
for (int i = 0; i < hex.Length; i += 2)
{
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
}
return bytes;
}
[WebMethod(EnableSession = true)]
public static string GetCapturedImage()
{
string url = string.Empty;
int imageId = Convert.ToInt32(HttpContext.Current.Session["CapturedImageId"]);
string VisitorManagementConnectionString = ConfigurationManager.ConnectionStrings["VisitorManagementConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(VisitorManagementConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT Data FROM LostFound WHERE Id = #Id";
cmd.Parameters.AddWithValue("#Id", imageId);
cmd.Connection = con;
con.Open();
byte[] bytes = (byte[])cmd.ExecuteScalar();
url = "data:image/png;base64," + Convert.ToBase64String(bytes, 0, bytes.Length);
con.Close();
}
}
HttpContext.Current.Session["CapturedImageId"] = null;
return url;
}
protected void btnCapture_Click(object sender, EventArgs e)
{
}
}
The values form the textbox never inserted into the database. only
datetime.now, imageName, contentType and data can be inserted.
should the insert textbox query at btncapture?
Can someone guide me where am I going wrong?
This code should at least be in a button click.
By the time the page_load event is called in the asp.net page event life cycle the TextBoxes will have been cleared.
You're only submitting to DB if it's not a postback.
if (!this.IsPostBack)
Since you're only running this in Page_Load, the textfields will probably not have any user inputs, and is therefore blank. Either you can do it on PostBack.
if (this.IsPostBack)
{
// Do stuff
}
Or, even better, do as Jeremy Thompson suggested and assign an event handler when the user clicks a button. Doing this kind of logic in Page_Load often come back and haunt you later. What happens when some other developer adds an UpdatePanel, or another postback event? Then this code will run at every postback. It will not scale very good. It seems as you already got an event handler for this - btnCapture_Click, I suggest that you use it.
Example:
In your HTML:
<asp:Button ID="Button1" runat="server" onclick="btnCapture_Click" Text="Button" />
And in your CS:
protected void btnCapture_Click(object sender, EventArgs e)
{
if (Request.InputStream.Length > 0)
{
using (StreamReader reader = new StreamReader(Request.InputStream))
{
string hexString = Server.UrlEncode(reader.ReadToEnd());
string imageName = DateTime.Now.ToString("dd-MM-yy hh-mm-ss");
string imagePath = string.Format("~/losefound/{0}.png", imageName);
string ItemName = txtItemName.Text;
string Place = txtPlace.Text;
byte[] bytes = ConvertHexToBytes(hexString);
File.WriteAllBytes(Server.MapPath(imagePath), bytes);
string VisitorManagementConnectionString = ConfigurationManager.ConnectionStrings["VisitorManagementConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(VisitorManagementConnectionString))
{
string query = "INSERT INTO LostFound (ItemName, FoundAt, TimeIn, ImageName, ContentType, Data) VALUES(#ItemName, #FoundAt, #TimeIn, #ImageName, #ContentType, #Data);SELECT SCOPE_IDENTITY()";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#ItemName", ItemName);
cmd.Parameters.AddWithValue("#FoundAt", Place);
cmd.Parameters.AddWithValue("#TimeIn", DateTime.Now);
cmd.Parameters.AddWithValue("#ImageName", imageName);
cmd.Parameters.AddWithValue("#ContentType", "image/png");
cmd.Parameters.AddWithValue("#Data", bytes);
con.Open();
Session["CapturedImageId"] = cmd.ExecuteScalar();
con.Close();
}
}
}
}
}
If you're having trouble binding the button you can take a look at this question.
First, check if you have AutoEventWireup="true" in the declaration of your aspx.
You can also try to manually assigning the delegate.
btnCapture += new EventHandler(btnCapture_Click);
Related
It only can be called once. where did I gone wrong? The second time it executes, no text appears. The Login and Site.Master are two different partial classes. I am kind of confounded on how to solve this.
Login.aspx
public partial class Login : System.Web.UI.Page
{
SqlDataReader dR;
DatabaseMgmt drObj = new DatabaseMgmt();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void submitButton_Click(object sender, EventArgs e)
{
string strEmail, strPwd;
int intShopperID;
strEmail = txtEmail.Text.ToLower();
strPwd = txtPwd.Text.Trim();
string strSqlCmd = "SELECT ShopperID FROM Shopper WHERE Email ="+ "'" + strEmail + "'" + "AND Passwd ="+ "'"+ strPwd + "'";
dR = drObj.ExecuteSelect(strSqlCmd);
if(dR.Read())
{
intShopperID = Convert.ToInt32(Session["ShopperID"]);
Session["ShopperID"]=intShopperID;
Response.Redirect("Default.aspx");
}
else
{
intShopperID = 0;
lblMsg.Text = "Incorrect email or password";
lblMsg.ForeColor = System.Drawing.Color.Red;
}
dR.Close();
}
}
Site.Master
public partial class Site : System.Web.UI.MasterPage
{
DatabaseMgmt dBObj = new DatabaseMgmt();
protected void Page_Load(object sender, EventArgs e)
{
if (Session["ShopperID"] != null)
{
string strSqlCmd;
strSqlCmd = "SELECT Name FROM Shopper WHERE ShopperID = " + Session["ShopperID"];
lblWelcome.Text = "Welcome Eric";
logoutButton.Visible = true;
loginButton.Visible = false;
regButton.Visible = false;
}
else
{
logoutButton.Visible = false;
loginButton.Visible = true;
regButton.Visible = true;
lblWelcome.Text = "";
}
}
Display Welcome Message
First Run
Second Run
database
I did not see where you are reading the ShopperID from the database. Perhaps that is your issue. ???
To address the Parameterisation issue, I think you should consider something more like this:
public int GetShopperID(System.String strEmail, System.String strPwd) {
int result = 0;
string strSqlCmd = "SELECT ShopperID FROM Shopper WHERE Email = #Email AND Passwd = #Passwd";
using (var cmd = new System.Data.SqlClient.SqlCommand(strSqlCmd, new System.Data.SqlClient.SqlConnection(_databaseConnection))) {
cmd.Parameters.Add("#Email", System.Data.SqlDbType.VarChar, 50);
cmd.Parameters.Add("#Passwd", System.Data.SqlDbType.VarChar, 50);
cmd.Parameter["#Email"].Value = strEmail;
cmd.Parameter["#Passwd"].Value = strPwd;
cmd.Connection.Open();
using (var reader = cmd.ExecuteReader()) {
if (reader.Read()) {
result = Convert.ToInt32(reader["ShopperID"]);
}
}
}
return result;
}
First, it appears you close your connection, however you don't have an explicit open connection (unless you didn't include that line by mistake) which on a postback your query won't produce results since the connection is closed after you run it the first time. Second, confirm you don't have your code in a !Page.IsPostBack, which could also cause it not to appear. Finally you can do all that you are trying to do using one datareader instead of opening up two datareaders with this:
string strEmail = txtEmail.Text.ToLower();
string strPwd = txtPwd.Text.Trim();
string conString = ConfigurationManager.ConnectionStrings["YourConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand("SELECT ShopperID, Name FROM Shopper WHERE Email = #Email AND Passwrd = #Passwrd", con))
{
con.Open();
cmd.Parameters.AddWithValue("#Email", strEmail);
cmd.Parameters.AddWithValue("#user_name", strPwd);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (dr.HasRows)
{
if(dr["ShopperID"].ToString() != Session["ShopperID"].ToString())
{
Response.Redirect("~/default.aspx");
}
else if (dr["ShopperID"].ToString() == Session["ShopperID"].ToString())
{
lblWelcome.Text = "Welcome " + dr["Name"].ToString();
}
else
{
lblMsg.Text = "Incorrect email or password";
lblMsg.ForeColor = System.Drawing.Color.Red;
}
}
}
con.Close();
}
}
This also addresses the SQL injection by using Type-Safe SQL Parameters, which was outlined as an issue in other comments.
I have a mysql table called images with MultipleImageID, MultipleImageName, MultipleImageMap and PropertyID (foreign key). The problem I'm having is the actually images seem to duplicate when I upload them but the columns filled with the correct info. Here is an image to better explain.
As you can see the image names are all different as each image should be different but the first image selected seems to upload multiple times. Other times the right image will upload which has confused me as to what was causing this. I am also getting no errors in my code.
Here is my c# for the upload.
protected void Insert(object sender, EventArgs e)
{
string PropertyName = txtName.Text;
string PropertyFeatures = txtPropFeat.Text;
string PropertyLocation = txtPropLoc.Text;
string PropertyInformation = txtPropInfo.Text;
string PropertyNumBeds = txtNumBeds.Text;
string PropertyPrice = txtPrice.Text;
string PropertyType = txtPropType.Text;
long InsertedID;
string constr = ConfigurationManager.ConnectionStrings["realestatedbAddConString"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
{
using (MySqlCommand cmd = new MySqlCommand("INSERT INTO property (PropertyName, PropertyNumBeds, PropertyType, PropertyPrice, PropertyFeatures, PropertyLocation, PropertyInformation, ImageName, ImageMap) VALUES (#PropertyName, #PropertyNumBeds, #PropertyType, #PropertyPrice, #PropertyFeatures, #PropertyLocation, #PropertyInformation, #ImageName, #ImageMap)"))
{
using (MySqlDataAdapter sda = new MySqlDataAdapter())
{
cmd.Parameters.AddWithValue("#PropertyName", PropertyName);
cmd.Parameters.AddWithValue("#PropertyNumBeds", PropertyNumBeds);
cmd.Parameters.AddWithValue("#PropertyPrice", PropertyPrice);
cmd.Parameters.AddWithValue("#PropertyType", PropertyType);
cmd.Parameters.AddWithValue("#PropertyFeatures", PropertyFeatures);
cmd.Parameters.AddWithValue("#PropertyLocation", PropertyLocation);
cmd.Parameters.AddWithValue("#PropertyInformation", PropertyInformation);
string FileName = Path.GetFileName(MainImageUploada.FileName);
MainImageUploada.SaveAs(Server.MapPath("ImagesUploaded/") + FileName);
cmd.Parameters.AddWithValue("#ImageName", FileName);
cmd.Parameters.AddWithValue("#ImageMap", "ImagesUploaded/" + FileName);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
InsertedID = cmd.LastInsertedId;
con.Close();
}
}
}
if (ImageUploada.HasFiles)
{
foreach (var file in ImageUploada.PostedFiles)
{
string FileName1 = Path.GetFileName(ImageUploada.FileName);
ImageUploada.SaveAs(Server.MapPath("ImagesUploaded/") + file.FileName);
using (MySqlConnection con = new MySqlConnection(constr))
{
using (MySqlCommand cmd = new MySqlCommand("INSERT INTO propertyimage(MultipleImageName, MultipleImageMap, PropertyID) VALUES (#MultipleImageName, #MultipleImageMap, #InsertedID); "))
{
using (MySqlDataAdapter sda = new MySqlDataAdapter())
{
cmd.Parameters.AddWithValue("#MultipleImageName", file.FileName);
cmd.Parameters.AddWithValue("#MultipleImageMap", "ImagesUploaded/" + file.FileName);
cmd.Parameters.AddWithValue("#InsertedID", InsertedID);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
}
txtName.Text = "";
txtPropFeat.Text = "";
txtPropInfo.Text = "";
txtPropLoc.Text = "";
txtNumBeds.Text = "";
txtPrice.Text = "";
txtPropType.Text = "";
Label1.Visible = true;
Label1.Text = "Property Added to Database Successfully!";
}
I am lost to whether its my code, database or the images I am using.
You're correctly looping over ImageUploada.PostedFiles, but then you're ignoring that and calling the methods on ImageUploada itself, which will only handle the first file.
So if you upload multiple files, all files saved on the server will be copies of the first file.
You need to change the code to handle each file individually:
foreach (var file in ImageUploada.PostedFiles)
{
string FileName1 = Path.GetFileName(file.FileName);
file.SaveAs(Server.MapPath("ImagesUploaded/") + file.FileName);
// ...
}
i am using datareader at page load to read and store database values in variables, my table includes both nvarchar and image type columns. At page load my 5 images value in database is not read by reader but others are perfectly read.
Byte[] img1 = null;
Byte[] img2 = null;
Byte[] img3 = null;
Byte[] img4 = null;
Byte[] img5 = null;
SqlConnection con = new SqlConnection("Data Source=RAJ-PC\\SQLEXPRESS;Initial Catalog=Finder;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
loadad();
}
}
protected void loadad()
{
SqlCommand cmd = new SqlCommand("sps_addetails", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#ad_id", ad_id);
cmd.Parameters.AddWithValue("#useremail", ses);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
rd_iam.SelectedValue = reader["iam"].ToString();
dd_category.SelectedValue = reader["category"].ToString();
c = Convert.ToInt16(reader["category"].ToString());
dd_subcategory.SelectedValue = reader["subcategory"].ToString();
txt_title.Text = reader["title"].ToString();
txt_description.Text = reader["description"].ToString();
txt_pername.Text = reader["contactname"].ToString();
txt_mobile1.Text = reader["mobile1"].ToString();
txt_mobile2.Text = reader["mobile2"].ToString();
txt_landline1.Text = reader["landline1"].ToString();
txt_landline2.Text = reader["landline2"].ToString();
txt_email1.Text = reader["email1"].ToString();
txt_email2.Text = reader["email2"].ToString();
txt_website.Text = reader["website"].ToString();
dd_country.Text = reader["country"].ToString();
d = Convert.ToInt16(reader["country"].ToString());
dd_state.Text = reader["state"].ToString();
txt_pincode.Text = reader["pincode"].ToString();
txt_address.Text = reader["address"].ToString();
txt_lat.Text = reader["latitude"].ToString();
txt_lon.Text = reader["longitude"].ToString();
img1 = (byte[])reader["image1"];
img2 = (byte[])reader["image2"];
img3 = (byte[])reader["image3"];
img4 = (byte[])reader["image4"];
img5 = (byte[])reader["image5"];
}
con.Close();
}
And stored procedure sps_addetails is
ALTER PROCEDURE [dbo].[sps_addetails]
#ad_id int,
#useremail nvarchar(100)
AS
BEGIN
select * from dbo.tbl_adregister where useremail=#useremail and ad_id=#ad_id
END
aspx
<asp:FileUpload ID="FileUpload1" runat="server" />
update button functionality is (aspx.cs)
Byte[] imgbytes1 = null;
if (FileUpload1.HasFile)
{
HttpPostedFile file1 = FileUpload1.PostedFile;
imgbytes1 = new Byte[file1.ContentLength];
file1.InputStream.Read(imgbytes1, 0, file1.ContentLength);
}
else
{
imgbytes1 = img1;
}
con.Open();
SqlCommand cmd = new SqlCommand("sps_uploadphoto", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#imagedata1", imgbytes1);
cmd.ExecuteNonQuery();
con.Close();
Try first determining the image size, then instantiating the variables, and then use the GetBytes() method:
int index = reader.GetOrdinal("image1");
Int64 size = 0;
try { size = reader.GetBytes(index , 0, null, 0, int.MaxValue); }
catch { size = reader.GetBytes(index, 0, img1, 0, 1); }
img1 = new Byte[size];
reader.GetBytes(index, 0, img1, 0, img1.Length);
... rinse and repeat for images 2 through 5 ...
Let us know if that gets it for you.
Reading image value is different from others...
<img runat="server" id="image1" alt="" src="" height="100" width="100" />
protected void LoadImage1()
{
SqlCommand cmd = new SqlCommand("sps_getimage", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#flag", 1);
cmd.Parameters.AddWithValue("#ad_id", ad_id);
con.Open();
SqlDataReader reader = cmd.ExecuteReader(System.Data.CommandBehavior.SequentialAccess);
if (reader.HasRows)
{
reader.Read();
MemoryStream memory = new MemoryStream();
long startIndex = 0;
const int ChunkSize = 256;
while (true)
{
byte[] buffer = new byte[ChunkSize];
long retrievedBytes = reader.GetBytes(0, startIndex, buffer, 0, ChunkSize);
memory.Write(buffer, 0, (int)retrievedBytes);
startIndex += retrievedBytes;
if (retrievedBytes != ChunkSize)
break;
}
byte[] data = memory.ToArray();
img1 = data;
memory.Dispose();
image1.Src = "data:image/png;base64," + Convert.ToBase64String(data);
}
con.Close();
}
I am developing a winform application in VS 2010 C#.
I have developed a form to insert and update the user details in this.
My Update user form is as below image
![Update User Screen][1]
http://i.stack.imgur.com/iZaAJ.png
And coding to update is
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using Microsoft.VisualBasic;
using System.Drawing.Imaging;
using System.IO;
namespace SampleApplication
{
public partial class UserUpdate : Form
{
public UserUpdate()
{
InitializeComponent();
}
SqlDataAdapter da;
SqlConnection con = new SqlConnection("user id=sa; password=123;initial catalog=Inventory;data source=Aniket-PC");
SqlCommand cmd;
MemoryStream ms;
byte[] photo_array;
DataSet ds;
int rno = 0;
string str;
private void nameTxt_Validating(object sender, CancelEventArgs e)
{
if (nameTxt.Text.Trim().Length == 0)
{
namewarning.Visible = true;
}
else
{
namewarning.Visible = false;
}
}
private void Update_Load(object sender, EventArgs e)
{
contTxt.MaxLength = 10;
retriveData();
retriveImg();
}
void retriveImg()
{
con.Open();
cmd = new SqlCommand("Select Logo from Register where UserName='" + uNameTxt.Text + "'", con);
da = new SqlDataAdapter(cmd);
ds = new DataSet("MyImage");
da.Fill(ds, "MyImage");
DataRow myRow;
myRow = ds.Tables["MyImage"].Rows[0];
photo_array = (byte[])myRow["Logo"];
ms = new MemoryStream(photo_array);
profPic.Image = Image.FromStream(ms);
con.Close();
}
void retriveData()
{
con.Open();
cmd = new SqlCommand("Select * from Register where UserName='"+uNameTxt.Text+"'",con);
SqlDataReader read = cmd.ExecuteReader();
while (read.Read())
{
nameTxt.Text = (read["Name"].ToString());
passTxt.Text = (read["Password"].ToString());
conPassTxt.Text = (read["Password"].ToString());
emailTxt.Text = (read["EmailId"].ToString());
addTxt.Text = (read["Address"].ToString());
contTxt.Text = (read["ContactNo"].ToString());
DORTxt.Text = (read["DOR"].ToString());
validity.Text = "Account Valid till "+(read["Validity"].ToString());
}
read.Close();
con.Close();
}
private void AttachBtn_Click(object sender, EventArgs e)
{
// Open image by OpenFiledialog and show it in PicturBox.
try
{
//filter only image format files.
openFileDialog1.Filter = "jpeg|*.jpg|bmp|*.bmp|all files|*.*";
DialogResult res = openFileDialog1.ShowDialog();
if (res == DialogResult.OK)
{
Image img = new Bitmap(openFileDialog1.FileName);
//inserting image in PicturBox
profPic.Image = img.GetThumbnailImage(127, 128, null, new IntPtr());
openFileDialog1.RestoreDirectory = true;
}
}
catch
{
MessageBox.Show("Cannot upload image");
}
}
private void UpdateBtn_Click_1(object sender, EventArgs e)
{
string DOM = dateTimePicker1.Value.ToShortDateString();
if (namewarning.Visible == true || picError.Visible == true || PassError.Visible == true || emailwarningImg.Visible == true)
{
MessageBox.Show("Please correct the marked fields");
}
else
{
//cmd = new SqlCommand("update Register set (Name,Password,EmailId,Address,ContactNo,Logo,DOM) values('" + nameTxt.Text.Trim() + "','" + passTxt.Text.Trim() + "','" + emailTxt.Text.Trim() + "','" + addTxt.Text.Trim() + "','" + contTxt.Text.Trim() + "',#Logo,'" + DOM+ "')", con);
str = string.Format("update Register set Name='{0}', Password='{1}',EmailID='{2}',Address='{3}',ContactNo='{4}',Logo='{5}',DOU='{6}' where UserName='{7}'", nameTxt.Text.Trim(), passTxt.Text.Trim(), emailTxt.Text.Trim(),addTxt.Text.Trim(), contTxt.Text.Trim(), #"Logo" ,DOM,uNameTxt.Text);
con_photo();
//con.Open();
cmd = new SqlCommand(str, con);
int count= cmd.ExecuteNonQuery();
if (count > 0)
MessageBox.Show("Sucsess");
else
MessageBox.Show("need to work");
}
}
void con_photo()
{
if (profPic.Image != null)
{
ms = new MemoryStream();
profPic.Image.Save(ms, ImageFormat.Jpeg);
byte[] photo_array = new byte[ms.Length];
ms.Position = 0;
ms.Read(photo_array, 0, photo_array.Length);
cmd.Parameters.AddWithValue("#Logo", photo_array);
}
}
when i run the application it executes very well and shows me success message but when i again try to view the update user form it shows below screenshot error
http://i.stack.imgur.com/7z1Rx.png
at retriveImg ()
Please help me with resolution for this..
You're not passing the image bytes to the UPDATE command, but a string containing the word Logo.
Also: PLEASE avoid creating SQL commands using string concatenation or String.Format. Use parameterized queries instead!
Also: Do not use an NVARCHAR field to store the image bytes (unless you create a BASE64 string from them first), but use a VARBINARY or IMAGE column instead.
The problem is in the following line:
str = string.Format("update Register set ... ,Logo='{5}' ...", ..., #"Logo", ...);
As you can see, you're formatting a string, but you don't insert the bytes from the image, but the word "Logo".
Assuming the column Logo was of type IMAGE or VARBINARY, I would write something like this:
byte[] photo_array = null;
if (profPic.Image != null)
{
MemoryStream ms = new MemoryStream();
profPic.Image.Save(ms, ImageFormat.Jpeg);
photo_array = ms.GetBuffer();
}
if (photo_array != null)
{
SqlCommand cmd = new SqlCommand("UPDATE Register SET Logo=#logo", connection);
cmd.Parameters.AddWithValue("#logo", imageBytes);
cmd.ExecuteNonQuery();
}
Maybe I'm wrong but I'll try to do this
photo_array = (byte[])myRow["Logo"];
if photo_array.length.trim()>0
{
ms = new MemoryStream(photo_array);
profPic.Image = Image.FromStream(ms);
}
con.Close();
This error may come when the lenght of the string is 0
Another thing is that you're not saving the image in the database
//C# Code
SqlCommand cmdSelect = new SqlCommand("select ImageValue from table where ID=1", ObjCon);
ObjCon.Open();
byte[] barrImg = (byte[])cmdSelect.ExecuteScalar();
ObjCon.Close();
string strfn = Convert.ToString(DateTime.Now.ToFileTime());
FileStream fs = new FileStream("C:\\Temp\\1.txt", FileMode.CreateNew, FileAccess.Write);
fs.Write(barrImg, 0, barrImg.Length);
fs.Flush();
fs.Close();
// 1.txt file will be created in c:\temp folder
Following are the links which describe connection to MySQL:
http://www.codeproject.com/KB/aspnet/asp_net_and_mysql.aspx
http://www.codeproject.com/KB/aspnet/image_asp.aspx
Here is the code to display image from mysql database:
protected void Page_Load(object sender, EventArgs e)
{
MySqlConnection conn = new MySqlConnection(db);
conn.Open();
string s;
s = Session["t"].ToString();
string commantext = "select img_id,img_file,img_type,img_name from image where img_name='"+s+"'";
// string commantext = "select img_id,img_file,img_type,img_name from image";
// DataSet ds = MySqlHelper.ExecuteDataset(conn, commantext);
MySqlCommand cmd = new MySqlCommand(commantext,conn);
cmd.Parameters.Add("?img_id", MySqlDbType.Int32).Value = s;
// DataTable dt = ds.Tables[0];
DataTable dt = GetData(cmd);
while(dt !=null)
{
Byte[] bytes = (Byte[])dt.Rows[0]["img_file"];
// Byte[] bytes = (Byte[])dt.Rows[1][] ;
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = dt.Rows[0]["img_type"].ToString();
Response.AddHeader("content-disposition", "attachment;filename="
+ dt.Rows[0]["img_name"].ToString());
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
conn.Close();
}
private DataTable GetData(MySqlCommand cmd)
{
DataTable dt = new DataTable();
//String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
MySqlConnection con = new MySqlConnection(db);
MySqlDataAdapter sda = new MySqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
catch
{ return null;
}
finally
{ con.Close();
sda.Dispose();
con.Dispose();
}
}
My code to upload image file to mysql database is as below.
protected void Button1_Click(object sender, EventArgs e)
{
Stream img_strm = File1.PostedFile.InputStream;
int img_len = File1.PostedFile.ContentLength;
string strtype = File1.PostedFile.ContentType;
//code snippet to determine image height and width.
System.Drawing.Image i = System.Drawing.Image.FromStream(img_strm);
int fileheight = int.Parse(i.Width.ToString());
int filewidth = int.Parse(i.Height.ToString());
strname = Text1.Value;
//Session["t"] = strname;
byte[] imgData = new byte[img_len];
int n = img_strm.Read(imgData, 0, img_len);
int result = saveToDb(strname, imgData, strtype);
}
private int saveToDb(string imgName, byte[] imgbin, string imgContenttype)
{
string db = "server=localhost;database=test;uid=root;password=techsoft";
MySqlConnection conn = new MySqlConnection(db);
MySqlCommand cmd = new MySqlCommand("insert into image(img_name,img_file,img_type) values(?img_name,?img_file,?img_type)", conn);
//MySqlParameter param0 = new MySqlParameter("?img_id", MySqlDbType.Int16, 20);
//param0.Value = ;
//cmd.Parameters.Add(param0);
MySqlParameter param0 = new MySqlParameter("?img_name", MySqlDbType.VarChar, 45);
param0.Value = imgName;
cmd.Parameters.Add(param0);
// MySqlParameter param1 = new MySqlParameter("?img_file", MySqlDbType.VarChar, 45);
MySqlParameter param1 = new MySqlParameter("?img_file", MySqlDbType.LongBlob, 10);
param1.Value = imgbin;
cmd.Parameters.Add(param1);
MySqlParameter param2 = new MySqlParameter("?img_type", MySqlDbType.VarChar, 45);
param2.Value = imgContenttype;
cmd.Parameters.Add(param2);
conn.Open();
int num = cmd.ExecuteNonQuery();
conn.Close();
return num;
}
I have used binary writer to display. Can anybody suggest how to display images in fixed dimensions?
I would resize the images on the page being used to display them. Where are they being displayed?
or
I would resize the images at the time they are saved
Assuming your only challenge is to only scale the images(either before uploading or when retrieving them)...here is some code i use to get scaled dimensions for an image (to fit specific fixed dimensions)...you can stick this somewhere in an imaging class
Note that there are many approaches...
public static Size getScaledDimensions( Image img, Int32 maxW, Int32 maxH)
{
//check if image is already within desired dimensions
if (img.Height <= maxH & img.Width <= maxW)
{
Size orgsize = new Size(img.Width, img.Height);
return orgsize; // no need to rescale
}
else //proceed with rescaling
{
int finalH;
int finalW;
//use height/width ratio to determine our new dimensions
double hwRatio = (double)img.Height / (double)img.Width;
int newW = (int) (maxH/ hwRatio);
int newH = (int) (hwRatio * maxW);
//make sure we scale the right dimension
if (newW <= maxW) // scale width
{
finalH = maxH;
finalW = newW;
}
else
{ // scale height
finalH = newH;
finalW = maxW;
}//end if
Size newsize = new Size(finalW, finalH);
return newsize;
}
Thanks for all the support from rip and The_AlienCoder for their answers. I have found out answer to my own query.
We need to use streams to convert binary data from mysql database. Later graphic library should be used to load the streams. In the meantime we need to resize the image according to our need.
protected void Page_Load(object sender, EventArgs e){
//Create connection to mysql database.
MySqlConnection conn = new MySqlConnection(db);
conn.Open();
string s;
s = Session["t"].ToString();
string commantext = "select img_id,img_file,img_type,img_name from image where img_name='"+s+"'";
MySqlCommand cmd = new MySqlCommand(commantext,conn);
cmd.Parameters.Add("?img_id", MySqlDbType.Int32).Value = s;
//create datatable. GetData is a method to fetch the data.
DataTable dt = GetData(cmd);
//Get data from database to bytes.
Byte[] bytes = (Byte[])dt.Rows[0]["img_file"];
//Defining the size to display data.
int outputSize = 100;
if (bytes.Length > 0)
{
// Open a stream for the image and write the bytes into it
System.IO.MemoryStream stream = new System.IO.MemoryStream(bytes, true);
stream.Write(bytes, 0, bytes.Length);
Bitmap bmp = new Bitmap(stream);
Size new_size = new Size();
//resize based on the longer dimension
if (bmp.Width > bmp.Height)
{
new_size.Width = outputSize;
new_size.Height = (int)(((double)outputSize / (double)bmp.Width) * (double)bmp.Height);
}
else
{
new_size.Width = (int)(((double)outputSize / (double)bmp.Height) * (double)bmp.Width);
new_size.Height = outputSize;
}
Bitmap bitmap = new Bitmap(new_size.Width, new_size.Height, bmp.PixelFormat);
Graphics new_g = Graphics.FromImage(bitmap);
new_g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
new_g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
new_g.DrawImage(bmp, -1, -1, bitmap.Width + 1, bitmap.Height + 1);
bmp.Dispose();
bitmap.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
bitmap.Dispose();
new_g.Dispose();
stream.Close();
}
}
private DataTable GetData(MySqlCommand cmd)
{
DataTable dt = new DataTable();
//String strConnString = System.Configuration.ConfigurationManager .ConnectionStrings["conString"].ConnectionString;
MySqlConnection con = new MySqlConnection(db);
MySqlDataAdapter sda = new MySqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
catch
{ return null;
}
finally
{ con.Close();
sda.Dispose();
con.Dispose();
}
}
}