How to Upload Selected Multiple Images into the Database - sql-server

I need to Upload Image selected in the Website into the DB My project has multiple File Select "File Upload" how can I Upload those multiple Files into Database the Image data in Binary Format, My Code is
protected void Button1_Click(object sender, EventArgs e)
{
string Qry = "insert into tblFiles values(#data)";
SqlConnection con = new SqlConnection(#"Data Source=ESLHPC17\SQL2008;Initial Catalog=dbFiles;User ID=user;Password=password");
SqlCommand cmd = new SqlCommand(Qry,con);
cmd.Parameters.Add("#data") = FileUpload1.FileBytes;
}
I am using the Following Web Handler to Save the Files in local Folder
<%# WebHandler Language="C#" Class="Upload" %>
using System;
using System.Web;
using System.IO;
public class Upload : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
context.Response.Expires = -1;
try
{
HttpPostedFile postedFile = context.Request.Files["Filedata"];
string savepath = "";
string tempPath = "";
tempPath = System.Configuration.ConfigurationManager.AppSettings["FolderPath"];
savepath = context.Server.MapPath(tempPath);
string filename = postedFile.FileName;
if (!Directory.Exists(savepath))
Directory.CreateDirectory(savepath);
postedFile.SaveAs(savepath + #"\" + filename);
context.Response.Write(tempPath + "/" + filename);
context.Response.StatusCode = 200;
}
catch (Exception ex)
{
context.Response.Write("Error: " + ex.Message);
}
}
public bool IsReusable {
get {
return false;
}
}
}
and I use the below Script
<script type = "text/javascript">
$(window).load(
function () {
$("#<%=FileUpload1.ClientID%>").fileUpload({
'uploader': 'scripts/uploader.swf',
'cancelImg': 'images/cancel.png',
'buttonText': 'Browse Files',
'script': 'Upload.ashx',
'folder': 'Uploads',
'fileDesc': 'Image Files',
'fileExt': '*.jpg;*.jpeg;*.gif;*.png',
'multi': true,
'auto': false
});
but I want to store the Images in Database
# Damith
I have tried in with the below mentioned code but it didn't worked,
protected void Button1_Click(object sender, EventArgs e)
{
string FolderPath=#"E:\Rajesh_Kumar\Application\Valuation\ExamManagement\ExamManagement\Uploads";
string path = System.Configuration.ConfigurationManager.AppSettings[FolderPath];
string Qry = "insert into tblFiles values(#data) Values (data)";
SqlConnection con = new SqlConnection(#"Data Source=ESLHPC17\SQL2008;Initial Catalog=dbFiles;User ID=rajesh";
StreamReader sr = new StreamReader(path);
while (sr.ReadLine() != null)
{
using (SqlCommand cmd = new SqlCommand(Qry, con))
{
cmd.Parameters.Add("#data",SqlDbType.VarBinary).Value = path;
con.Open();
cmd.ExecuteNonQuery();
}
con.Close();
con.Dispose();
}
}

try with
foreach (HttpPostedFile uploadedFile in FileUpload1.PostedFiles)
{
SaveImage(uploadedFile);
}
private void SaveImage(HttpPostedFile file)
{
using(SqlConnection con = new SqlConnection(ConnectionString))// set ConnectionString
{
using(SqlCommand cmd = new SqlCommand(Qry,con)) // set Qry
{
cmd.Parameters.AddWithValue("#data", ReadFile(file));
con.Open();
cmd.ExecuteNonQuery();
}
}
}
private byte[] ReadFile(HttpPostedFile file)
{
byte[] data = new Byte[file.ContentLength];
file.InputStream.Read(data, 0, file.ContentLength);
return data;
}
If you need to insert images from server folder and assume you have array of image paths as imageArray then
foreach (var path in imageArray)
{
SaveImage(path);
}
private void SaveImage(string path)
{
using(SqlConnection con = new SqlConnection(ConnectionString))// set ConnectionString
{
using(SqlCommand cmd = new SqlCommand(Qry,con)) // set Qry
{
cmd.Parameters.AddWithValue("#data", System.IO.File.ReadAllBytes(path));
con.Open();
cmd.ExecuteNonQuery();
}
}
}

foreach(HttpPostedFile file in FileUpload1.PostedFiles)
{
var memoryStream = new MemoryStream();
file.InputStream.CopyTo(memoryStream);
string Qry = "insert into tblFiles values(#data)";
SqlConnection con = new SqlConnection(#"Data Source=ESLHPC17\SQL2008;Initial Catalog=dbFiles;User ID=user;Password=password");
SqlCommand cmd = new SqlCommand(Qry,con);
cmd.Parameters.Add("#data") = memoryStream.ToArray();
}

Related

Save excel file in database using c#

I have an excel file. Now I need to save data of excel file in database. What is the simplest way to do that using c# with simple example? Thank in advance
This will do what you want.
private void button1_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection ExcelConnection = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\your_path\\Import_List.xls;Extended Properties=Excel 8.0;");
ExcelConnection.Open();
string expr = "SELECT * FROM [Sheet1$]";
OleDbCommand objCmdSelect = new OleDbCommand(expr, ExcelConnection);
OleDbDataReader objDR = null;
SqlConnection SQLconn = new SqlConnection();
string ConnString = "Data Source=Your_Database_Name;Initial Catalog=Table_Name;Trusted_Connection=True;";
SQLconn.ConnectionString = ConnString;
SQLconn.Open();
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(SQLconn))
{
bulkCopy.DestinationTableName = "tblTest";
try
{
objDR = objCmdSelect.ExecuteReader();
bulkCopy.WriteToServer(objDR);
ExcelConnection.Close();
//objDR.Close()
SQLconn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
To copy from a SQL Server table to an Excel file, try the following.
using System;
using System.Drawing;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
System.Data.OleDb.OleDbConnection MyConnection ;
System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand();
string sql = null;
MyConnection = new System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\\csharp.net-informations.xls';Extended Properties=Excel 8.0;");
MyConnection.Open();
myCommand.Connection = MyConnection;
sql = "Insert into [Sheet1$] (id,name) values('5','e')";
myCommand.CommandText = sql;
myCommand.ExecuteNonQuery();
MyConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());
}
}
}
}
Or, with a 'Where' clause, you can have more control of the output.
using System;
using System.Drawing;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
System.Data.OleDb.OleDbConnection MyConnection ;
System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand();
string sql = null;
MyConnection = new System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\\csharp.net-informations.xls';Extended Properties=Excel 8.0;");
MyConnection.Open();
myCommand.Connection = MyConnection;
sql = "Update [Sheet1$] set name = 'New Name' where id=1";
myCommand.CommandText = sql;
myCommand.ExecuteNonQuery();
MyConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());
}
}
}
}

