Using Dapper to select data from MS SQL - asp.net

I use Dapper to select data form Mssql, It result display "null"
(use stored procedure态 List to get data, and "myDictionary[0].Account" and myDictionary[0].Password to get detail information) ,
but MS SQL database have data.
How can I fix code ? thanks.
public void Do_Click(object sender, EventArgs e)
{
string strAccount = Request.Form["userAccount"];
string strPassword = Request.Form["userPwd"];
using (var conn = new SqlConnection(strConn))
{
try
{
conn.Open();
List<LoginModel> myDictionary =
conn.Query<LoginModel>(#"uspSelectLoginChk",
new { LoginAcc = strAccount, LoginPsd = strPassword }, commandType: CommandType.StoredProcedure).ToList();
string strAccountChk = myDictionary[0].Account;
string strPASChk = myDictionary[0].Password;
conn.Close();
if (strAccountChk != null && strAccountChk != null)
{
Response.Redirect("test.aspx");
}
else
{
}
}
catch (Exception ex)
{
response.write( ex.ToString());
}
}
}

Try this one,
// Modified your code
public void Do_Click(object sender, EventArgs e)
{
string strAccount = Request.Form["userAccount"];
string strPassword = Request.Form["userPwd"];
var _para = new DynamicParameters();
_para.Add("#LoginAcc", strAccount);
_para.Add("#LoginPsd", strPassword);
var _list = _con.Query<LoginModel>("uspSelectLoginChk", _para, commandType: CommandType.StoredProcedure); // _con is SqlConnection _con = new SqlConnection("your connection string")
if(_list != null) {
Response.Redirect("test.aspx");
}
}

you need to check:
execute sp in sql with parameter which can view in debug the code.
example:
exec uspSelectLoginChk 'LoginAccValue', 'LoginPsdValue'
if a any data in sql execute,your code is error,if no data, you can insert data before with a data debug result.
Thanks

Related

Stored procedure executing even with the error message

