Data Reader and Invalid attempt to read when no data is present - asp.net

This is my code:
protected void logujButton_Click(object sender, EventArgs e)
{
string user = "data source=myHostServer; database = myDataBase; user id=myLogin; password=myPassword";
SqlConnection con2 = new SqlConnection(user);
con2.Open();
string loguj = "select count(*) from uzytkownik where Login = '"+ logujTextBox.Text +"'";
SqlCommand command = new SqlCommand(loguj, con2);
int wartosc = Convert.ToInt32(command.ExecuteScalar().ToString());
con2.Close();
if (wartosc == 1)
{
con2.Open();
SqlCommand pobierzHaslo = new SqlCommand("select Haslo from uzytkownik where Login = '" + logujTextBox.Text + "'", con2);
SqlDataReader rdr = pobierzHaslo.ExecuteReader();
string haslo = rdr["Haslo"].ToString();
if (haslo == hasloTextBox.Text)
{
errorLabel.Text = "Prawidlowe Haslo !";
}
else
{
errorLabel.Text = "Zle haslo !";
}
}
else
{
errorLabel.Text = "Taki uzytkownik nie istnieje !";
}
}
When I press button, this error is appearing: "Invalid attempt to read when no data is present". Could You tell me, where i made mistake ?. Thanks for advise !

You haven't read anything from the reader yet. You have to call the Read() method:
SqlDataReader rdr = pobierzHaslo.ExecuteReader();
if (rdr.Read())
{
string haslo = rdr["Haslo"].ToString();
....
}

If you have access to SSMS, run the query directly in a query window and make sure that you get data back. Your query may be bad. It is most likely an error from the ExecuteReader method of your SqlDataReader, based on the text of the error message.

Related

how to auto login after registration in asp.net

I want to login automatically after registration by using a session like Session["ud"] , but I don't know where should I put it.
public partial class index : System.Web.UI.Page
{
SqlConnection cnn = new SqlConnection(ConfigurationManager.AppSettings["dbpath"]);
protected void btnSave_Click(object sender, EventArgs e)
{
long idx;
SqlCommand cmd = new SqlCommand();
cmd.Connection = cnn;
cmd.CommandText = "Insert into tblUser (UInfo,UEmail,UName,UPass, UGender) Values (#P1,#P2,#P3,#P4,#P5) select ##Identity";
cmd.Parameters.AddWithValue("#P1", txtInfo.Text);
cmd.Parameters.AddWithValue("#P2", txtEmail.Text);
cmd.Parameters.AddWithValue("#P3", txtUserName.Text);
cmd.Parameters.AddWithValue("#P4", txtPass.Text);
cmd.Parameters.AddWithValue("#P5", rdbMale.Checked);
cnn.Open();
idx = Convert.ToInt64(cmd.ExecuteScalar()); // i think here we can do something
cnn.Close();
here we want to upload the image of user and it works correctly
string fn = "";
if (FileUpload1.HasFile == true)
{
fn = FileUpload1.FileName;
string des = Server.MapPath("\\UserImg\\") + idx.ToString() + ".jpg";
FileUpload1.PostedFile.SaveAs(des);
SqlCommand cmdUpdate = new SqlCommand();
cmdUpdate.Connection = cnn;
cmdUpdate.CommandText = "Update tblUser Set UImg=#P5 where UId=#P0";
cmdUpdate.Parameters.AddWithValue("#P5", idx.ToString() + ".jpg");
cmdUpdate.Parameters.AddWithValue("#P0", idx);
cnn.Open();
cmdUpdate.ExecuteNonQuery();
cnn.Close();
}
Response.Redirect("Profile.aspx");
}
}
once you have entered data into in sql database you will get id of new user here
idx = Convert.ToInt64(cmd.ExecuteScalar()); // i think here we can do something
Once you get the id assign it to your session
idx = Convert.ToInt64(cmd.ExecuteScalar()); // i think here we can do something
cnn.Close();
Session["ud"]=idx;
once you have assigned session ,you just have to redirect to required page and validate Session variable if it's null or not.
i hope on Profile.aspx page you are checking for same session variable.
Profile.aspx.cs--on page load
if (Session["ud"] != null)
{
//successfull login
}
else
{
//redirect to login page
}