Login for users of different positions

I am sort of new to login feature for projects and am trying to do logins for my group, which consists of 3 users, namely Nurse, Patient and Pharmacist. I think I am about to complete the loin process but I have a problem with one of my methods, getPosition() in my LoginDAO.cs. So far, I have not done any login codes for patient and pharmacist as i will need my group mates' parts for it to work, but shown below is what I have done. Somehow, login(string nric, string pw) works, but not getPosition(string nric). This is the error that i get from my error log:
Exception: Must declare the scalar variable "#paraNRIC". Source: LoginDAO.getPosition
Thanks in advance :D
protected void btnLogin_Click(object sender, EventArgs e)
{
login login = new login();
login.nric = tbLoginID.Text;
login.pw = tbPassword.Text;
if (login.userLogin(login.nric, login.pw))
{
if (login.getPosition(login.nric) == "Nurse")
{
Response.Redirect("Nurse.aspx");
}
else if (login.getPosition(login.nric) == "Patient")
{
Response.Redirect("Patient.aspx");
}
else if (login.getPosition(login.nric) == "Pharmacist")
{
Response.Redirect("PharmacistDisplay.aspx");
}
}
else
{
lblErr.Text = "Invalid account.";
}
}
public bool login(string nric, string pw)
{
bool flag = false;
SqlCommand cmd = new SqlCommand();
StringBuilder sqlStr = new StringBuilder();
sqlStr.AppendLine("SELECT Password from Position");
sqlStr.AppendLine("Where NRIC = #paraNRIC");
try
{
SqlConnection myconn = new SqlConnection(DBConnect);
cmd = new SqlCommand(sqlStr.ToString(), myconn);
cmd.Parameters.AddWithValue("#paraNRIC", nric);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
if (dt == null)
{
flag = false;
}
else
{
string dbhashedpw = dt.Rows[0]["Password"].ToString();
flag = Helper.VerifyHash(pw, "SHA512", dbhashedpw);
}
}
catch (Exception exc)
{
logManager log = new logManager();
log.addLog("NurseDAO.login", sqlStr.ToString(), exc);
}
return flag;
}
public string getPosition(string nric)
{
string dbPosition = "";
int result = 0;
SqlCommand cmd = new SqlCommand();
StringBuilder sqlStr = new StringBuilder();
sqlStr.AppendLine("SELECT Position from Position ");
sqlStr.AppendLine("where NRIC = #paraNRIC");
cmd.Parameters.AddWithValue("#paraNRIC", nric);
try
{
SqlConnection myconn = new SqlConnection(DBConnect);
cmd = new SqlCommand(sqlStr.ToString(), myconn);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
myconn.Open();
result = cmd.ExecuteNonQuery();
dbPosition = dt.Rows[0]["Position"].ToString();
myconn.Close();
}
catch (Exception exc)
{
logManager log = new logManager();
log.addLog("LoginDAO.getPosition", sqlStr.ToString(), exc);
}
return dbPosition;
`}
Your error is here:
SqlCommand cmd = new SqlCommand();
// lines omitted
cmd.Parameters.AddWithValue("#paraNRIC", nric);
try
{
SqlConnection myconn = new SqlConnection(DBConnect);
cmd = new SqlCommand(sqlStr.ToString(), myconn);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
Note that you are instantiating cmd twice. The code adds the parameters to the first SqlCommand instance, but executes the second instance.
To resolve, ensure you declare the parameters on the instance of SqlCommand you invoke:
public string getPosition(string nric)
{
string dbPosition = "";
int result = 0;
// remove this line: SqlCommand cmd = new SqlCommand();
StringBuilder sqlStr = new StringBuilder();
sqlStr.AppendLine("SELECT Position from Position ");
sqlStr.AppendLine("where NRIC = #paraNRIC");
// move parameter declaration until after you declare cmd
try
{
SqlConnection myconn = new SqlConnection(DBConnect);
SqlCommand cmd = new SqlCommand(sqlStr.ToString(), myconn);
// add the parameters here:
cmd.Parameters.AddWithValue("#paraNRIC", nric);
// code continues
You could change this line
sqlStr.AppendLine("where NRIC = #paraNRIC");
To This
sqlStr.AppendLine("where NRIC = '" + nric + "'");
and avoid parameters altogether.

fill textbox on second combobox selection changed in cascading combobox in windows form using c#

I have 2 cascading combo-box in windows form application. I have textbox for price and unit. when I select first combobox, second combobox gets populated. I want textbox for price and unit to be filled only on second combobox selection.
My problem is when the form is loaded both textboxes are filled with values from table and not on combobox selection changed.
my code is:
private void Purchase_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'supplierDataSet.Supplier' table. You can move, or remove it, as needed.
this.supplierTableAdapter.Fill(this.supplierDataSet.Supplier);
fillName();
comboBoxName.SelectedIndex = -1;
}
private void fillName()
{
string str = "Select distinct Item_Name from Item";
using (SqlConnection con = new SqlConnection(#"Data Source=ashish-pc\;Initial Catalog=HMS;Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand(str, con))
{
using (SqlDataAdapter adp = new SqlDataAdapter(cmd))
{
DataTable dtItem = new DataTable();
adp.Fill(dtItem);
comboBoxName.DataSource = dtItem;
comboBoxName.DisplayMember = "Item_Name";
comboBoxName.ValueMember = "Item_Name";
}
}
}
}
private void fillMake()
{
string str = "Select Item_Make from Item Where Item_Name=#Item_Name";
using (SqlConnection con = new SqlConnection(#"Data Source=ashish-pc\;Initial Catalog=HMS;Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand(str, con))
{
cmd.Parameters.AddWithValue("#Item_Name", comboBoxName.Text);
using (SqlDataAdapter adp = new SqlDataAdapter(cmd))
{
DataTable dtItem = new DataTable();
adp.Fill(dtItem);
comboBoxMake.DataSource = dtItem;
comboBoxMake.ValueMember = "Item_Make";
comboBoxMake.DisplayMember = "Item_Make";
}
}
}
}
private void comboBoxName_SelectedIndexChanged_1(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(comboBoxName.Text))
{
comboBoxMake.Enabled = true;
fillMake();
comboBoxMake.SelectedIndex = -1;
}
}
private void comboBoxMake_SelectedIndexChanged_1(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(comboBoxMake.Text))
{
textBoxPrice.Enabled = true;
textBoxUoM.Enabled = true;
}
SqlConnection con = new SqlConnection(#"Data Source=ashish-pc\;Initial Catalog=HMS;Integrated Security=True");
SqlCommand cmd = new SqlCommand("Select * from Item Where Item_Make='" + comboBoxMake.Text + "' AND Item_Name='" + comboBoxName.Text + "'", con);
SqlDataReader reader;
try
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
reader = cmd.ExecuteReader();
while (reader.Read())
{
textBoxPrice.Text = Convert.ToString(reader["Price"]);
textBoxUoM.Text = Convert.ToString(reader["Unit"]);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
}
I am stuck here. please help.
Try changing SelectedIndex = -1 to SelectedItem = -1 in Purchase_Load and ComboBox1_SelectedIndexChanged.

Error in Win Form Login

private void Button1Click(object sender, EventArgs e)
{
var dt = new DataTable();
const string Connectionstring = "Data Source=GARETH-PC1;Initial Catalog=Genres;Integrated Security=True";
using (var con = new SqlConnection(Connectionstring))
{
con.Open();
var query = "Select Username From Login Where Username ='" + ComboBox1.SelectedText + "' Password ='" + textBox2.Text + "'";
using (var sda = new SqlDataAdapter(query, con))
{
sda.Fill(dt);
}
}
if (dt.Rows[0].ItemArray.GetValue(0).ToString() == "1")
{
Hide();
var ss = new Main();
ss.Show();
}
else
{
MessageBox.Show("Invalid Username or Password");
}
}
The if (dt.Rows[0].ItemArray.GetValue(0).ToString() == "1") - Returns an error saying there's nothing in the table... But there is ..any suggestions?
Maybe you can try like this:
dt.Rows[0]["ColumnName"].ToString()
This is working for me.
I would change your code in this way.
First, change to a parameterized query instead of a string concatenation (Sql Injection and parsing)
Second, use the count property to check if you have found a record or not
private void Button1Click(object sender, EventArgs e)
{
var dt = new DataTable();
const string Connectionstring = "Data Source=GARETH-PC1;Initial Catalog=Genres;Integrated Security=True";
var query = "Select Username From Login Where Username =#uname AND Password=#pwd";
using (var con = new SqlConnection(Connectionstring))
using (var cmd = new SqlCommand(query, con)
{
con.Open();
cmd.Parameters.AddWithValue("#uname", ComboBox1.SelectedText);
cmd.Parameters.AddWithValue("#pwd", textBox2.Text);
using (var sda = new SqlDataAdapter(cmd))
{
sda.Fill(dt);
}
}
if (dt.Rows.Count > 0)
{
Hide();
var ss = new Main();
ss.Show();
}
else
{
MessageBox.Show("Invalid Username or Password");
}
}
As a side note, it is a very bad idea to store passwords in plain text inside a database. You should consider to use an HASH and store it instead of the plain password.

Adding a new entry to a Access table

I'm very new to programing and am trying to link a database to a website. I want the website to allow a user to make a username (OrgID) and password (OrgPassword) and have them apear in my database table (Organizer). This is the code I have so far, but I cannot get it to update the information in the database. Does anyone have any suggestions?
protected void RegisterUser_CreatedUser(object sender, EventArgs e)
{
if (txtUserName.Text != "" && OrgPassword.Text !="")
{
string cnnString = "Provider= Microsoft.ACE.OLEDB.12.0; Data Source =C:/Users/codym/Desktop/Fall 2011/Information Systems/Project/CampuSpaceDatabase2.accdb";
OleDbConnection cnx = new OleDbConnection(cnnString);
OleDbDataAdapter adapter = new OleDbDataAdapter();
string cmdText= "SELECT * FROM Organizer";
OleDbCommand cmd = new OleDbCommand(cmdText, cnx);
adapter.SelectCommand= cmd;
adapter.Fill(Organizer);
Session["Organizer"]= Organizer;
Organizer= ((DataTable)Session["Organizer"]);
string orgname = OrgID.Text;
string orgpass = OrgPassword.Text;
foreach (DataRow in Organizer.Rows)
{
if(row["OrgID"].ToString() == orgname & row["OrgPassword"].ToString() == orgpass)
{
errLabel.Text = "Welcome "+ row["OrgID"].ToString();
return;
}
else
{
errLabel.Text = "OrgID/Password Invalid";
return;
}
}
}
}
It looks like you are missing opening the connection:
OleDbConnection cnx = new OleDbConnection(cnnString);
cnx.Open();

Resources