Registration page error in .NET - c#

i'm a newbie in .NET and C# field.
I'm creating a Registration page to a website im working on.
i keep getting an error when registering to a website i'm creating. When entering my details, it doesn't register me to the database.
I created the a table in the database(i created a connectionString), and yet i cannot register - i get an exception that says "error,please try registering again" (as i did).
Does someone know what am i doing wrong?! Thanks!
here's my code and images:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
public partial class Registration : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RegisConnectionString"].ConnectionString);
con.Open();
string cmdStr = "Select count(*) from Table where Username='" + TextBox1Username.Text + "'";
SqlCommand userExist = new SqlCommand(cmdStr, con);
// int temp = Convert.ToInt32(userExist.ExecuteScalar().ToString());
con.Close();
/* if (temp == 1)
{
Response.Write("username already exists");
} */
}
}
protected void TextBox2_TextChanged(object sender, EventArgs e)
{
}
protected void Submit_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RegisConnectionString"].ConnectionStr ing);
con.Open();
string insCmd = "Insert into Table (Username, Password, EmailAddress,Fullname, City) values (#Username, #Password, #EmailAddress, #Fullname, #City)";
SqlCommand insertUser = new SqlCommand(insCmd, con);
insertUser.Parameters.AddWithValue("#Username", TextBox1Username.Text);
insertUser.Parameters.AddWithValue("#Password", TextBox2Password.Text);
insertUser.Parameters.AddWithValue("#EmailAddress", TextBox4Email.Text);
insertUser.Parameters.AddWithValue("#Password", TextBox2Password.Text);
insertUser.Parameters.AddWithValue("#City", TextBox6City.Text);
try
{
insertUser.ExecuteNonQuery();
con.Close();
Response.Redirect("Login.aspx");
}
catch (Exception er)
{
Response.Write("error,please try registering again");
}
}
}
image:
[URL=http://imageshack.us/photo/my-images/4/os6b.jpg/][IMG=http://img4.imageshack.us/img4/2526/os6b.jpg][/IMG][/URL]
Uploaded with [URL=http://imageshack.us]ImageShack.us[/URL]

you are missing fullname in your parameter and you have password twice.fix that and run it again.
Also, in your catch block.. you should use exception message to debug or log somewhere where you can see the error clearly. the way you have it right now gives the error you typed. not actual message.
here is link where they are discussing about sqlexception. might be good idea to catch that.
SqlException catch and handling

You pass two times the password parameter in the insert query. The second one is in place of the #fullname parameter.
This will cause your insert command to fail because you don't provide the #fullname parameter expected by the query.
SqlCommand insertUser = new SqlCommand(insCmd, con);
insertUser.Parameters.AddWithValue("#Username", TextBox1Username.Text);
insertUser.Parameters.AddWithValue("#Password", TextBox2Password.Text);
insertUser.Parameters.AddWithValue("#EmailAddress", TextBox4Email.Text);
insertUser.Parameters.AddWithValue("#FullName", TextBox???????.Text); //<- Get from the correct textbox
insertUser.Parameters.AddWithValue("#City", TextBox6City.Text);
You could have found this problem yourself if, inside the catch, you had added the er.Message to your Response
try
{
insertUser.ExecuteNonQuery();
con.Close();
Response.Redirect("Login.aspx");
}
catch (Exception er)
{
Response.Write("error: " + er.Message + " ,please try registering again");
}

Related

Why am I getting the error "There is already open data reader associated which must be closed first"?

I'm trying to make a simple accounts register page with requiredvalidator for textboxes and comparevalidator to confirm password.
the validators work fine.
When I inserted the correct data in correct format, I receive an error
" there is already open DataReader associated which must be closed first"
Why is it so? How do I fix it?
here are my c# codes
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class register : System.Web.UI.Page
{
static readonly string scriptErrorUserId =
"<script language=\"javascript\">\n" +
"alert (\"Error - Username you keyed in is taken up, please key in another Username\");\n" +
"</script>";
static readonly string scriptSuccessNewAccount =
"<script language=\"javascript\">\n" +
"alert (\"Your account has been succesfully created - Thank You!\");\n" +
"</script>";
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
SqlConnection mDB = new SqlConnection(#"Data Source=iipproject.database.windows.net;Initial Catalog=IIP Project;Integrated Security=False;User ID=beatrice135;Password=Tompel1997;Encrypt=False;TrustServerCertificate=False");
mDB.Open();
Type csType = this.GetType();
// check to ensure that UserId keyed in is not being in used by other Customers
SqlCommand cmd;
SqlDataReader rdr;
string strSQLSelect = "SELECT cUsername FROM Customer ORDER BY cUsername";
cmd = new SqlCommand(strSQLSelect, mDB);
rdr = cmd.ExecuteReader();
while (rdr.Read() == true)
{
if (txtUsername.Text == (string)rdr["cUsername"])
{
ClientScript.RegisterStartupScript(csType, "Error", scriptErrorUserId);
mDB.Close();
return;
}
}
// insert new record
string strSQLInsert = "INSERT INTO "
+ " Customer (cUsername, cPassword, cFirstName, cLastName, cAddress, cEmail, cPhone,cTitle,cGender,cPostalCode,cBirthDate)"
+ " VALUES (#username,#pw,#fn,#ln,#add,#email,#phone,#title,#gender,#postcode,#birthdate)";
cmd = new SqlCommand(strSQLInsert, mDB);
cmd.Parameters.AddWithValue("#uid", txtUsername.Text);
cmd.Parameters.AddWithValue("#pw", txtPassword.Text);
cmd.Parameters.AddWithValue("#fn", txtFirstName.Text);
cmd.Parameters.AddWithValue("#add", txtAddress.Text);
cmd.Parameters.AddWithValue("#email", txtEmail.Text);
cmd.Parameters.AddWithValue("#phone", txtPhone.Text);
cmd.Parameters.AddWithValue("#ln", txtLastName.Text);
cmd.Parameters.AddWithValue("#birthdate", txtBirthDate);
cmd.Parameters.AddWithValue("#postcode", txtPostalCode.Text);
cmd.Parameters.AddWithValue("#title", ddlTitle.SelectedItem.Text);
cmd.Parameters.AddWithValue("#gender", ddlGender.SelectedItem.Text);
cmd.ExecuteNonQuery();
mDB.Close();
ClientScript.RegisterStartupScript(csType, "Success", scriptSuccessNewAccount);
// prepare Session variables for newly registered customer
Session["sFlag"] = "T";
Session["sUsername"] = (string)txtUsername.Text;
Session["sFirstName"] = (string)txtFirstName.Text;
Session["sAddress"] = (string)txtAddress.Text;
Session["sEmail"] = (string)txtEmail.Text;
Session["sPhone"] = (string)txtPhone.Text;
Response.Redirect("default.aspx");
}
I believe the error is self-explanatory. After reading your data you have to dispose the reader:
...
while (rdr.Read() == true)
{
if (txtUsername.Text == (string)rdr["cUsername"])
{
ClientScript.RegisterStartupScript(csType, "Error", scriptErrorUserId);
mDB.Close();
return;
}
}
rdr.Close();
...
The error is self-explanatory. Please close the data reader after the while loop. rdr.close();
However as a good practice, please use using statement which will take care of closing the data reader or connection.

Execute scalar cannot pass password textbox, throws null exception

The code does connect to the database and actually check the username(number) and then exception runs when it has to get to verifying the password and a null reference is thrown
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnLogin_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Intellicell_CallCentreConnectionString"].ConnectionString);
conn.Open();
string checkuser = "SELECT COUNT(*) FROM Debtors WHERE MobilePhone='" + txtMobilePhone.Text + "'";
SqlCommand cmd = new SqlCommand(checkuser, conn);
int temp = Convert.ToInt32(cmd.ExecuteScalar().ToString());
conn.Close();
if (temp == 1)
{
conn.Open();
string CheckPasswordQuery = "SELECT IDNumber from Debtors WHERE MobilePhone='" + txtPassword.Text + "'";
SqlCommand passCmd = new SqlCommand(CheckPasswordQuery, conn);
string password = passCmd.ExecuteScalar().ToString().Replace(" ","");
conn.Close();
if (password == txtPassword.Text)
{
Session["New"] = txtMobilePhone.Text;
Response.Write("Password is correct!");
Response.Redirect("Home.aspx");
}
else
{
Response.Write("Password is not correct!");
}
}
else
{
Response.Write("Please Provide valid Login details!");
}
}
}
it is on line
string password = passCmd.ExecuteScalar().ToString().Replace(" ","");
that it breaks.
I suggest you if you want write sql adhoc, use string.format
It's clean
string checkuser = string.Format("SELECT COUNT(*) FROM Debtors WHERE MobilePhone={0},txtMobilePhone.Text);
Secondly, you can use using syntax , in order to clean your connection properly
I think, In the second sql you are using txtPassword.Text instead of txtMobilePhone.Text
The question is why are you getting the null execption, see this: https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar(v=vs.110).aspx
In summary ExecuteScaler returns a null (not a DBNull) if no rows are found, whence passCmd.ExecuteScalar().ToString().Replace(" ",""); null refences as its null.ToString()
You global logic looks flawed so hard to suggest exactly what to do, but passCmd.ExecuteScalar()?.ToString().Replace(" ","") will suppress the exeception.

Adding values of one table into another with INSERT INTO ... SELECT

I need to add value to table sales(acnum,scriptname,shares_bought) from transac(acnum,scriptname,Quantity,Price) using c# in visual studio 2008. I am using the code shown below, but it is not inserting value into sales database.
It is not showing any error or exception but its not updating sales table also.
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection Con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
Con.Open();
string insertsale = "INSERT INTO sales(acnum, scriptname, shares_bought) select acnum,scriptname,Quantity from transac";
SqlCommand cmd = new SqlCommand(insertsale, Con);
cmd.ExecuteNonQuery();
Con.Close();
}
catch (Exception ex)
{
Response.Write("error" + ex.ToString());
}
}
The problem was that I had used PostUrl for the button click . . so i think it was redirecting to the nextpage without processing the code. Now its fixed .