change password in asp.net,c#,ms-access database

i am desiging a change password screen in asp.net,c#,MS-access database
i m having 4 fields
userid,
oldpassword,
newpassword
confirm password
NOW I M NOT GETTING RESULT THE COUNT RETURNS 0 I HAVE UPDATED MY CODE
my code is as follows
try
{
OleDbConnection myCon = new OleDbConnection(ConfigurationManager.ConnectionStrings["vhgroupconnection"]
.ConnectionString);
myCon.Open();
string userid = txtuserid.Text;
string oldpass = txtoldpass.Text;
string newPass = txtnewpass.Text;
string conPass = txtconfirmpass.Text;
string q = "select user_id,passwd from register where user_id = #userid and passwd = #oldpass";
OleDbCommand cmd = new OleDbCommand(q, myCon);
cmd.Parameters.AddWithValue("#userid", txtuserid.Text);
cmd.Parameters.AddWithValue("#oldpass", txtoldpass.Text);
OleDbDataReader re = cmd.ExecuteReader();
re.Read();
if (re["user_id"].ToString() != String.Empty && re["passwd"].ToString() != String.Empty)
{
if (newPass.Trim() != conPass.Trim())
{
lblmsg.Text = "New Password and old password does not match";
}
else
{
q = "UPDATE register SET passwd = #newPass WHERE user_id =#userid";
cmd = new OleDbCommand(q, myCon);
cmd.Parameters.AddWithValue("#userid", txtuserid.Text);
cmd.Parameters.AddWithValue("#newPasss", txtnewpass.Text);
int count = cmd.ExecuteNonQuery();
if (count > 0)
{
lblmsg.Text = "Password changed successfully";
}
else
{
lblmsg.Text = "password not changed";
}
}
}
}
catch(Exception ex)
{
throw ex;
}
plz help me to solve the error
You're getting the error, No constructor is defined, because you can't directly instantiate this object. As stated on MSDN:
To create an OleDbDataReader, you must call the ExecuteReader method
of the OleDbCommand object, instead of directly using a constructor.
Essentially, you'd do something like the following after creating your connection and specifying your query:
OleDbDataReader re = cmd.ExecuteReader();

ASP.Net insert data from form to a database Exception

I'm trying to insert data from a form to my database and it is throwing this error:
No mapping exists from object type System.Web.UI.WebControls.TextBox to a known managed provider native type.
Maybe it has to do with the fact that I try to get a data from a dropdownlist and I'm not really sure the syntax is great.
Here is the code:
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=MICROSOF-58B8A5\\SQL_SERVER_R2;Initial Catalog=Movie;Integrated Security=True");
conn.Open();
string titleName = Title.Text;
string sqlQuery = ("INSERT INTO Movies(Ganere, Title, Descreption) VALUES (#Ganere, #Title , #Descreption) ");
SqlCommand cmd = new SqlCommand(sqlQuery, conn);
cmd.Parameters.AddWithValue("Title", Title);
string genre = GenreDropDown.SelectedIndex.ToString();
cmd.Parameters.AddWithValue("Ganere", GenreDropDown);
string descp = Descreption.Text;
cmd.Parameters.AddWithValue("Descreption", Descreption);
if (titleName == null || genre == null)
{
ErrorMessege.Text = "Please fill all of the fields.";
}
else
{
ErrorMessege.Text = "You have successfully add a movie!";
cmd.ExecuteNonQuery();
}
conn.Close();
}
You -weren't using any of the vars where you had the values
string titleName = Title.Text;
string sqlQuery = ("INSERT INTO Movies(Ganere, Title, Descreption) VALUES (#Ganere, #Title , #Descreption) ");
SqlCommand cmd = new SqlCommand(sqlQuery, conn);
cmd.Parameters.AddWithValue("Title", titlename);
string genre = GenreDropDown.SelectedIndex.ToString();
cmd.Parameters.AddWithValue("Ganere", genre);
string descp = Descreption.Text;
cmd.Parameters.AddWithValue("Descreption", descp);
if (titleName == null || genre == null)
{
ErrorMessege.Text = "Please fill all of the fields.";
}
else
{
ErrorMessege.Text = "You have successfully add a movie!";
cmd.ExecuteNonQuery();
}
conn.Close();
}
The problem is that you are trying to use the entire textbox as the value to the parameter.
Change:
cmd.Parameters.AddWithValue("Title", Title);
to
cmd.Parameters.AddWithValue("Title", Title.Text);