I'm working with two stored procedures in an ASP.NET button function. While I get an error message based on the results that the invoice number is already dispatched from the other stored procedure, it still moves to the other stored procedure and executes it.
If the user gets this error message:
This invoice num was already dispatched!
then it shouldn't move on to this aspect of the function
protected void Button2_Click(object sender, EventArgs e)
{
try
{
for (int i = GridView2.Rows.Count - 1; i >= 0; i--)
{
var row = GridView2.Rows[i];
CheckBox chk = row.FindControl("chkInvoice") as CheckBox;
//CheckBox chk = (CheckBox)GridView2.Rows[i].Cells[0].FindControl("CheckBox3");
if (chk != null && chk.Checked)
{
string strSQLconstring = System.Configuration.ConfigurationManager.ConnectionStrings["TWCL_OPERATIONSConnectionString"].ToString();
using (SqlConnection objConnection = new SqlConnection(strSQLconstring))
{
objConnection.Open();
using (SqlTransaction transaction = objConnection.BeginTransaction())
{
string SID = GridView2.Rows[i].Cells[3].Text.Trim();
SqlDataReader myReader = null;
using (SqlCommand command = new SqlCommand("PP_SelectStatus", objConnection, transaction))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#invoiceNum", SID);
command.Parameters.AddWithValue("#custPONum", GridView2.Rows[i].Cells[4].Text.Trim());
myReader = command.ExecuteReader();
if (myReader.Read())
{
string invoice1 = (myReader["status"].ToString());
if (invoice1 == "0")
{
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "alert('This invoice num was already dispatched!')", true);
}
myReader.Close();
}
}
else if (invoice1=="1")
{
using (SqlCommand cmd = new SqlCommand("PP_RemoveInvoice", objConnection, transaction))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#loadSheetNum", txtDispatchNum.Text);
cmd.Parameters.AddWithValue("#invoiceNum", SID);
cmd.Parameters.AddWithValue("#removeUser", lblUsername.Text.Replace("Welcome", ""));
**int a = cmd.ExecuteNonQuery();**
cmd.Dispose();
if (a > 0)
{
dt.Rows.RemoveAt(i);
////Read invoice qty from grid view 2
string invoice = GridView2.Rows[i].Cells[5].Text.ToString();
decimal invoiceTotal = Convert.ToDecimal(txtInvoiceTotal.Text) - Convert.ToDecimal(invoice);
txtInvoiceTotal.Text = invoiceTotal.ToString();
////Read invoice weight from grid view 2
string weight = GridView2.Rows[i].Cells[6].Text.ToString();
decimal invoiceWeight = Convert.ToDecimal(txtQtyWeight.Text) - Convert.ToDecimal(weight);
txtQtyWeight.Text = invoiceWeight.ToString();
lblError.ForeColor = Color.Green;
lblError.Text = "Selected record(s) successfully updated";
}
else
{
lblError.ForeColor = Color.Red;
lblError.Text = " Record has not yet been recorded";
}
}
//objConnection.Close();
transaction.Commit();
}
}
}
//Button2.Visible = false;
//showData();
GridView2.DataSource = dt;
GridView2.DataBind();
txtInvoiceCount.Text = dt.Rows.Count.ToString();
}
}
}
catch (Exception ex)
{
if (ex.Message.StartsWith("Violation of PRIMARY KEY constraint"))
{
lblError.ForeColor = Color.Red;
lblError.Text = " This invoice number was remove from dispatch sheet before!!";
}
else
{
// re-throw the error if you haven't handled it
lblError.Text = ex.Message;
throw;
}
}
}
You have a very, very simple logic error, but it is incredibly hard to see because your code is such a mess. Therefore, my answer is:
REFACTOR REFACTOR REFACTOR
It is important to get into the habit of writing short functions and controlling their inputs and outputs. If you don't do this, even a fairly trivial operation like this one gets very confusing and error-prone.
Here is an example of how to organize things. We remove most of the code from the click handler:
protected void DeleteButton_Click(object sender, EventArgs e)
{
for (int i = GridView2.Rows.Count - 1; i >= 0; i--)
{
var row = GridView2.Rows[i];
if (IsChecked(row))
{
var result = ProcessRow(row, i);
DisplayResult(i, result);
}
}
}
Firstly, notice it has a meaningful name. These become very important as your application grows. Also, look how short it is! Where did all the code go? Well, it went into two separate methods, which are now short enough for us to view on one page-- a common requirement that IT organizations impose on their programmers, to avoid spaghetti code.
protected TransactionResult ProcessRow(GridViewRow row, int index)
{
var SID = GridView2.Rows[index].Cells[3].Text.Trim();
var custPONum = GridView2.Rows[index].Cells[4].Text.Trim();
var loadSheetNum = txtDispatchNum.Text;
var removeUser = lblUsername.Text.Replace("Welcome", "");
return ExecuteInvoiceTransaction(SID, custPONum, loadSheetNum, removeUser);
}
And
public void DisplayResult(int rowIndex, TransactionResult result)
{
switch result
{
case TransactionResult.Success:
dt.Rows.RemoveAt(rowIndex);
DisplayTotals(rowIndex);
DisplaySuccess("Selected record(s) successfully updated");
break;
case TransactionResult.AlreadyDispatched;
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "alert('This invoice num was already dispatched!')", true);
break;
case TransactionResult.RecordNotRecorded;
DisplayError("Record has not yet been recorded");
break;
case TransactionResult.AlreadyRemoved:
DisplayError("This invoice number was remove from dispatch sheet before!!");
break;
}
}
These methods in turn call a variety of helper methods, each of which does one thing and one thing only. This could be referred to as separation of concerns, which is really important for structured code.
Here's the rest of the methods:
enum TransactionResult
{
Success,
AlreadyDispatched,
RecordNotRecorded,
AlreadyRemoved
}
private bool ExecuteSelectStatus(SqlConnection connection, SqlTransaction transaction, string invoiceNum, string custPONum)
{
using (SqlCommand command = new SqlCommand("PP_SelectStatus", objConnection, transaction))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#invoiceNum", invoiceNum);
command.Parameters.AddWithValue("#custPONum", custPONum);
using (var myReader = command.ExecuteReader())
{
if (myReader.Read())
{
string invoice1 = (myReader["status"].ToString());
if (invoice1 == "0")
{
return false;
}
}
}
return true;
}
}
private int ExecuteRemoveInvoice(SqlConnection objConnection, SqlTransaction transaction, string loadSheetNum, string invoiceNum, string removeUser)
{
try
{
using (SqlCommand cmd = new SqlCommand("PP_RemoveInvoice", objConnection, transaction))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#loadSheetNum", loadSheetNum);
cmd.Parameters.AddWithValue("#invoiceNum", invoiceNum);
cmd.Parameters.AddWithValue("#removeUser", removeUser);
return cmd.ExecuteNonQuery();
}
}
catch (SqlException ex)
{
if (ex.Number == 2627) //Primary key violation
{
return -1;
}
}
}
protected TransactionResult ExecuteInvoiceTransaction(string invoiceNum, string custPONum, string loadSheetNum, string removeUser)
{
var strSQLconstring = System.Configuration.ConfigurationManager.ConnectionStrings["TWCL_OPERATIONSConnectionString"].ToString();
using (SqlConnection objConnection = new SqlConnection(strSQLconstring))
{
objConnection.Open();
using (SqlTransaction transaction = objConnection.BeginTransaction())
{
var ok = ExecuteSelectStatus(objConnection, transaction, invoiceNum, custPONum);
if (!ok) return TransactionResult.AlreadyDispatched;
var a = ExecuteRemoveInvoice(objConnection, transaction, loadSheetNum, invoiceNum, removeUser);
switch a
{
case -1:
return TransactionResult.AlreadyRemoved;
case 0:
return TransactionResult.RecordNotRecorded;
default:
transaction.Commit();
return TransactionResult.Success;
}
}
}
}
public void DisplayTotals(int i)
{
////Read invoice qty from grid view 2
string invoice = GridView2.Rows[i].Cells[5].Text;
decimal invoiceTotal = Convert.ToDecimal(txtInvoiceTotal.Text) - Convert.ToDecimal(invoice);
txtInvoiceTotal.Text = invoiceTotal.ToString();
////Read invoice weight from grid view 2
string weight = GridView2.Rows[i].Cells[6].Text();
decimal invoiceWeight = Convert.ToDecimal(txtQtyWeight.Text) - Convert.ToDecimal(weight);
txtQtyWeight.Text = invoiceWeight.ToString();
}
public void DisplaySuccess(string message)
{
lblError.ForeColor = Color.Green;
lblError.Text = message;
}
public void DisplayError(string message)
{
lblError.ForeColor = Color.Red;
lblError.Text = message;
}
A few things to note:
You don't need to call Dispose() if you are using using.
You should always catch the most specific exception possible, per Microsoft's guidance. My example does this.
The exception handling for the primary key error is isolated into the method that calls the stored procedure. The overall business logic shouldn't have to know details about the SQL implementation. I've shown how you can identify the specific error based on this post.
Because there are four possible outcomes, I added an enumeration called TransactionResult so we could return the status to the caller easily.
Some of these methods are short-- just two lines-- and that is OK. The main reason to separate them out is to give them a meaningful name and make the code shorter and easier to read.
This code is much more structured but it could still be improved! In many implementations, the code that accesses the database is actually moved to a completely different layer or project.
See if this works. Moved your if/else together:
protected void Button2_Click(object sender, EventArgs e)
{
try
{
for (int i = GridView2.Rows.Count - 1; i >= 0; i--)
{
var row = GridView2.Rows[i];
CheckBox chk = row.FindControl("chkInvoice") as CheckBox;
if (chk != null && chk.Checked)
{
string strSQLconstring = System.Configuration.ConfigurationManager.ConnectionStrings["TWCL_OPERATIONSConnectionString"].ToString();
using (SqlConnection objConnection = new SqlConnection(strSQLconstring))
{
objConnection.Open();
using (SqlTransaction transaction = objConnection.BeginTransaction())
{
string SID = GridView2.Rows[i].Cells[3].Text.Trim();
SqlDataReader myReader = null;
using (SqlCommand command = new SqlCommand("PP_SelectStatus", objConnection, transaction))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#invoiceNum", SID);
command.Parameters.AddWithValue("#custPONum", GridView2.Rows[i].Cells[4].Text.Trim());
myReader = command.ExecuteReader();
if (myReader.Read())
{
string invoice1 = (myReader["status"].ToString());
if (invoice1 == "0")
{
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "alert('This invoice num was already dispatched!')", true);
}
else if (invoice1 == "1")
{
using (SqlCommand cmd = new SqlCommand("PP_RemoveInvoice", objConnection, transaction))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#loadSheetNum", txtDispatchNum.Text);
cmd.Parameters.AddWithValue("#invoiceNum", SID);
cmd.Parameters.AddWithValue("#removeUser", lblUsername.Text.Replace("Welcome", ""));
int a = cmd.ExecuteNonQuery();
cmd.Dispose();
if (a > 0)
{
dt.Rows.RemoveAt(i);
////Read invoice qty from grid view 2
string invoice = GridView2.Rows[i].Cells[5].Text.ToString();
decimal invoiceTotal = Convert.ToDecimal(txtInvoiceTotal.Text) - Convert.ToDecimal(invoice);
txtInvoiceTotal.Text = invoiceTotal.ToString();
////Read invoice weight from grid view 2
string weight = GridView2.Rows[i].Cells[6].Text.ToString();
decimal invoiceWeight = Convert.ToDecimal(txtQtyWeight.Text) - Convert.ToDecimal(weight);
txtQtyWeight.Text = invoiceWeight.ToString();
lblError.ForeColor = Color.Green;
lblError.Text = "Selected record(s) successfully updated";
}
else
{
lblError.ForeColor = Color.Red;
lblError.Text = " Record has not yet been recorded";
}
}
//objConnection.Close();
transaction.Commit();
}
}
}
GridView2.DataSource = dt;
GridView2.DataBind();
txtInvoiceCount.Text = dt.Rows.Count.ToString();
}
}
}
}
}
catch (Exception ex)
{
if (ex.Message.StartsWith("Violation of PRIMARY KEY constraint"))
{
lblError.ForeColor = Color.Red;
lblError.Text = " This invoice number was remove from dispatch sheet before!!";
}
else
{
// re-throw the error if you haven't handled it
lblError.Text = ex.Message;
throw;
}
}
}
}

