So I've created this image uploader following a tutorial. The problem is that i did all of it in the frame. Now i want to make it MVC. I've created classes for Controller and Dataaccesslayer. Can someone help me get started?
Regards William
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 System.IO;
namespace ImageSaveToSQLServer
{
public partial class Form1 : Form
{
SqlConnection conn = new SqlConnection("server=localhost; Trusted_Connection=yes; database=ImageDataBase");
SqlCommand command;
string imgLoc = "";
public Form1()
{
InitializeComponent();
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void buttonBrowse_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif|All Files (*.*)|*.*";
dlg.Title = "Select Employee Picture";
if(dlg.ShowDialog() == DialogResult.OK)
{
imgLoc = dlg.FileName.ToString();
picEmp.ImageLocation = imgLoc;
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void buttonSave_Click(object sender, EventArgs e)
{
try {
byte[] img = null;
FileStream fs = new FileStream(imgLoc, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
img = br.ReadBytes((int)fs.Length);
string sql = "INSERT INTO Employee(EID,FIRST_NAME,LAST_NAME,IMAGE)VALUES("+textBoxEID.Text+",'"+textBoxFNAME.Text+"','"+textBoxLname.Text+"',#img)";
if (conn.State != ConnectionState.Open)
conn.Open();
command = new SqlCommand(sql, conn);
command.Parameters.Add(new SqlParameter("#img",img));
int x = command.ExecuteNonQuery();
conn.Close();
MessageBox.Show(x.ToString() + " record(s) saved.");
textBoxEID.Text = "";
textBoxFNAME.Text = "";
textBoxLname.Text = "";
picEmp.Image = null;
}
catch (Exception ex)
{
conn.Close();
MessageBox.Show(ex.Message);
}
}
private void buttonShow_Click(object sender, EventArgs e)
{
try
{
string sql = "SELECT FIRST_NAME,LAST_NAME,IMAGE FROM Employee WHERE EID="+textBoxEID.Text+"";
if(conn.State!=ConnectionState.Open)
conn.Open();
command = new SqlCommand(sql, conn);
SqlDataReader reader = command.ExecuteReader();
reader.Read();
if (reader.HasRows)
{
textBoxFNAME.Text=reader[0].ToString();
textBoxLname.Text=reader[1].ToString();
byte[] img = (byte[])(reader[2]);
if(img==null)
picEmp.Image= null;
else
{
MemoryStream ms = new MemoryStream(img);
picEmp.Image = Image.FromStream(ms);
}
}
else
{
MessageBox.Show("FINNS INTE");
}
conn.Close();
}
catch(Exception ex)
{
conn.Close();
MessageBox.Show(ex.Message);
}
}
}
}
here i leave you a link with a nice implementation, it has a demo so you wont have any kind of trouble testing it.
http://www.codeproject.com/Articles/379980/Fancy-ASP-NET-MVC-Image-Uploader
Related
The program is made in C# and database is MySQL.
I have 2 errors, first one when program loads (parameter is not valid) and second one (You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '(Slika) values (_binary '?PNG).
So i tried the #blob thing (before i was only saving it as pictureBox which people said its false) and i get this error.
Also good to mention that i always get saved the same file which is BLOB - 55B.
This is the code:
private void button3_Click(object sender, EventArgs e)
{
con.OpenConnection2();
string query2 = "update tabla set (Slika) values (#Blob)";
cmd.Connection = Connectioncl.connection2;
cmd.CommandText = query2;
cmd.Parameters.AddWithValue("Blob", save(pictureBox3));
cmd.ExecuteNonQuery();
MessageBox.Show("Data Save in Database ", "Data Save", MessageBoxButtons.OK, MessageBoxIcon.Information);
pictureBox2.Image = pictureBox3.Image;
this.Refresh();
}
I get parameter is invalid in this code where image has to load from database as soon as program is started:
private void Form2_Load(object sender, EventArgs e)
{
try
{
textBox1.Text = Form1.id; //just to check if its the correct ID
con.OpenConnection();
label1.Text = Form1.ime;
label2.Text = Form1.prezime;
timer1.Start();
string query = "select * from tabla where ID='" + ID + "'";
cmd.Connection = Connectioncl.connection;
cmd.CommandText = query;
MySqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
pictureBox2.Image = displayImage((byte[])dr["Slika"]);
}
dr.Close();
con.CloseConnection();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
And here is the whole code of the Form2 (Form1 works perfectly fine):
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.IO;
namespace Maturski_Rad_1
{
public partial class Form2 : Form
{
Connectioncl con = new Connectioncl();
MySqlCommand cmd = new MySqlCommand();
string ID = Form1.id;
public Form2()
{
InitializeComponent();
}
public byte[] save(PictureBox pb)
{
MemoryStream mstr = new MemoryStream();
pictureBox3.Image.Save(mstr, pb.Image.RawFormat);
return mstr.GetBuffer();
}
public Image displayImage(byte[] slika)
{
MemoryStream mstr = new MemoryStream(slika);
return Image.FromStream(mstr);
}
private void Form2_Load(object sender, EventArgs e)
{
try
{
textBox1.Text = Form1.id; //just to check if its the correct ID
con.OpenConnection();
label1.Text = Form1.ime;
label2.Text = Form1.prezime;
timer1.Start();
string query = "select * from tabla where ID='" + ID + "'";
cmd.Connection = Connectioncl.connection;
cmd.CommandText = query;
MySqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
pictureBox2.Image = displayImage((byte[])dr["Slika"]);
}
dr.Close();
con.CloseConnection();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void toolTip1_Popup(object sender, PopupEventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void panel1_MouseHover(object sender, EventArgs e)
{
toolTip1.Show("Vas ID je: " + Form1.id, panel1);
toolTip1.UseFading = true;
}
private void label3_Click(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
label4.Text = DateTime.Now.ToShortTimeString();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Title = "Odaberite sliku";
dialog.Filter = " (*.jpg;*.png;*.jpeg) | *.jpg;*.png;*.jpeg";
DialogResult dr = new DialogResult();
dr = dialog.ShowDialog();
if (dr == DialogResult.OK)
{
pictureBox3.Image = new Bitmap(dialog.FileName);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void button3_Click(object sender, EventArgs e)
{
con.OpenConnection2();
string query2 = "update tabla set (Slika) values (#Blob)";
cmd.Connection = Connectioncl.connection2;
cmd.CommandText = query2;
cmd.Parameters.AddWithValue("Blob", save(pictureBox3));
cmd.ExecuteNonQuery();
MessageBox.Show("Data Save in Database ", "Data Save", MessageBoxButtons.OK, MessageBoxIcon.Information);
pictureBox2.Image = pictureBox3.Image;
this.Refresh();
}
private void pictureBox1_Click(object sender, EventArgs e)
{
if (panel3.Visible = !panel3.Visible)
{
panel3.Visible = panel3.Visible;
}
else if(panel3.Visible = panel3.Visible)
{
panel3.Visible = !panel3.Visible;
}
}
}
}
Thanks for any help!!
UPDATE
So I have decided to insert full data and image directly to table in phpmyadmin and when I entered credentials no errors were showing.
It just seems to be an error while converting to blob while updating the table, now if someone can help me with this i'm pretty new to C# and MySQL especially.
[1]: https://i.stack.imgur.com/KUK7a.png
UPDATE #2
I have changed mstr.GetBuffer() to mstr.GetArray(), also I added few lines to code and there are no more errors at saving picture, but I still have problem when it gets saved its corrupted or it just doesn't convert correctly.
When image gets uploaded it doesn't take nearly as much memory as same image i inserted directly into the table which had no problem loading into program.
So now it's just problem converting to binary ! guess, any help is appreciated!
This is how code looks after I added couple lines to save button:
private void button3_Click(object sender, EventArgs e)
{
byte[] ImageData;
FileStream fs = new FileStream(fname, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
ImageData = br.ReadBytes((int)fs.Length);
br.Close();
fs.Close();
con.OpenConnection2();
string query2 = "update tabla set Slika = '" + ImageData + "' where ID = '" + ID + "'";
cmd.Connection = Connectioncl.connection2;
cmd.CommandText = query2;
cmd.Parameters.AddWithValue("Slika", ImageData);
cmd.ExecuteNonQuery();
MessageBox.Show("Data Save in Database ", "Data Save", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.Refresh();
con.CloseConnection2();
}
I am happy to say that the problem has been fixed, it was indeed problem with saving picture to the database.
The problem was that I had to add parameter MySqlDbType.Blob like so:
cmd.Parameters.Add("#Slika", MySqlDbType.Blob);
And then I had to give that parameter the picture, like so:
cmd.Parameters["#Slika"].Value = ImageData;
Easy as that, feels much more rewarding when you solve the problem yourself :D
I will post the whole code so if someone wants to use it feel free.
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.IO;
namespace Maturski_Rad_1
{
public partial class Form2 : Form
{
Connectioncl con = new Connectioncl();
MySqlCommand cmd = new MySqlCommand();
string ID = Form1.id;
string fname;
public Form2()
{
InitializeComponent();
}
public Image displayImage(byte[] slika)
{
MemoryStream mstr = new MemoryStream(slika);
return Image.FromStream(mstr);
}
private void Form2_Load(object sender, EventArgs e)
{
try
{
textBox1.Text = Form1.id; //just to check if its the correct ID
con.OpenConnection();
label1.Text = Form1.ime;
label2.Text = Form1.prezime;
timer1.Start();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
try {
string query = "select Slika,ID from tabla where ID='" + ID + "'";
cmd.Connection = Connectioncl.connection;
cmd.CommandText = query;
MySqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
pictureBox2.Image = displayImage((byte[])dr["Slika"]);
}
dr.Close();
con.CloseConnection();
}
catch
{
MessageBox.Show("Error: Profilna slika nije pronadjena!");
}
}
private void toolTip1_Popup(object sender, PopupEventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void panel1_MouseHover(object sender, EventArgs e)
{
toolTip1.Show("Vas ID je: " + Form1.id, panel1);
toolTip1.UseFading = true;
}
private void label3_Click(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
label4.Text = DateTime.Now.ToShortTimeString();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Title = "Odaberite sliku";
dialog.Filter = " (*.jpg;*.png;*.jpeg) | *.jpg;*.png;*.jpeg";
DialogResult dr = new DialogResult();
dr = dialog.ShowDialog();
if (dr == DialogResult.OK)
{
pictureBox3.Image = new Bitmap(dialog.FileName);
fname = dialog.FileName;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void button3_Click(object sender, EventArgs e)
{
byte[] ImageData;
FileStream fs = new FileStream(fname, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
ImageData = br.ReadBytes((int)fs.Length);
br.Close();
fs.Close();
con.OpenConnection2();
string query2 = "update tabla set Slika= #Slika where ID = '" + ID + "'";
cmd.Connection = Connectioncl.connection2;
cmd.CommandText = query2;
cmd.Parameters.Add("#Slika", MySqlDbType.Blob);
cmd.Parameters["#Slika"].Value = ImageData;
cmd.ExecuteNonQuery();
MessageBox.Show("Data Save in Database ", "Data Save", MessageBoxButtons.OK, MessageBoxIcon.Information);
con.CloseConnection2();
pictureBox2.Image = pictureBox3.Image;
}
private void pictureBox1_Click(object sender, EventArgs e)
{
pictureBox3.Image = pictureBox2.Image;
if (panel3.Visible = !panel3.Visible)
{
panel3.Visible = panel3.Visible;
}
else if(panel3.Visible = panel3.Visible)
{
panel3.Visible = !panel3.Visible;
}
}
}
}
Enjoy!
PS. Slika or #Slika means image in my language, its just that I called my image column in the database like that.
when i try to enter quantity and update the tblcart error shows that as shown in the picture the error comes as incorrect syntax near sdate..can you guys help me solve this problem..i have listed both quantity form and my posform codes below and you can also see the error in the pictures.
This is quantity form code
`using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace POSsystem
{
public partial class frmQty : Form
{
//code to connect sql database
SqlConnection cn = new SqlConnection();
SqlCommand cm = new SqlCommand();
DBConnection dbcon = new DBConnection();
SqlDataReader dr;
private String pcode;
private double price;
private string transno;
string stitle = "Simple POS System";
frmPOS fpos;
public frmQty(frmPOS frmpos)
{
InitializeComponent();
cn = new SqlConnection(dbcon.MyConnection());
fpos = frmpos;
}
private void frmQty_Load(object sender, EventArgs e)
{
}
public void ProductDetails(String pcode, double price, String transno)
{
this.pcode = pcode;
this.price = price;
this.transno = transno;
}
private void frmQty_KeyPress(object sender, KeyPressEventArgs e)
{
}
private void txtQty_KeyPress(object sender, KeyPressEventArgs e)
{
if ((e.KeyChar==13) && (txtQty.Text != String.Empty))
{
cn.Open();
cm = new SqlCommand("insert into tblcart (transno, pcode, price, qty, sdate) values
(#transno, #pcode, #price, #qty, #sdate", cn);
cm.Parameters.AddWithValue("#transno", transno);
cm.Parameters.AddWithValue("#pcode", pcode);
cm.Parameters.AddWithValue("#price", price);
cm.Parameters.AddWithValue("#qty", int.Parse(txtQty.Text));
cm.Parameters.AddWithValue("#sdate", DateTime.Now);
cm.ExecuteNonQuery();
fpos.txtSearch.Clear();
fpos.txtSearch.Focus();
this.Dispose();
}
}
}
}
`
this is the code of posform
`using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace POSsystem
{
public partial class frmPOS : Form
{
SqlConnection cn = new SqlConnection();
SqlCommand cm = new SqlCommand();
SqlDataReader dr;
DBConnection dbcon = new DBConnection();
string stitle = "Simple POS System";
public frmPOS()
{
InitializeComponent();
lblDate.Text = DateTime.Now.ToLongDateString();
cn = new SqlConnection(dbcon.MyConnection());
this.KeyPreview = true;
}
private void button4_Click(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
private void GetTransno()
{
try
{
string sdate = DateTime.Now.ToString("yyyyMMdd");
string transno;
int count;
cn.Open();
cm = new SqlCommand("select top 1 transno from tblcart where transno like '" + sdate +
"%' order by id desc", cn);
dr = cm.ExecuteReader();
dr.Read();
if (dr.HasRows) {
transno = dr[0].ToString();
count = int.Parse(transno.Substring(8, 4));
lblTransno.Text = sdate + (count + 1);
} else {
transno = sdate + "1001";
lblTransno.Text = transno;
} dr.Close();
cn.Close();
}
catch (Exception ex)
{
cn.Close();
MessageBox.Show(ex.Message, stitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private void btnNew_Click(object sender, EventArgs e)
{
GetTransno();
txtSearch.Enabled = true;
txtSearch.Focus();
}
private void txtSearch_Click(object sender, EventArgs e)
{
}
private void txtSearch_TextChanged(object sender, EventArgs e)
{
try
{
if (txtSearch.Text == String.Empty) { return; }
else
{
cn.Open();
cm = new SqlCommand("select * from tblproduct where barcode like '" + txtSearch.Text
+ "'", cn);
dr = cm.ExecuteReader();
dr.Read();
if (dr.HasRows)
{
frmQty frm = new frmQty(this);
frm.ProductDetails(dr["pcode"].ToString(), double.Parse(dr["price"].ToString()),
lblTransno.Text);
frm.ShowDialog();
}
dr.Close();
cn.Close();
}
}
catch (Exception ex)
{
cn.Close();
MessageBox.Show(ex.Message, stitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}
}
`
very likely is this line cm.Parameters.AddWithValue("#sdate", DateTime.Now);
try using
cm.Parameters.AddWithValue("#sdate", $"'{DateTime.Now:yyyy-MM-dd}'");
not sure about your data schema, but pass a string instead of a DateTime to it.
the above sample code omits the time portion, so make the adjustment you want
This is my first time attempting to read an Access database and write each row to the console. When I execute the application I get thrown an exception that says, "No value given for one or more required parameters" on the following statement:
OleDbDataReader reader = cmd.ExecuteReader();
I'm relatively new to c# programming and after hours of research, I can't figure out what I'm doing wrong. Here's my code:
private void maintenanceToolStripMenuItem_Click(object sender, EventArgs e)
{
//Use a variable to hold the SQL statement.
string inputString = "SELECT Full_Name, First_Name, Last_Name, Company FROM CONTACTS";
try
{
//Create an OleDbCommand object and pass in the SQL statement and OleDbConnection object
OleDbCommand cmd = new OleDbCommand(inputString, conn);
//Send the CommandText to the connection, and then build an OleDbDataReader.
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("\t{0}\t{1}", reader.GetString(1));
reader.NextResult();
}
}
reader.Close();
}
catch (Exception ex)
{
error_message = ex.Message;
MessageBox.Show(error_message);
}
In response to the commenters, I'm posting a larger piece of code to eliminate any assumptions and give a better overall picture of what I'm trying to do:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
using System.IO;
namespace AzFloodSquad
{
public partial class frm1DefaultScreen : Form
{
//Initialize the application
String conn_string = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source = C:\\Databases\\AzFloodSquad\\AzFloodSquad.accdb;Persist Security Info=False;";
OleDbConnection conn = null;
String error_message = "";
String q = "";
string varReportId = "";
public frm1DefaultScreen()
{
InitializeComponent();
}
//Load the default form
private void frm1DefaultScreen_Load(object sender, EventArgs e)
{
connectToolStripMenuItem.PerformClick();
contactsToolStripMenuItem.PerformClick();
}
//Exit the application
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
//Start the database
private void connectToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
conn = new OleDbConnection(conn_string);
conn.Open();
disconnectToolStripMenuItem.Enabled = true;
connectToolStripMenuItem.Enabled = false;
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
}
//Stop the database
private void disconnectToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
conn.Close();
disconnectToolStripMenuItem.Enabled = false;
connectToolStripMenuItem.Enabled = true;
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
}
//Clean up database whem form close button clicked
private void frm1DefaultScreen_FormClosing(object sender, FormClosingEventArgs e)
{
disconnectToolStripMenuItem.PerformClick();
}
private void contactsToolStripMenuItem_Click(object sender, EventArgs e)
{
varReportId = "Contacts";
q = "SELECT * " +
"FROM CONTACTS WHERE CONTACTS.CONTACT_TYPE = 'CUSTOMER' " +
"OR CONTACTS.CONTACT_TYPE = 'HOMEOWNER' OR CONTACTS.CONTACT_TYPE = 'HOME OWNER' " +
"OR CONTACTS.CONTACT_TYPE = 'TENANT'" +
"ORDER BY FULL_NAME";
this.Cursor = Cursors.WaitCursor;
run_Query_Parm(q);
this.Cursor = Cursors.Default;
}
//Pull data from the database using the parameter field
private void run_Query_Parm(String q)
{
error_message = "";
try
{
OleDbCommand cmd = new OleDbCommand(q, conn);
OleDbDataAdapter a = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
a.SelectCommand = cmd;
a.Fill(dt);
results.DataSource = dt;
results.AutoResizeColumns();
}
catch (Exception ex)
{
error_message = ex.Message;
MessageBox.Show(error_message);
}
}
//Clear all data from the screen
private void clearFormToolStripMenuItem_Click(object sender, EventArgs e)
{
varReportId = "";
if (this.results.DataSource != null)
{
this.results.DataSource = null;
}
else
{
this.results.Rows.Clear();
}
}
private void maintenanceToolStripMenuItem_Click(object sender, EventArgs e)
{
//Use a variable to hold the SQL statement.
string inputString = "SELECT Full_Name, First_Name, Last_Name, Company FROM CONTACTS";
try
{
//Create an OleDbCommand object and pass in the SQL statement and OleDbConnection object
OleDbCommand cmd = new OleDbCommand(inputString, conn);
//Send the CommandText to the connection, and then build an OleDbDataReader.
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("\t{0}\t{1}", reader.GetString(1));
reader.NextResult();
}
}
reader.Close();
}
catch (Exception ex)
{
error_message = ex.Message;
MessageBox.Show(error_message);
}
}
Any help provided would be greatly appreciated. Thanks in advance.
I found the problem. Apparently, I had improper syntax on my SELECT statement. When I replaced my SELECT, (shown in the first code example I posted), with the following, it worked fine:
string inputString = "SELECT Contacts.[Account_Number], " +
"Contacts.[Full_Name], Contacts.[ID], Contacts.[Street], " +
"Contacts.[City], Contacts.[State], Contacts.[Zip] FROM Contacts";
I created a simple project for parking car. When i register any user and save it in access database.After saving Dialog box is shown and ask me to save that user but problem when Dialog Box is shown error comes out about access violation exception.Read or write protected memory i don't know how to fix.
I read some blogs and posts about this error but no provide a correct solution and also not post any correct idea.
Below is my complete code how can i fix.
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.Configuration;
using System.Data.OleDb;
using MessagingToolkit.QRCode.Codec;
using MessagingToolkit.QRCode.Codec.Data;
using System.IO;
using NPR.Properties;
namespace NPR
{
public partial class UserAdd : Form
{
public UserAdd()
{
InitializeComponent();
}
private int userId = 0;
public int UserId
{
get { return userId; }
set { userId = value; }
}
private bool isUpdate = false;
public bool IsUpdate
{
get { return isUpdate; }
set { isUpdate = value; }
}
private void UpdateRecord()
{
string connString = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;
string cmdString = "Update users SET u_name = #name,u_car_no = #car_no, u_mobile_no = #mobile_no,u_license_no = #license_no,u_reg_date = #reg_date , u_image=#firstimage,u_car_background=#secondimage WHERE Id = #userId";
using (OleDbConnection con = new OleDbConnection(connString))
{
using (OleDbCommand cmd = new OleDbCommand(cmdString, con))
{
con.Open();
cmd.Parameters.AddWithValue("#name", NameTextBox.Text);
cmd.Parameters.AddWithValue("#car_no", PlateNoTextBox.Text);
cmd.Parameters.AddWithValue("#mobile_no", MobileTextBox.Text);
cmd.Parameters.AddWithValue("#license_no", LicenseTextBox.Text);
cmd.Parameters.AddWithValue("#reg_date", DateTime.Text);
cmd.Parameters.AddWithValue("#firstimage", savePhoto());
cmd.Parameters.AddWithValue("#secondimage", savePhoto2());
cmd.Parameters.AddWithValue("#userId", this.userId);
cmd.ExecuteNonQuery();
}
}
}
private void SaveRecord()
{
string connString = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;
string cmdString = "INSERT INTO users (u_name,u_car_no,u_mobile_no,u_license_no,u_reg_date,u_image,u_car_background) VALUES (#name,#car_no,#mobile_no,#license_no,#reg_date,#firstimage,#secondimage)";
using (OleDbConnection con = new OleDbConnection(connString))
{
using (OleDbCommand cmd = new OleDbCommand(cmdString, con))
{
con.Open();
cmd.Parameters.AddWithValue("#name", NameTextBox.Text);
cmd.Parameters.AddWithValue("#car_no", PlateNoTextBox.Text);
cmd.Parameters.AddWithValue("#mobile_no", MobileTextBox.Text);
cmd.Parameters.AddWithValue("#license_no", LicenseTextBox.Text);
cmd.Parameters.AddWithValue("#reg_date", DateTime.Text);
cmd.Parameters.AddWithValue("#firstimage", savePhoto());
cmd.Parameters.AddWithValue("#secondimage", savePhoto2());
cmd.ExecuteNonQuery();
}
}
}
private byte[] savePhoto()
{
MemoryStream ms = new MemoryStream();
FirstpictureBox.Image.Save(ms, FirstpictureBox.Image.RawFormat);
return ms.GetBuffer();
}
private byte[] savePhoto2()
{
MemoryStream ms = new MemoryStream();
SecondpictureBox.Image.Save(ms, SecondpictureBox.Image.RawFormat);
return ms.GetBuffer();
}
private bool IsValidated()
{
if (NameTextBox.Text.Trim() == string.Empty)
{
MessageBox.Show("Name is Required.", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
NameTextBox.Focus();
return false;
}
if (PlateNoTextBox.Text.Trim() == string.Empty)
{
MessageBox.Show("Car Plate No. is Required.", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
PlateNoTextBox.Focus();
return false;
}
if (MobileTextBox.Text.Trim() == string.Empty)
{
MessageBox.Show("Mobile No. is Required.", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
MobileTextBox.Focus();
return false;
}
if (LicenseTextBox.Text.Trim() == string.Empty)
{
MessageBox.Show("License No. is Required.", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
NameTextBox.Focus();
return false;
}
if (DateTime.Text.Trim() == string.Empty)
{
MessageBox.Show("Date is Required.", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
DateTime.Focus();
return false;
}
return true;
}
private DataTable GetUserInfoById()
{
DataTable dtUsersInfo = new DataTable();
string connString = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;
string cmdString = "SELECT * FROM users WHERE Id = #UserId";
using (OleDbConnection con = new OleDbConnection(connString))
{
using (OleDbCommand cmd = new OleDbCommand(cmdString, con))
{
con.Open();
cmd.Parameters.AddWithValue("#UserId", this.UserId);
OleDbDataReader reader = cmd.ExecuteReader();
dtUsersInfo.Load(reader);
}
}
return dtUsersInfo;
}
private Image LoadImg(byte[] img)
{
MemoryStream ms = new MemoryStream(img);
return Image.FromStream(ms);
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
private void SecondpictureBox_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Select Car Background Image";
ofd.Filter = "Image File(*.png;*.jpg;*.bmp;*.gif)|*.png;*.jpg;*.bmp;*.gif";
if (ofd.ShowDialog() == DialogResult.OK)
{
SecondpictureBox.Image = new Bitmap(ofd.FileName);
}
}
private void FirstpictureBox_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Select User Profile Image";
ofd.Filter = "Image File(*.png;*.jpg;*.bmp;*.gif)|*.png;*.jpg;*.bmp;*.gif";
if (ofd.ShowDialog() == DialogResult.OK)
{
FirstpictureBox.Image = new Bitmap(ofd.FileName);
}
}
private void button3_Click(object sender, EventArgs e)
{
DataTable dtUsers = GetUserInfoById();
DataRow row = dtUsers.Rows[0];
PlateNoTextBox.Text = row["u_car_no"].ToString();
string connString = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;
string cmdString = "DELETE * FROM users WHERE Id = #UserId";
using (OleDbConnection con = new OleDbConnection(connString))
{
using (OleDbCommand cmd = new OleDbCommand(cmdString, con))
{
con.Open();
cmd.Parameters.AddWithValue("#UserId", this.UserId);
cmd.ExecuteNonQuery();
}
}
string connString2 = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;
string camdString = "Update slots SET u_name = #name,u_car_no = #car_no,Status = 0 WHERE u_car_no = #slotId";
using (OleDbConnection conn = new OleDbConnection(connString2))
{
using (OleDbCommand cmd = new OleDbCommand(camdString, conn))
{
conn.Open();
cmd.Parameters.AddWithValue("#name", " ");
cmd.Parameters.AddWithValue("#car_no", " ");
cmd.Parameters.AddWithValue("#slotId", row["u_car_no"]);
cmd.ExecuteNonQuery();
conn.Close();
conn.Dispose();
}
}
MessageBox.Show("User Deleted Successfully.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.Close();
}
private void viewDataToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Hide();
AllUserDetail mef = new AllUserDetail();
mef.ShowDialog();
}
private void toolStripMenuItem1_Click(object sender, EventArgs e)
{
this.Hide();
Dashboard dsh = new Dashboard();
dsh.ShowDialog();
}
private void UserAdd_Load(object sender, EventArgs e)
{
if (this.IsUpdate)
{
DataTable dtUsers = GetUserInfoById();
DataRow row = dtUsers.Rows[0];
NameTextBox.Text = row["u_name"].ToString();
PlateNoTextBox.Text = row["u_car_no"].ToString();
MobileTextBox.Text = row["u_mobile_no"].ToString();
LicenseTextBox.Text = row["u_license_no"].ToString();
DateTime.Text = row["u_reg_date"].ToString();
FirstpictureBox.Image = (row["u_image"] is DBNull) ? Resources.no_thumb : LoadImg((byte[])row["u_image"]);
SecondpictureBox.Image = (row["u_car_background"] is DBNull) ? Resources.no_thumb : LoadImg((byte[])row["u_car_background"]);
}
}
private void button1_Click(object sender, EventArgs e)
{
if (IsValidated())
{
try
{
if (this.isUpdate)
{
UpdateRecord();
String plate = PlateNoTextBox.Text;
QRCodeEncoder encoder = new QRCodeEncoder();
Bitmap qrcode = encoder.Encode(plate);
qrimage.Image = qrcode as Image;
MessageBox.Show("Record Updated Successfully.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
SaveFileDialog s = new SaveFileDialog();
s.Title = "Save QR Code";
s.Filter = "JPEG|*.jpg|PNG|*.png|BMP|*.bmp|GIF|*.gif";
if (s.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
try
{
qrimage.Image.Save(s.FileName);
}
catch (ApplicationException ex)
{
MessageBox.Show("ERROR:" + ex.Message, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
else
{
SaveRecord();
String plate = PlateNoTextBox.Text;
QRCodeEncoder encoder = new QRCodeEncoder();
Bitmap qrcode = encoder.Encode(plate);
qrimage.Image = qrcode as Image;
MessageBox.Show("Record Save Successfully.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
SaveFileDialog s = new SaveFileDialog();
s.Title = "Save QR Code";
s.Filter = "JPEG|*.jpg|PNG|*.png|BMP|*.bmp|GIF|*.gif";
if (s.ShowDialog() == DialogResult.OK)
{
try
{
qrimage.Image.Save(s.FileName);
}
catch (ApplicationException ex)
{
MessageBox.Show("ERROR:" + ex.Message, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
this.Close();
}
catch (ApplicationException ex)
{
MessageBox.Show("ERROR:" + ex.Message, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}
Problem i face it in SaveRecord(); function dialog box.
if (s.ShowDialog() == DialogResult.OK) //Here is error
{
try
{
qrimage.Image.Save(s.FileName);
}
Please try to add s.InitialDirectory = "D:\\"; to prevent access to special directories when dialog opens
C#, WFA, using .NET 4.5 platform,
I dropped textBox1 (firstname), textBox2 (lastname), pictureBox1 (employee phot), button2 (browse), and button1 (save) to insert new employees.
button2 -> must browse image and display in pictureBox1,
button1 -> must save the image, which was browsed by button2 and is in display by pictureBox1, to this table in localhost.
After I run the program, I GET THIS ERROR (file could not be found.)
(I don't get any error on browsing alone though)
I just want answers that contain codes to fix this WFA. Just want to be sure I'm crystal clear on this.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Data.SqlClient;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
SqlConnection cnn = new SqlConnection("Initial Catalog=randomcompany;Data Source=localhost;Integrated Security=SSPI;");
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e) //Browse button
{
try
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "Images (*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|" + "All files (*.*)|*.*";
dlg.Title = "Select Employee Picture";
if (dlg.ShowDialog() == DialogResult.OK)
{
pictureBox1.Image = System.Drawing.Image.FromFile(dlg.FileName);
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void button1_Click(object sender, EventArgs e) //Save button
{
try
{
cnn.Open();
string path = pictureBox1.Image.ToString();
Byte[] imagedata = File.ReadAllBytes(path);
SqlCommand cmd = new SqlCommand("INSERT INTO Employees (EmployeeFirstname, EmployeeLastname, EmployeePhoto) VALUES (#item1,#item2,#img", cnn);
cmd.Parameters.AddWithValue("#item1", textBox1.Text);
cmd.Parameters.AddWithValue("#item2", textBox2.Text);
cmd.Parameters.AddWithValue("#img", imagedata);
cmd.ExecuteNonQuery();
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
When you try to get image file path from your image here:
string path = pictureBox1.Image.ToString();
you actually get the name of Image type (System.Drawing.Bitmap)
You need to keep path to image file after selecting it in dialog. You can do it like this:
pictureBox1.Image = System.Drawing.Image.FromFile(dlg.FileName);
pictureBox1.Tag = dlg.FileName;
Then you need to read this name like this:
string path = pictureBox1.Tag as string;
The issue is that this:
string path = pictureBox1.Image.ToString();
does not return a path. Store the path when you get it in a class field. Let's name it _path:
private string _path;
and then let's set it when you get the file name:
_path = dlg.FileName;
and then just use it here:
Byte[] imagedata = File.ReadAllBytes(_path);
Here is the full code modified:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Data.SqlClient;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private string _path;
SqlConnection cnn = new SqlConnection("Initial Catalog=randomcompany;Data Source=localhost;Integrated Security=SSPI;");
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e) //Browse button
{
try
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "Images (*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|" + "All files (*.*)|*.*";
dlg.Title = "Select Employee Picture";
if (dlg.ShowDialog() == DialogResult.OK)
{
pictureBox1.Image = System.Drawing.Image.FromFile(dlg.FileName);
_path = dlg.FileName;
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void button1_Click(object sender, EventArgs e) //Save button
{
try
{
cnn.Open();
Byte[] imagedata = File.ReadAllBytes(_path);
SqlCommand cmd = new SqlCommand("INSERT INTO Employees (EmployeeFirstname, EmployeeLastname, EmployeePhoto) VALUES (#item1,#item2,#img", cnn);
cmd.Parameters.AddWithValue("#item1", textBox1.Text);
cmd.Parameters.AddWithValue("#item2", textBox2.Text);
cmd.Parameters.AddWithValue("#img", imagedata);
cmd.ExecuteNonQuery();
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
You are using wrong property to get the image path. You should you
PictureBox.ImageLocation property of picture box to get the exact location of image.
Modify this part
private void button1_Click(object sender, EventArgs e) //Save button
{
try
{
cnn.Open();
string path = pictureBox1.ImageLocation; // this will work
string path = pictureBox1.Image.ToString(); // here error comes
Byte[] imagedata = File.ReadAllBytes(path);
SqlCommand cmd = new SqlCommand("INSERT INTO Employees (EmployeeFirstname, EmployeeLastname, EmployeePhoto) VALUES (#item1,#item2,#img", cnn);
cmd.Parameters.AddWithValue("#item1", textBox1.Text);
cmd.Parameters.AddWithValue("#item2", textBox2.Text);
cmd.Parameters.AddWithValue("#img", imagedata);
cmd.ExecuteNonQuery();
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}