ASP.NET Mysql Data Reader not working - asp.net

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.

Related

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 Dapper to select data from MS SQL

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

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

Not able to connect to database in ASP IIS

I was able to deloy my asp project on IIS and it shows the front page, there I have a login page , after entering the credentials it does not logs in, I used try and catch , and in catch it gave me an error, stating thread has aborted, it was on
page.redirect["master.apsx",true]
so I changed it to
page.redirect["master.aspx",false]
and it didnt gave error, but it was not able to login further, I guess it is not able to connect to database. So any help would be appreciable.
Thanks
CODE:
protected void Page_Load(object sender, EventArgs e)
{
strconn = #"Data Source=.\SQLEXPRESS;AttachDbFilename=" + Server.MapPath("~/App_Data/Securityservice.mdf") + ";Integrated Security=True;User Instance=True";
Label1.Text = " conn string";
}
protected void Button2_Click(object sender, EventArgs e)
{
}
protected void btn_popup_quick_login_Click(object sender, EventArgs e)
{
try
{
if (txt_username.Text != null)
{
if (txt_password.Text != null)
{
DataTable dt = new DataTable();
conn = new SqlConnection(strconn);
conn.Open();
cmd = new SqlCommand("Select * From UserMaster Where Username=#username and Password=#password", conn);
cmd.Parameters.AddWithValue("#username", txt_username.Text);
cmd.Parameters.AddWithValue("#password", txt_password.Text);
da = new SqlDataAdapter(cmd);
da.Fill(dt);
{
if (dt.Rows.Count > 0)
{
userloginname = txt_username.Text;
userloginpassword = txt_password.Text;
Session["username"] = txt_username.Text;
MessageBox.Show("User Login Sucessfully", "Login", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
Response.Redirect("Marketing.aspx",false);
}
else
{
Label1.Text = "else part";
MessageBox.Show("Invalid User Name and Password", "Login", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
txt_username.Focus();
}
txt_username.Text = "";
txt_password.Text = "";
}
}
}
}
catch (Exception ex) { MessageBox.Show(ex.Message,"Error",MessageBoxButtons.OK,MessageBoxIcon.Error); }
conn.Close();
Label1.Text = "login";
}
You should check the connection strings in web.config, to make sure they still point to the proper location of the database after you deployed the site.
I think the problem could be the Application_Start method.
Look if you have written some thing there.
Make a break point there and see is there any error.
Or have you written Response.End() in you code?
You need to provide more detail
You need to check weather you are able to connect to database or not.
You also need to check weather the page is called or not (which comes after login).

update cancel on gridview asp.net

I am trying to update a gridview on asp.net using a stored procedure but it always resets to the original values. What am I doing wrong?
edit: all page code added now
protected void page_PreInit(object sender, EventArgs e)
{
MembershipUser UserName;
try
{
if (User.Identity.IsAuthenticated)
{
// Set theme in preInit event
UserName = Membership.GetUser(User.Identity.Name);
Session["UserName"] = UserName;
}
}
catch (Exception ex)
{
string msg = ex.Message;
}
}
protected void Page_Load(object sender, EventArgs e)
{
userLabel.Text = Session["UserName"].ToString();
SqlDataReader myDataReader = default(SqlDataReader);
SqlConnection MyConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["RescueAnimalsIrelandConnectionString"].ConnectionString);
SqlCommand command = new SqlCommand("sp_EditRescueDetails", MyConnection);
if (!User.Identity.IsAuthenticated)
{
}
else
{
command.Parameters.AddWithValue("#UserName", userLabel.Text.Trim());
}
try
{
command.CommandType = CommandType.StoredProcedure;
MyConnection.Open();
myDataReader = command.ExecuteReader(CommandBehavior.CloseConnection);
// myDataReader.Read();
GridViewED.DataSource = myDataReader;
GridViewED.DataBind();
if (GridViewED.Rows.Count >= 1)
{
GridViewED.Visible = true;
lblMsg.Visible = false;
}
else if (GridViewED.Rows.Count < 1)
{
GridViewED.Visible = false;
lblMsg.Text = "Your search criteria returned no results.";
lblMsg.Visible = true;
}
MyConnection.Close();
}
catch (SqlException SQLexc)
{
Response.Write("Read Failed : " + SQLexc.ToString());
}
}
//to edit grid view
protected void GridViewED_RowEditing(object sender, GridViewEditEventArgs e)
{
GridViewED.EditIndex = e.NewEditIndex;
}
protected void GridViewED_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
SqlConnection MyConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["RescueAnimalsIrelandConnectionString"].ConnectionString);
SqlCommand command = new SqlCommand("sp_UpdateRescueDetails", MyConnection);
if (!User.Identity.IsAuthenticated)
{
}
else
{
command.Parameters.AddWithValue("#UserName", userLabel.Text.Trim());
command.Parameters.Add("#PostalAddress", SqlDbType.VarChar).Value = ((TextBox)GridViewED.Rows[e.RowIndex].Cells[0].Controls[0]).Text;
command.Parameters.Add("#TelephoneNo", SqlDbType.VarChar).Value = ((TextBox)GridViewED.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
command.Parameters.Add("#Website", SqlDbType.VarChar).Value = ((TextBox)GridViewED.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
command.Parameters.Add("#Email", SqlDbType.VarChar).Value = ((TextBox)GridViewED.Rows[e.RowIndex].Cells[3].Controls[0]).Text;
}
command.CommandType = CommandType.StoredProcedure;
MyConnection.Open();
command.ExecuteNonQuery();
MyConnection.Close();
GridViewED.EditIndex = -1;
}
I suspect the code loading the grid is being invoked upon postback, which is causing the data to be pulled from the database when you don't want it to.
Yes - I think you want the code to only load if it is not a postback. You can use the Page.IsPostBack property for this.
Something like this:
protected void Page_Load(object sender, EventArgs e)
{
userLabel.Text = Session["UserName"].ToString();
if (!IsPostBack) {
SqlDataReader myDataReader = default(SqlDataReader);
SqlConnection MyConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["RescueAnimalsIrelandConnectionString"].ConnectionString);
SqlCommand command = new SqlCommand("sp_EditRescueDetails", MyConnection);
if (!User.Identity.IsAuthenticated)
{
}
else
{
command.Parameters.AddWithValue("#UserName", userLabel.Text.Trim());
}
try
{
command.CommandType = CommandType.StoredProcedure;
MyConnection.Open();
myDataReader = command.ExecuteReader(CommandBehavior.CloseConnection);
// myDataReader.Read();
GridViewED.DataSource = myDataReader;
GridViewED.DataBind();
if (GridViewED.Rows.Count >= 1)
{
GridViewED.Visible = true;
lblMsg.Visible = false;
}
else if (GridViewED.Rows.Count < 1)
{
GridViewED.Visible = false;
lblMsg.Text = "Your search criteria returned no results.";
lblMsg.Visible = true;
}
MyConnection.Close();
}
catch (SqlException SQLexc)
{
Response.Write("Read Failed : " + SQLexc.ToString());
}
}
}
Don't bind your data in the Page_Load event. Create a separate method that does it, then in the Page Load, if !IsPostback, call it.
The reason to perform the databinding is it's own method is because you'll need to call it if you're paging through the dataset, deleting, updating, etc, after you perform the task. A call to a method is better than many instances of the same, repetitive, databinding code.

Resources