How to check if email is already in use in asp.net and making sure email is available before allowing the user to register?

I need to check an SQL Server database (not asp.net membership) to see if an email is already in use before allowing the user to register.
I have tried using the information in this website but it does not seem to work.
Your help will be much appreciated
You can try
protected void txtUsername_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txtUsername.Text))
{
SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB");
con.Open();
SqlCommand cmd = new SqlCommand("select * from UserInformation where UserName like " + txtUsername.Text.Trim(), con);//I changed
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
checkusername.Visible = true;
imgstatus.ImageUrl = "NotAvailable.jpg";
lblStatus.Text = "UserName Already Taken";
}
else
{
checkusername.Visible = true;
imgstatus.ImageUrl = "Icon_Available.gif";
lblStatus.Text = "UserName Available";
}
con.Close();//I added
}
else
{
checkusername.Visible = false;
}
}

loop in select statment

protected void Button1_Click(object sender, EventArgs e)
{
if (firstname_tb.Text == "" || lastname_tb.Text == "" || email_tb.Text == "" || reemail_tb.Text == "" || pass_tb.Text == "" || gender_ddl.SelectedItem.Text == "" || day_ddl.SelectedItem.Text == "" || year_ddl.SelectedItem.Text == "")
{
Label9.Text = "please fill all data";
Label9.Visible = true;
}
else
{
str = email_tb.Text;
SqlConnection con = new SqlConnection(#"Data Source=SAMA-PC\SQLEXPRESS;Initial Catalog=meral10;Integrated Security=True");
SqlCommand comsel = new SqlCommand("SELECT email from reg ",con);
con.Open();
comsel.ExecuteNonQuery();
con.Close();
foreach (var v in comsel.Parameters.ToString())
{
if (v.ToString() == str)
{
Label9.Text = "this email already exist choose another one";
Label9.Visible = true;
b = false;
break;
}
else
{
b = true;
}
}
if (b==true)
{
birthday = day_ddl.Text + "/" + month_ddl.Text + "/" + year_ddl.Text;
SqlCommand com = new SqlCommand("INSERT INTO reg(first_name,last_name,email,email_ver,pass,gender,birthday) values(#fn,#ln,#email,#reemail,#pass,#gen,#birth)", con);
con.Open();
com.Parameters.AddWithValue("#fn", firstname_tb.Text);
com.Parameters.AddWithValue("#ln", lastname_tb.Text);
com.Parameters.AddWithValue("#email", email_tb.Text);
com.Parameters.AddWithValue("#reemail", reemail_tb.Text);
com.Parameters.AddWithValue("#pass", pass_tb.Text);
com.Parameters.AddWithValue("#gen", gender_ddl.SelectedItem.Text);
com.Parameters.AddWithValue("#birth", birthday);
com.ExecuteNonQuery();
con.Close();
Label9.Text = "thank you for registration";
Label9.Visible = true;
}
else
{
Label9.Text = "this email already exist choose another one";
Label9.Visible = true;
}
}
There is a problem that is when I try to enter email allready exist in the database it enterd while it must show to the user that this email already exist in the data base. Can any one help me?
OK as far as I can understand, you only want the INSERT to occur if the email is unique in the [reg].[email] field. This will happen if b == true. The logic you use for this is basically correct, but you are not retrieving the results of the database correctly. Try something like:
con.Open();
System.Data.SqlClient.SqlDataReader objReader = comsel.ExecuteReader();
while (objReader.Read())
{
if ((String)objReader("email") == str)
{
Label9.Text = "this email already exist choose another one";
Label9.Visible = true;
b = false;
break;
}
else
{
b = true;
}
}
con.Close();
Hopefully that will work as intended.
On a side note, I would be remiss not to mention that this approach is pretty inefficient. A better idea would be to use a query like this:
SELECT [email] FROM [reg] WHERE [email] = #email;
In which you specify your variable "str" as a parameter in a similar manner to the INSERT operation below. Then instead of iterating through the results, simply check to see if the SqlDataReader has any rows:
SqlConnection con = new SqlConnection(#"Data Source=SAMA-PC\SQLEXPRESS;Initial Catalog=meral10;Integrated Security=True");
SqlCommand comsel = new SqlCommand("SELECT [email] FROM [reg] WHERE [email] = #email;",con);
comsel.Parameters.AddWithValue("#email", str);
System.Data.SqlClient.SqlDataReader objReader = comsel.ExecuteReader();
if (objReader.HasRows())
{
b = false;
}
else
{
b = true;
}
con.Close();
Remove the if statement checking for field entries and add RequiredValidators to your form:
https://web.archive.org/web/20211020145950/https://www.4guysfromrolla.com/webtech/090200-1.shtml
As for the second part.. if email already exists... create a custom validator for this and use this to display the message to your user if the email already exists. Note that you're using ExecuteNonQuery() here for what is essentially a query...
You also need some "separation of concerns". For example, put the connection string in the Web.Config. Do your data access from a DAL class, etc
For the first query, you can just use ExecuteScalar as that will return a single value from your query. I rewrote your query so that it will do a count of the emails that match the email the user is trying to use. If the count returned is 0, then you know that the email is currently not in use.
string strEmail = email_tb.Text.Trim();
try
{
using(SqlConnection conn = new SqlConnection(#"Data Source=SAMA-PC\SQLEXPRESS;Initial Catalog=meral10;Integrated Security=True"))
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT COUNT(1) FROM reg WHERE email = #email", conn);
cmd.Parameters.AddWithValue("#email", strEmail);
int count = (int)cmd.ExecuteScalar();
if(count==0)
{
birthday = day_ddl.Text + "/" + month_ddl.Text + "/" + year_ddl.Text;
SqlCommand cmdInsert = new SqlCommand("INSERT INTO reg(first_name,last_name,email,email_ver,pass,gender,birthday) values(#fn,#ln,#email,#reemail,#pass,#gen,#birth)", conn);
cmdInsert.Parameters.AddWithValue("#fn", firstname_tb.Text);
cmdInsert.Parameters.AddWithValue("#ln", lastname_tb.Text);
cmdInsert.Parameters.AddWithValue("#email", email_tb.Text);
cmdInsert.Parameters.AddWithValue("#reemail", reemail_tb.Text);
cmdInsert.Parameters.AddWithValue("#pass", pass_tb.Text);
cmdInsert.Parameters.AddWithValue("#gen", gender_ddl.SelectedItem.Text);
cmdInsert.Parameters.AddWithValue("#birth", birthday);
cmdInsert.ExecuteNonQuery();
Label9.Text = "thank you for registration";
Label9.Visible = true;
}
else
{
Label9.Text = "this email already exist choose another one";
Label9.Visible = true;
}
}
}
catch(SqlException ex)
{
// log your exception then display a friendly message to user
Label9.Text = "An error occurred while trying to save your registration";
}

Resources