How can I add a picture to a Database using DataBindign - c#

I want to add a picture to a Database using DataBindign but I don't know how to do it .
this is the code i used to load the image:
byte[] imgData;
private void simpleButton5_Click_1(object sender, EventArgs e)
{
try
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
picture.ImageLocation = openFileDialog1.FileName;
imgData = File.ReadAllBytes(openFileDialog1.FileName);
}
}
catch (Exception ex)
{
// Could not load the image - probably related to Windows file system permissions.
XtraMessageBox.Show("Cannot display the image.\n You may not have permission to read the file, or " +
"it may be corrupt.\n\nReported error: " + ex.Message);
}
}

Here is the code how you can read BLOB (in Oracle) files from database. I hope it will help you a bit:
private void ReadFileFromDatabase()
{
byte[] fileData = null;
string selectSql = "SELECT FILE_DATA FROM BLOBTEST WHERE FILE_ID=1";
OracleConnection con = new OracleConnection(conString);
OracleCommand cmd = new OracleCommand(selectSql, con);
try
{
con.Open();
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
fileData = (byte[])reader["FILE_DATA"];
//do your operations with fileData here
}
}
}
finally
{
con.Close();
}
}

Related

C# App - Input string was not in a correct format

I created an app in C# with SQLite Database. When I want to display data from database into a text box, I receive the error: "Input string was not in a correct format".
Here is my code:
public Form1()
{
InitializeComponent();
connectionString = #"Data Source=.\mydb.db;Version =3Integrated Security=True";
}
private void button1_Click(object sender, EventArgs e)
{
using (SQLiteConnection conn = new SQLiteConnection(connectionString))
{
try
{
conn.Open();
if(conn.State == ConnectionState.Open)
{
//MessageBox.Show("Succes!");
SQLiteDataReader reader = null;
SQLiteCommand cmd = new SQLiteCommand("select username from users where id='1'", conn);
reader = cmd.ExecuteReader();
while(reader.Read())
{
textBox1.Text = reader.GetValue(0).ToString();
}
}
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
The code from Microsoft's example is like this:
while (reader.Read())
{
Console.WriteLine(String.Format("{0}", reader[0]));
}
So maybe
while(reader.Read())
{
textBox1.Text = reader[0];
}
That said I would be using the debugger to find out more about the element and what you should display.
Just putting it out there but I would be looking and c# MVC or C# Core with entity framework. It's much easier to interact with a database and something I would encourage.

i am using DigitalPeronsa U ARE U4500. i am facing problem in saving fingerprint into mysql using c#

I am using MySql database and column type is VARBINARY. I am trying to save template into database. Stored successfully but in database it is storing "System.Byte[]" but I want to store the binary data. Can you tell why this is displaying in database? is there in code problem or in database problem?
protected override void Process(DPFP.Sample Sample)
{
base.Process(Sample);
DPFP.FeatureSet features = ExtractFeatures(Sample, DPFP.Processing.DataPurpose.Enrollment);
DPFP.Capture.SampleConversion ToByte = new DPFP.Capture.SampleConversion();
if (features != null) try
{
MakeReport("The fingerprint feature set was created.");
Enroller.AddFeatures(features);
}
finally
{
UpdateStatus();
// Check if template has been created.
switch (Enroller.TemplateStatus)
{
case DPFP.Processing.Enrollment.Status.Ready: // report success and stop capturing
{
OnTemplate(Enroller.Template);
SetPrompt("Click Close, and then click Fingerprint Verification.");
Stop();
MemoryStream fingerprintData = new MemoryStream();
Enroller.Template.Serialize(fingerprintData);
fingerprintData.Position = 0;
BinaryReader br = new BinaryReader(fingerprintData);
byte[] bytes = br.ReadBytes((Int32)fingerprintData.Length);
try
{
MySqlConnection conn = new MySqlConnection("server=localhost;username=root;password=root;database=enroll");
conn.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO reg(reg_temp) VALUES('" + bytes + "')";
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Success!");
}
catch (Exception e)
{
MakeReport(e.Message);
}
break;
}
case DPFP.Processing.Enrollment.Status.Failed: // report failure and restart capturing
{
Enroller.Clear();
Stop();
UpdateStatus();
OnTemplate(null);
Start();
break;
}
}
}
}
You would need to use parameters
using(var cmd = new MySqlCommand("INSERT INTO mssqltable(varbinarycolumn) VALUES (#binaryValue)", conn))
{
cmd.Parameters.Add("#binaryValue", SqlDbType.VarBinary, 8000).Value = bytes;
cmd.ExecuteNonQuery();
}

How do I check a BLOB field has Data or not?

I am working on asp.net with oracle database. I want to print the image of employee which is saved in an old table. I don't even the data type of image saved in the photo field of that table.
I used Image handlers to print the images from newly created table but when I query on old tables the images is not getting printed.
How do I know that is there any image saved in the table?
If there is an image why it's not getting printed?
I'll show you the code for image handler for both the table (NEW , OLD) Image from newly created table is printing very fine but what's the problem in old one.
Can any give me any suggestions ?
Here is my ImgHandler.ashx code ;
public void ProcessRequest (HttpContext context)
{
OracleDataReader rdr = null;
OracleConnection conn = Conn.getConn();
OracleCommand cmd = null;
string ImgType = context.Request.QueryString["typ"].ToString();
try
{
if (ImgType=="edu")//this is working fine
{
cmd = new OracleCommand("select attachment pic from newtbl where lvldcp_code=" + context.Request.QueryString["dcp"] + "and emp_code="+context.Request.QueryString["emp"], conn);
}
else if (ImgType=="profile")
{
cmd = new OracleCommand("select photo pic from oldtbl where emp_code="+context.Request.QueryString["emp"], conn);
}
conn.Open();
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
context.Response.ContentType = "image/jpg";
context.Response.BinaryWrite((byte[])rdr["pic"]);
}
if (rdr != null)
rdr.Close();
}
catch (Exception ex)
{
}
finally
{
if (conn != null)
conn.Close();
}
}
If your queries are returning a blob field value then you could use the OracleBlob class.
public void ProcessRequest (HttpContext context)
{
OracleDataReader rdr = null;
OracleConnection conn = Conn.getConn();
OracleCommand cmd = null;
string ImgType = context.Request.QueryString["typ"].ToString();
try
{
if (ImgType=="edu")//this is working fine
{
cmd = new OracleCommand("select attachment pic from newtbl where lvldcp_code=" + context.Request.QueryString["dcp"] + "and emp_code="+context.Request.QueryString["emp"], conn);
}
else if (ImgType=="profile")
{
cmd = new OracleCommand("select photo pic from oldtbl where emp_code="+context.Request.QueryString["emp"], conn);
}
Byte[] byteArray = null;
OracleBlob blob;
conn.Open();
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
blob = rdr.GetOracleBlob(0);
byteArray = new Byte[blob.Length];
int i = blob.Read(byteArray, 0, System.Convert.ToInt32(blob.Length));
//clob.Length or i > 0 will show if there are bites in the clob or not
}
if (rdr != null)
rdr.Close();
context.Response.ContentType = "image/jpg";
context.Response.BinaryWrite(byteArray);
}
catch (Exception ex)
{
}
finally
{
if (conn != null)
conn.Close();
}
}

Unable to save null value in database even if tables columns set to "allow null"

I am uploading a file into SQL Server using C# windows form application, but user will not always upload the file, if user directly presses save without using OpenFileDialog it should save null in database
My save button code is
private void btnSave_Click(object sender, EventArgs e)
{
try
{
//Read File Bytes into a byte array for attaching file
byte[] FileData = ReadFile(txtpath.Text);
con.Open();
cmd = new SqlCommand("insert into CourierMaster(srno,OriginalPath,FileData)values(" + txtsrNo.Text + ",#OriginalPath, #FileData)", con);
cmd.Parameters.Add(new SqlParameter("#OriginalPath", (object)txtpath.Text));
cmd.Parameters.Add(new SqlParameter("#FileData", (object)FileData));
int n = cmd.ExecuteNonQuery();
if (n > 0)
{
MessageBox.Show("Record for "+txtsrNo.Text+" Inserted Successfully.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
MessageBox.Show("Insertion failed");
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
My Readfile() Function is
byte[] ReadFile(string sPath)
{
//Initialize byte array with a null value initially.
byte[] data = null;
//Use FileInfo object to get file size.
FileInfo fInfo = new FileInfo(sPath);
long numBytes = fInfo.Length;
//Open FileStream to read file
FileStream fStream = new FileStream(sPath, FileMode.Open, FileAccess.Read);
//Use BinaryReader to read file stream into byte array.
BinaryReader br = new BinaryReader(fStream);
//When you use BinaryReader, you need to supply number of bytes to read from file.
//In this case we want to read entire file. So supplying total number of bytes.
data = br.ReadBytes((int)numBytes);
//Close BinaryReader
br.Close();
//Close FileStream
fStream.Close();
return data;
}
I am getting error
“The path is not of a legal form.”
In my ReadFile() function error occurs at this FileInfo fInfo = new FileInfo(sPath); line of code, I know we cannot assign a null to a path, But does it means I can’t save null in my database if it is a path?
Following is snap of my application:
Following is snap of my table:
You should use the debugger and place a breakpoint on the line
FileInfo fInfo = new FileInfo(sPath);
You'll see that the value of sPath is something that isn't a valid path, and moving in the debugger callstack window to the method calling ReadFile you will be able to see what line created the problem (One of the path in your db is " ." or something like that that isn't a valid path).
Yes you can do many things in conditional blocks,
instead of if (txtpath.Text == "") you can also use if (txtpath.Text == null)
Before passing insert query I checked whether txtpath.Text is null or not, If it is null than I am not passing OriginalPath and FileData, Here is the code..
private void btnSave_Click(object sender, EventArgs e)
{
try
{
if (txtpath.Text == "")
{
con.Open();
cmd = new SqlCommand("insert into CourierMaster(srno)values(" + txtsrNo.Text +")", con);
}
else
{
byte[] FileData = ReadFile(txtpath.Text);
con.Open();
cmd = new SqlCommand("insert into CourierMaster(srno, OriginalPath,FileData)values(" + txtsrNo.Text + ",#OriginalPath, #FileData)", con);
cmd.Parameters.Add(new SqlParameter("#OriginalPath", (object)txtpath.Text));
cmd.Parameters.Add(new SqlParameter("#FileData", (object)FileData));
}
int n = cmd.ExecuteNonQuery();
if (n > 0)
{
MessageBox.Show("Record for "+txtsrNo.Text+" Inserted Successfully.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
MessageBox.Show("Insertion failed");
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}

Getting error after updating image in Sql server 2008 database

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

Categories