Populating a dropdown list from the database c# aspx

I am struggling a bit to populate my dropdown list, can anybody tell me where I am going wrong?
ASPX CODE it keeps looping after getting the connection string - back into the connection string method.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDropDownList();
}
}
private string GetConnectionString()
{
using (DataManager dmgr = new DataManager())
{
dmgr.Connect(ConfigurationManager.AppSettings["ProductionKey"]);
return BindDropDownList();
}
}
public string BindDropDownList()
{
DataTable dt = new DataTable();
SqlConnection connection = new SqlConnection(GetConnectionString());
try
{
connection.Open();
string sqlStatement = "SELECT * FROM Itemseriesmaster";
SqlCommand sqlCmd = new SqlCommand(sqlStatement, connection);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
DropDownList1.DataSource = dt;
DropDownList1.DataTextField = "Description"; // the items to be displayed in the list items
DropDownList1.DataValueField = "ID"; // the id of the items displayed
DropDownList1.DataBind();
}
}
catch (SqlException ex)
{
string msg = "Fetch Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
connection.Close();
}
return AppRelativeTemplateSourceDirectory;
}
DataManager Code - where the code calls into
public DataSet ItemSeriesMaster(int id, string description)
{
object[] args = new object[2] { id, description };
return CallSp(MethodBase.GetCurrentMethod(), args) as DataSet; // i know this is not an sp call.. just testing
}
}
}
I am trying to go to my database and bring out the list.