NullReferenceException i am familiar with them, but cannot solve on this occasion

im fairly new to ASP.net but i am familiar with Null reference exceptions however i cant solve this one. Im trying to collect data from a webform and pass it to my database through a connection string, this is when the exception occurs.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
public partial class Register : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (IsPostBack)
{
SqlConnection studConnA = new SqlConnection(ConfigurationManager.ConnectionStrings["StudConnection"].ConnectionString);
studConnA.Open();
string checkuser = "select count(*) from StudTable where Name='" + TextBoxName.Text + "'";
SqlCommand studComA = new SqlCommand(checkuser, studConnA);
int temp = Convert.ToInt32(studComA.ExecuteScalar().ToString());
if (temp == 1)
{
Response.Write("User already Exists");
}
studConnA.Close();
}
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
}
protected void Button1_Click(object sender, System.EventArgs e)
{
try
{
SqlConnection studConn = new SqlConnection(ConfigurationManager.ConnectionStrings["StudConnectionString"].ConnectionString);
studConn.Open();
string insertQuery = "insert into StudTable (Name,Email,Age,Continent,School,Password) values (#name,#email,#age,#cont,#school,#pass)";
SqlCommand studCom = new SqlCommand(insertQuery, studConn);
studCom.Parameters.AddWithValue("#name", TextBoxName.Text);
studCom.Parameters.AddWithValue("#email", TextBoxEmail.Text);
studCom.Parameters.AddWithValue("#age", TextBoxAge.Text);
studCom.Parameters.AddWithValue("#cont",DropDownCont.SelectedItem.ToString());
studCom.Parameters.AddWithValue("#school", TextBoxSchool.Text);
studCom.Parameters.AddWithValue("#pas", TextBoxPass.Text);
studCom.ExecuteNonQuery();
Response.Redirect("Backend.aspx");
Response.Write("Your Registration is Sucessful");
studConn.Close();
}
catch (Exception ex)
{
Response.Write("Error:" +ex.ToString());
}
}
}
The null reference occurs at line 19
Line 17: if (IsPostBack)
Line 18: {
Line 19: SqlConnection studConnA = new SqlConnection(ConfigurationManager.ConnectionStrings["StudConnection"].ConnectionString);
Line 20: studConnA.Open();
Line 21: string checkuser = "select count(*) from StudTable where Name='" + TextBoxName.Text + "'";
I believe the issue is in the syntax of my connection string but im not sure,
Can anyone help me to solve this?
Check your configuration file for the following key:
<connectionStrings>
<add name="StudConnection" connectionString="YOUR DETAILS" />
</connectionStrings>
If it doesn't exist, add the right key and retry.
You can also check the issue with the following code:
if (IsPostBack)
{
// if this line fails, then you don't have the proper connection string
// element in the config file.
Debug.Assert(ConfigurationManager.ConnectionStrings["StudConnection"] != null);
SqlConnection studConnA = new SqlConnection(ConfigurationManager.ConnectionStrings["StudConnection"].ConnectionString);
studConnA.Open();
string checkuser = "select count(*) from StudTable where Name='" + TextBoxName.Text + "'";
SqlCommand studComA = new SqlCommand(checkuser, studConnA);
int temp = Convert.ToInt32(studComA.ExecuteScalar().ToString());
if (temp == 1)
{
Response.Write("User already Exists");
}
studConnA.Close();
}
It would appear that there is no connection string named StudConnection configured.

can't display "wrong pw"

I have this simple login page below ,
if I enter correct ID + pw -> success (which I want)
if I enter wrong ID -> wrong login (which I want)
But if I enter correct ID + wrong ID , I Want it to say wrong password.
How can I do it?
Thank you.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["X"] != null)
{
Response.Redirect("MemberPage.aspx");
}
}
SqlConnection cnn = new SqlConnection("Initial Catalog=Northwind;Data Source=localhost;Integrated Security=SSPI;");
protected void Button1_Click(object sender, EventArgs e)
{
cnn.Open();
SqlCommand cmd = new SqlCommand("SELECT FirstName,LastName FROM Employees", cnn);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
if (TextBox1.Text == dr.GetString(0) || TextBox2.Text == dr.GetString(1))
{
Session["x"] = TextBox1.Text;
Response.Redirect("MemberPage.aspx");
}
else
{
Label2.Text = "wrong login";
}
}
}
cnn.Close();
}
protected void Button2_Click(object sender, EventArgs e)
{
Response.Redirect("Register.aspx");
}
}
while this doesn't answer your question, I see a MAJOR security flaw with your logic. I think no matter what failure your users encounter, invalid username or invalid password, you should always display the same "invalid login" message.
If you have someone who is attempting to break into the system, once you validate that a user account exists (invalid password) they can then begin to crack that specific account's password using brute force.
Just something to think about.
You are putting your logic wrongly here. the logic will be
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["X"] != null)
{
Response.Redirect("MemberPage.aspx");
}
}
SqlConnection cnn = new SqlConnection("Initial Catalog=Northwind;Data Source=localhost;Integrated Security=SSPI;");
protected void Button1_Click(object sender, EventArgs e)
{
cnn.Open();
SqlCommand cmd = new SqlCommand("SELECT FirstName,LastName FROM Employees", cnn);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
if (TextBox1.Text.Trim() == dr.GetString(0) || TextBox2.Text.Trim()== dr.GetString(1))
{
if (TextBox2.Text.Trim()== dr.GetString(1))
{
Session["x"] = TextBox1.Text.Trim();
Response.Redirect("MemberPage.aspx");
}
else
{
Label2.Text = "wrong password";
}
}
else
{
Label2.Text = "wrong login";
}
}
cnn.Close();
}
protected void Button2_Click(object sender, EventArgs e)
{
Response.Redirect("Register.aspx");
}
}
You read the firstname and the lastname from the database, but then check for the password against the lastname. I doubt that this field contains a valid password
A part from this logic error, you should use a WHERE clause in your statement to check if the user is present or not in the database.
protected void Button1_Click(object sender, EventArgs e)
{
// Command with parameters that check if a user with the supplied credentials exists
// If the user exists then just one record is returned from the datatable....
string cmdText = "SELECT FirstName,LastName " +
"FROM Employees " +
"WHERE username=#uname and pass=#pwd";
using(SqlConnection cnn = new SqlConnection(.....))
using(SqlCommand cmd = new SqlCommand(cmdText, cnn))
{
cnn.Open();
cmd.Parameters.AddWithValue("#uname", TextBox1.Text);
cmd.Parameters.AddWithValue("#pwd", TextBox2.Text);
using(SqlDataReader reader = cmd.ExecuteReader())
{
// If the Read returns true then a user with the supplied credentials exists
// Only one record is returned, not the whole table and you don't need to
// compare every record against the text in the input boxes
if(reader.Read())
{
Session["x"] = reader.GetString(0);
Response.Redirect("MemberPage.aspx");
}
else
{
Label2.Text = "Invalid credentials";
}
}
}
}
Another point to keep in mind is the following. In the database you should not have a password in clear text. The correct way to store password is to store an hashed string corresponding to the password and then applying the hashing function to the user input and check for same hashed string in the database

Categories

Resources