C# sql data will lost after copy them - c#

i'm created a database(with VS wizard) which contains 2 columns : Id , fData ;; fData type is nvarchar(MAX).
and then i insert a file into with this command :
public void InsertToDB()
{
byte[] data = File.ReadAllBytes(barcodeEXE); //this is an exe file
string base64 = Convert.ToBase64String(data);
mytbl3TableAdapter.Insert(1, base64);
mytbl3TableAdapter.Fill(mydb3DataSet.mytbl3);
//FILE ADDED !
}
now everythings is ok(file added into database with base64string format and we don't need to use those commands to insert file again) problem is here: i will copy the data from database to other folder with this commands :
public void CopyFromDB()
{
con = new SqlConnection();
con.ConnectionString = CnString;
con.Open(); //start
SqlCommand cmd = new SqlCommand("SELECT fData FROM [mytbl3] WHERE Id=1", con);
using (SqlDataReader d = cmd.ExecuteReader())
{
string base64;
base64 = ((string)mydb3DataSet.Tables[0].Rows[0]["fData"]);
byte[] base64byte = Convert.FromBase64String(base64);
mytbl3TableAdapter.Update(mydb3DataSet.mytbl3);
mytbl3TableAdapter.Fill(mydb3DataSet.mytbl3);
SaveFileDialog ofd = new SaveFileDialog(); ofd.Filter = "exe file|*.exe";
if (ofd.ShowDialog() == DialogResult.OK)
{
File.WriteAllBytes(ofd.FileName, base64byte);
System.Threading.Thread.Sleep(3000);
d.Close();
//
}
d.Close();
}
//end
con.Close();
}
the file will copy successfully but data will remove from database!!

The CopyFromDB function looks to be not doing what you intend to:
public void CopyFromDB()
{
con = new SqlConnection();
con.ConnectionString = CnString;
con.Open(); //start
SqlCommand cmd = new SqlCommand("SELECT fData FROM [mytbl3] WHERE Id=1", con);
using (SqlDataReader d = cmd.ExecuteReader())
{
if (d.Read())
{
string base64;
base64 = reader.GetString(d.GetOrdinal("fData"));
byte[] base64byte = Convert.FromBase64String(base64);
SaveFileDialog ofd = new SaveFileDialog(); ofd.Filter = "exe file|*.exe";
if (ofd.ShowDialog() == DialogResult.OK)
{
File.WriteAllBytes(ofd.FileName, base64byte);
System.Threading.Thread.Sleep(3000);
}
}
d.Close();
//end
con.Close();
}
}

Related

Trying to upload image file to database using input from asp.net page getting error

I am trying to upload an image to a mysql database. I upload the image on a asp.net page . But i am getting this error whenever i try to upload the image to the database.
System.FormatException: 'Input string was not in a correct format.'
on the line with this code
MySqlDataReader MyReader2 = MyCommand2.ExecuteReader();
This is the complete code that i tried
protected void upload_files(object sender, EventArgs e)
{
if (FileUpload_UploadFile.HasFile)
{
HttpPostedFile img = FileUpload_UploadFile.PostedFile;
// IMPLEMENT YOUR CODE FOR SAVING THE FILE
Console.Write(img);
Stream stream = img.InputStream;
BinaryReader binaryReader = new BinaryReader(stream);
bytes = binaryReader.ReadBytes((int)stream.Length);
result = System.Text.Encoding.UTF8.GetString(bytes);
myLabel2.Text = "file has been uploaded";
MySqlConnection conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
string sql_command = "Insert INTO Recognized_person1 (Name,Image,Department,Department_id) VALUES (#Name, #Image, #Department, #Department_id )";
conn.Open();
MySqlCommand MyCommand2 = new MySqlCommand(sql_command, conn);
MyCommand2.Parameters.AddWithValue("#Name", MySqlDbType.VarChar).Value = Name.Text;
MyCommand2.Parameters.AddWithValue("#Image", MySqlDbType.Blob).Value = bytes;
MyCommand2.Parameters.AddWithValue("#Department", MySqlDbType.VarChar).Value = Department.Text ;
MyCommand2.Parameters.AddWithValue("#Department_id", MySqlDbType.Int32).Value = Int32.Parse((Department_id1.Text));
//MyCommand2.ExecuteNonQuery();
MySqlDataReader MyReader2 = MyCommand2.ExecuteReader();
while (MyReader2.Read())
{
}
conn.Close();
}
}
Any ideas on how to correct this error ?

Getting ASCII string converted and show on Picturebox

I am using this Topaz Signature Pad and it saves ASCII string upon final signature to the Database. Now i have a Problem i want to get the ASCII string from the database and convert it to an Image and show in a Picturebox Control I have this code below :
private void button4_Click(object sender, EventArgs e)
{
string constring = #"Data Source=DESKTOP-FJBB72F\SQLEXPRESS;Initial Catalog=SignatureCapture;Integrated Security=True";
using (SqlConnection con = new SqlConnection(constring))
{
con.Open();
string sql = "select * from SignTable where id =#id";
using (SqlCommand cm = new SqlCommand(sql, con))
{
cm.Parameters.AddWithValue("#id",textBox1.Text);
try
{
using (SqlDataReader rd = cm.ExecuteReader())
{
if (rd.Read())
{
// byte[] imgData = (byte[])rd["signature"];
byte[] imgData = Convert.FromBase64String(rd["signature"].ToString());
using (MemoryStream ms = new MemoryStream(imgData))
{
System.Drawing.Image image = Image.FromStream(ms);
//image.Save(#"C:\Users\Administrator\Desktop\UserPhoto.jpg");
pictureBox1.Image = image;
}
}
}
}
catch(Exception ex)
{
MessageBox.Show("Error: "+ex.ToString());
}
}
}
}
And i get an Exception at this Line which looks thus :
Question is , How can i go about retrieving an ASCII and displaying on a picturebox?
Edit
SHows error at this Code .. At this line :
private void button4_Click(object sender, EventArgs e)
{
string constring = #"Data Source=DESKTOP-FJBB72F\SQLEXPRESS;Initial Catalog=SignatureCapture;Integrated Security=True";
using (SqlConnection con = new SqlConnection(constring))
{
con.Open();
string sql = "select * from SignTable where id =#id";
using (SqlCommand cm = new SqlCommand(sql, con))
{
cm.Parameters.AddWithValue("#id",textBox1.Text);
try
{
using (SqlDataReader rd = cm.ExecuteReader())
{
if (rd.Read())
{
// byte[] imgData = (byte[])rd["signature"];
//byte[] imgData = Convert.FromBase64String(rd["signature"].ToString());
byte[]imgData = Encoding.ASCII.GetBytes(rd["signature"].ToString());
using (MemoryStream ms = new MemoryStream(imgData))
{
System.Drawing.Image image = Image.FromStream(ms); // Error shows at this Line <------
//image.Save(#"C:\Users\Administrator\Desktop\UserPhoto.jpg");
pictureBox1.Image = image;
}
}
}
}
catch(Exception ex)
{
MessageBox.Show("Error: "+ex.ToString());
}
}
}
}

How to binary data to PDF file ASP.NET MVC

I develop a student information system.I inser the PDF file to the database as a binary for each course.I want users to download this file.Downloading file but not displaying.Where am I doing wrong.
MvcCode
public FileResult FileDownload(Ders not)
{
byte[] byteArray = GetPdfFromDB(not.DersId);
MemoryStream pdfStream = new MemoryStream();
pdfStream.Write(byteArray, 0, byteArray.Length);
pdfStream.Position = 0;
//return new FileStreamResult(pdfStream, "application/pdf");
return File(pdfStream, "application/pdf", "DersNot.pdf");
}
private byte[] GetPdfFromDB(int id)
{
#region
byte[] bytes = { };
using (SqlConnection con = new SqlConnection(#"Server=****;Database=***;UID=***;PWD=***"))
{
con.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT DersNotIcerik FROM Ders WHERE DersId=#Id";
cmd.Parameters.AddWithValue("#Id", id);
cmd.Connection = con;
using (SqlDataReader sdr = cmd.ExecuteReader())
{
if (sdr.HasRows == true)
{
sdr.Read();
bytes = (byte[])sdr["DersNotIcerik"];
}
}
con.Close();
}
}
return bytes;
#endregion
}
View
#Html.ActionLink(item2.DersNotAd, "FileDownload", new { id = item2.DersId })
I solved the problem like this.We can close the subject
public FileResult FileDownload(int id)
{
SqlConnection con = new SqlConnection(#"Server=10UR\MSSQLSERVERR;Database=UniversiteDB;UID=onur;PWD=1234");
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "SELECT DersNotIcerik FROM Ders WHERE DersId=#Id";
cmd.Parameters.AddWithValue("#Id", id);
byte[] binaryData = (byte[])cmd.ExecuteScalar();
return File(binaryData, "application/octet-stream", "DersNot.pdf");
}

Parameter is no valid when convert byte to image c#

I have done inserting image into database and the datatype is image, but when I want to retrieve it, it is very difficult and error will show Parameter is not valid.
public void RetrieveImage()
{
var con = new SqlConnection(Connection.CATAS_LOCAL());
string SQL = "Select Name,Image from dbo.[TestImage] where Name = 'Test1'";
var cmd = new SqlCommand(SQL, con);
con.Open();
SqlDataReader Reader = cmd.ExecuteReader();
Reader.Read();
if (Reader.HasRows)
{
txtAddStaffNric.Text = Reader[0].ToString();
byte[] img = (byte[])(Reader[1]);
MemoryStream ms = new MemoryStream(img);
pictureBox2.Image = Image.FromStream(ms); ** error show at this line
}
con.Close();
}

Retrieve Image from Binary Data in SQL to DataList

I am doing a 3 tier application to retrieve image from sql server which i stored image to binary data in sql, and the problem is i can't retrieve my image from the sql server.
here is my code in DataAccessLayer
public List<Volunteer> VolunteerTRetrieve()
{
List<Volunteer> vList = new List<Volunteer>();
byte[] volunteerProfilePicture;
string volunteerName, volunteerNRIC, volunteerAddress, volunteerEmail, volunteerContact;
string queryStr = "SELECT * FROM TVolunteer Order By VolunteerName";
SqlConnection conn = new SqlConnection(DBconnStr);
SqlCommand cmd = new SqlCommand(queryStr, conn);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
while ((dr.Read()))
{
volunteerName = dr["VolunteerName"].ToString();
volunteerNRIC = dr["VolunteerNRIC"].ToString();
volunteerAddress = dr["VolunteerAddress"].ToString();
volunteerEmail = dr["VolunteerEmail"].ToString();
volunteerContact = dr["VolunteerContact"].ToString();
volunteerProfilePicture = (byte[])dr["VolunteerProfilePicture"];
vList.Add(new Volunteer(volunteerName, volunteerNRIC, volunteerAddress, volunteerEmail, volunteerContact, volunteerProfilePicture));
}
conn.Close();
dr.Dispose();
return vList;
}
in BusinessLogicLayer
public List<Volunteer> RetrieveAllBVolunteer()
{
Volunteer v = new Volunteer();
List<Volunteer> vList = new List<Volunteer>();
vList = v.VolunteerBRetrieve();
return vList;
}
and in PresentationLayer
List<Volunteer> allVolunteer = new List<Volunteer>();
allVolunteer = vBLL.RetrieveAllTVolunteer();
dl_tvolunteer.DataSource = allVolunteer;
dl_tvolunteer.DataBind();
I have also an image handler class
public class ShowImage : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["DBconnStr"].ConnectionString;
SqlConnection conn = new SqlConnection(connStr);
conn.Open();
string queryStr = "SELECT VolunteerProfilePicture FROM TVolunteer WHERE VolunteerNRIC = #NRIC";
SqlCommand cmd = new SqlCommand(queryStr, conn);
cmd.Parameters.Add("#NRIC", SqlDbType.VarChar).Value =
context.Request.QueryString["VolunteerNRIC"];
cmd.Prepare();
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
context.Response.BinaryWrite((byte[])dr["VolunteerProfilePicture"]);
}
Please help, Thankyou!
If you are returning one image you could the following
1. place a PictureBox control on the asp.net webpage
2. define the sql connections //not sure why you are using cmd.prepare
byte[] sqlImage = (byte[])cmd.ExecuteScalar();
MemoryStream memStream = new MemoryStream();
memStream.Write(sqlImage, 0, sqlImage.Length);
Bitmap bit = new Bitmap(memStream);
or if you want to do it a different way
try
{
con = new SqlConnection(constr);
cmd = new SqlCommand("select photopath,Photo from employees where employeeid=14", con);
con.Open();
dr = cmd.ExecuteReader();
while(dr.Read())
{
if (!dr.IsDBNull(1))
{
byte[] photo = (byte[])dr[1];
MemoryStream ms = new MemoryStream(photo);
pictureBox1.Image = Image.FromStream(ms);
}
}
}
catch (Exception ex)
{
dr.Close();
cmd.Dispose();
con.Close();
Response.Write(ex.Message);
}

Categories

Resources