using Session for creating login for mutiple users has error and further which can evaluate the rights of users

I have tried many things but its just showing error "Object reference not set to an instance of an object."
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
else if (Session["StudId"] != null)
{
Label1.Text = Session["StudId"].ToString();
}
I have written this code in my login page dragging all the required databases strings i.e. typeid,students,faculty,admin and accemployee in the page.
public partial class Login : System.Web.UI.Page
{private string strcon = WebConfigurationManager.ConnectionStrings["StudentConnectionString1"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Request.Cookies["UName"] != null)
TextBox1.Text = Request.Cookies["UName"].Value;
if (Request.Cookies["PWD"] != null)
TextBox2.Attributes["value"] = Request.Cookies["PWD"].Value;
if (Request.Cookies["UName"] != null && Request.Cookies["PWD"] != null)
CheckBox1.Checked = true;
}
}
protected void Button1_Click1(object sender, EventArgs e)
{
if (DropDownList1.SelectedItem.Value == "1")
{
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("Select StudFirstName from Student where StudId=#sid and Password=#pw", con);
cmd.Parameters.AddWithValue("#sid", TextBox1.Text);
cmd.Parameters.AddWithValue("#pw", TextBox2.Text);
con.Open();
string name = Convert.ToString(cmd.ExecuteScalar());
con.Close();
if (String.IsNullOrEmpty(name))
Label1.Text = "Sorry! Invalid User ID or Password!";
else
{
if (CheckBox1.Checked)
{
Response.Cookies["UName"].Value = TextBox1.Text;
Response.Cookies["PWD"].Value = TextBox2.Text;
Response.Cookies["UName"].Expires = DateTime.Now.AddMonths(2);
Response.Cookies["PWD"].Expires = DateTime.Now.AddMonths(2);
}
Session.Add("StudId", TextBox1.Text);
Session.Add("StudFirstName", name);
Session.Add("Password", TextBox2.Text);
FormsAuthentication.RedirectFromLoginPage(name, false);
}
}
else if (DropDownList1.SelectedItem.Value == "2")
{
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("Select FacultyFirstName from Faculty where FacultyId=#fid and Password=#pw", con);
cmd.Parameters.AddWithValue("#fid", TextBox1.Text);
cmd.Parameters.AddWithValue("#pw", TextBox2.Text);
con.Open();
string name = Convert.ToString(cmd.ExecuteScalar());
con.Close();
if (String.IsNullOrEmpty(name))
Label1.Text = "Sorry! Invalid User ID or Password!";
else
{
if (CheckBox1.Checked)
{
Response.Cookies["UName"].Value = TextBox1.Text;
Response.Cookies["PWD"].Value = TextBox2.Text;
Response.Cookies["UName"].Expires = DateTime.Now.AddMonths(2);
Response.Cookies["PWD"].Expires = DateTime.Now.AddMonths(2);
}
Session["FacultyId"] = TextBox1.Text;
Session.Add("FacultyFisrtName", name);
Session["Password"] = TextBox2.Text;
FormsAuthentication.RedirectFromLoginPage(name, false);
}
}
else if (DropDownList1.SelectedItem.Value == "3")
{
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("Select AccEmployeeName from AccEmployee where AccEmployeeId=#aid and Password=#pw", con);
cmd.Parameters.AddWithValue("#aid", TextBox1.Text);
cmd.Parameters.AddWithValue("#pw", TextBox2.Text);
con.Open();
string name = Convert.ToString(cmd.ExecuteScalar());
con.Close();
if (String.IsNullOrEmpty(name))
Label1.Text = "Sorry! Invalid User ID or Password!";
else
{
if (CheckBox1.Checked)
{
Response.Cookies["UName"].Value = TextBox1.Text;
Response.Cookies["PWD"].Value = TextBox2.Text;
Response.Cookies["UName"].Expires = DateTime.Now.AddMonths(2);
Response.Cookies["PWD"].Expires = DateTime.Now.AddMonths(2);
}
Session["AccEmployeeFacultyId"] = TextBox1.Text;
Session.Add("AccEmployeeName", name);
Session["Password"] = TextBox2.Text;
FormsAuthentication.RedirectFromLoginPage(name, false);
}
}
else if (DropDownList1.SelectedItem.Value == "4")
{
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("Select from Admin where AdminId=#pid and Password=#pw", con);
cmd.Parameters.AddWithValue("#pid", TextBox1.Text);
cmd.Parameters.AddWithValue("#pw", TextBox2.Text);
con.Open();
string name = Convert.ToString(cmd.ExecuteScalar());
con.Close();
if (String.IsNullOrEmpty(name))
Label1.Text = "Sorry! Invalid User ID or Password!";
else
{
if (CheckBox1.Checked)
{
Response.Cookies["UName"].Value = TextBox1.Text;
Response.Cookies["PWD"].Value = TextBox2.Text;
Response.Cookies["UName"].Expires = DateTime.Now.AddMonths(2);
Response.Cookies["PWD"].Expires = DateTime.Now.AddMonths(2);
}
string adminName = "Pujan";
Session["AdminId"]=TextBox1.Text;
Session["AdminName"] = adminName;
Session["Password"]=TextBox2.Text;
FormsAuthentication.RedirectFromLoginPage(name, false);
}
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Label2.Text = DropDownList1.SelectedItem.Text;
}
`
}
.....................................................................................
Now the error occurs in the masterpage.master.cs which is shown below....
public partial class MasterPage : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["StudId"] == null)
Response.Redirect("Login.aspx");
else if (Session["StudId"] != null)
{
Label1.Text = Session["StudId"].ToString();
}
else if (Session["FacultyFirstName"] == null)
{
Response.Redirect("Login.aspx");
}
else if (Session["FacultyFirstName"] != null)
{
Label1.Text = Session["FacultyFirstName"].ToString();
}
else if (Session["AccEmployeeName"] == null)
{
Response.Redirect("Login.aspx");
}
else if (Session["AccEmployeeName"] != null)
{
Label1.Text = Session["AccEmployeeName"].ToString();
}
else if (Session["AdminName"] == null)
{
Response.Redirect("Login.aspx");
}
else if (Session["AdminName"] != null)
{
Label1.Text = Session["AdminName"].ToString();
}
}
protected void LinkButton1_Click1(object sender, EventArgs e)
{
FormsAuthentication.SignOut();
Response.Redirect("Login.aspx");
}
}
Please suggest me how to get rid of the error in session or wateva it is......Thank you in advance :)
System.NullReferenceException: Object reference not set to an instance of an object.
This error means that the value that is being provided is a null and the Server cannot use it for a process, that requires a parameter to work on.
Sometimes this happens when you're trying to use a variable in a method, and the variable gets a null value. Null value means that there is no value or no data for this thing.
In your code I guess that this error would generate when the site is first loading. At that time, there is no Session for the Server to load or work on. Thus the values are all null throwing this Null exception.
You can try to cover up the code inside an if else block to check whether there is a cookie present for the Session, or try out a try catch block to minimize this exception and do the work depending on the condition.
An example would be:
try {
/* your code here */
} catch (System.NullReferenceException) {
/* create a session or fill up the variable */
}
This block would run the code of yours, and if the exception provided inside the Catch method gets thrown it would execute the code inside the catch block.
Second thing was to use if else:
if(variable != null) {
/* your code here */
} else {
/* set the value */
}
You just check for the value of that particular variable, and check it. If its a null valued variable, then you can skip the execution of the code block and fill the variable with a value and then come back to the current space and re-execute it.
For exception details: http://msdn.microsoft.com/en-us/library/system.nullreferenceexception(v=vs.110).aspx

asp.net: upload images to SQL using imageupload

i have a database column 'images' which can hold binary data, for some reason the images doesnt want to upload. it doest pull any exceptions or aything wrong with the code:
here is extracts of the code
protected void BtnAdd_Click(object sender, EventArgs e)
{
string imgpath = FileUploadImage.FileName.ToString();
DBConnectivity.Add(imgpath);
}
here is the DBCoectivity Class:
public static void Add(string imgpath)
{
byte[] imgbt = null;
FileStream fstream = new FileStream(imgpath, FileMode.Open, FileAccess.Read);
BinaryReader BR = new BinaryReader(fstream);
imgbt = BR.ReadBytes((int)fstream.Length);
SqlConnection myConnection = GetConnection();
string myQuery = "INSERT INTO images( imagePath) VALUES ( #IMG )";
SqlCommand myCommand = new SqlCommand(myQuery, myConnection);
try
{
myConnection.Open();
myCommand.Parameters.Add(new SqlParameter("#IMG",imgbt));
myCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine("Exception in DBHandler", ex);
}
finally
{
myConnection.Close();
}
}
This snippet works for me:
byte[] imgbt = null;
if (FileUploadImage.HasFile)
{
Stream photoStream = FileUploadImage.PostedFile.InputStream;
imgbt = new byte[FileUploadImage.PostedFile.ContentLength];
photoStream.Read(imgbt, 0, FileUploadImage.PostedFile.ContentLength);
}
Also, you were inserting the image name (misspelled as parameter to Add method and bad choice of variable name as it is not a path) into the database, not the binary data. It should read:
string myQuery = "INSERT INTO images(imgbt) VALUES (#IMG)";
Here's a sample tutorial which explains it better:
File Upload with ASP.NET

ASP.NET Mysql Data Reader not working

I try to autentificate to a database, to create a Login function. Every time I press the button I receive this error: System.InvalidOperationException: The connection is not open. at MySql.Data.MySqlClient.MySqlConnection.Throw(Exception ex) at MySql.Data.MySqlClient.MySqlCommand.Throw(Exception ex) at MySql.Data.MySqlClient.MySqlCommand.Prepare() at start.CheckUserLogin(String username, String password) in c:\Users\RARES\Documents\Visual Studio 2010\WebSites\tem1\start.aspx.cs:line 46
Please tell me how can I read the data and check if the user and pass are the same as the ThextBox texts.
protected void Button1_Click(object sender, EventArgs e)
{
try
{
String sCon = "SERVER=localhost;DATABASE=sd_tema1;UID=root;";
MySqlConnection con = new MySqlConnection(sCon);
if (CheckUserLogin(Label2.Text, Label3.Text))
{
Response.Redirect("login.aspx");
}
}
catch (Exception ex)
{
Label1.Text = ex.ToString();
}
}
public Boolean CheckUserLogin(string username, string password)
{
try
{
String sCon = "SERVER=localhost;DATABASE=sd_tema1;UID=root;";
MySqlConnection con = new MySqlConnection(sCon);
String query = "Select * from users where username= ?userName and password= ?passWord";
MySqlCommand cmd = new MySqlCommand(query,con);
cmd.Parameters.Add("?userName", TextBox1.Text);
cmd.Parameters.Add("?passWord", TextBox2.Text);
cmd.Prepare();
MySqlDataReader print = cmd.ExecuteReader();
bool read = print.Read();
if(username.Equals(print.GetString("1")) && password.Equals(print.GetString("2"))) return true;
}
catch (Exception ex)
{
Label1.Text = ex.ToString();
}
return false;
}
You didn't open the connection before calling ExecuteReader method. Call con.Open. Your issue will be resolved.

Resources