Execute scalar cannot pass password textbox, throws null exception - c#

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.

Related

How to get a value from a query and compare it with a string?

Here is the schema of my Society Table:
Society(SocietyName, Email, Password, Status)
So basically I'm creating a login page in which user enters Email and password. If there is an email which matches the one in database then it checks that whether status is equal to president or faculty member or Student Affairs Office. Based on that , it redirects to different pages.
Following is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication3 {
public partial class WebForm1 : System.Web.UI.Page {
MySql.Data.MySqlClient.MySqlConnection conn;
MySql.Data.MySqlClient.MySqlCommand cmd;
MySql.Data.MySqlClient.MySqlDataReader reader;
String QueryStr;
String name;
protected void Page_Load(object sender, EventArgs e) { }
protected void clicked(object sender, EventArgs e) {
String ConnString = System.Configuration.ConfigurationManager.ConnectionStrings["Webappconstring"].ToString();
conn = new MySql.Data.MySqlClient.MySqlConnection(ConnString);
conn.Open();
String QueryStr2 = "";
QueryStr = "";
QueryStr = "Select * from the_society_circle.society WHERE Email= '" + Emailtxt.Text + "' And Psswd=' " + passwordtxt.Text + "'";
cmd = new MySql.Data.MySqlClient.MySqlCommand(QueryStr, conn);
reader = cmd.ExecuteReader();
QueryStr2 = "Select Status from the_society_circle.society where Email = '" + QueryStr + "'";
name = "";
while (reader.HasRows && reader.Read()) {
name = reader["Email"].ToString();
}
if ((QueryStr2== "president" || QueryStr2 == "faculty member") && reader.HasRows ) {
Session["Email"] = name;
Response.BufferOutput = true;
Response.Redirect("WebForm2.aspx", true);
} else {
Emailtxt.Text = "invalid user";
}
conn.Close();
}
}
}
The problem is that if statement is never executed and it always prints invalid user.
PS: Im new to web development :D
You set QueryString2 to this value
QueryStr2 = "Select Status from the_society_circle.society where Email = '" + QueryStr + "'";
It can never be one of the values you check for.
As codemonkey already wrote, your condition will never come true.
You do the following: if ((QueryStr2== "president" || Quer... which evaluates to if (("Select Status from the_society_circle.society where Email = '" + QueryStr + "'"== "president" || Quer.... So you're comparing two different strings, which will never succeed.
I tried to refactor your code and came up with this (not tested, wrote from scratch):
First put your database-related code into a separate class (MySqlAccess) and dispose the database objects (put them into using-blocks which invokes Dispose() on leaving the block).
Don't use the user-inputs in your sql query directly. Remember "all input is evil". So better use parameterized-queries.
The reason your comparison failed was that you didn't execute your second query. Now the code executes just one query and returns the status of the user.
So to sum up:
Have SQL Injection and other malicious actions in mind. For example have a look at this article: http://msdn.microsoft.com/en-us/library/ms161953%28v=sql.105%29.aspx
And never store passwords as clear text in your database. That's the next thing you should care about. Edit your database to store the passwords as salted password hashes and just compare the hashes. For a starting point, have look at this article: http://www.codeproject.com/Articles/704865/Salted-Password-Hashing-Doing-it-Right
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MySql;
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
private string _connectionString;
protected void Page_Load(object sender, EventArgs e)
{
_connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Webappconstring"].ToString();
}
protected void Clicked(object sender, EventArgs e)
{
string email = Emailtxt.Text;
string password = passwordtxt.Text;
var mysqlAccess = new MySqlAccess(_connectionString);
string status = mysqlAccess.GetStatus(email, password);
if (status == Constants.Status.PRESIDENT || status == Constants.Status.FACULTY_MEMBER)
{
Session["Email"] = email;
Response.Redirect("WebForm2.aspx", true);
}
else
{
Emailtxt.Text = "invalid user";
}
}
}
internal class MySqlAccess
{
private readonly string _connectionString;
public MySqlAccess(string connectionString)
{
_connectionString = connectionString;
}
public string GetStatus(string email, string password)
{
using (var conn = new MySqlConnection(_connectionString))
{
conn.Open();
string query = "SELECT Status FROM the_society_circle.society WHERE Email=#Email AND Psswd=#Password;";
using (var cmd = new MySqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("#Email", email);
cmd.Parameters.AddWithValue("#Password", password);
using (var reader = cmd.ExecuteReader())
{
if (reader.HasRows && reader.Read())
{
return reader["Status"].ToString();
}
}
}
}
return string.Empty;
}
}
internal class Constants
{
internal class Status
{
public const string PRESIDENT = "president";
public const string FACULTY_MEMBER = "faculty member";
}
}
}

Registration allows duplicate user name in Access

I do have a problem in checking username and password in my registration form. When I tend to register the same username and password that's is already in my database(Access), still it allows to register. I just wanna trap it however, I don't know how to that.
What I want to output is that, I want a trap that says "Account Exists, Try Again!" or "Username Exists!"
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Data.OleDb; using System.Text.RegularExpressions;
namespace Login { public partial class Register : Form {
private OleDbConnection personalConn;
private OleDbCommand oleDbCmd = new OleDbCommand();
private String connParam = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\Majel\Tic Tac Toe\Database\data.accdb";
public Register()
{
personalConn = new OleDbConnection(connParam);
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
personalConn.Open();
oleDbCmd.Connection = personalConn;
if (textBox1.Text != "" && textBox2.Text != "")
{
int temp;
oleDbCmd.CommandText = "INSERT INTO data(Users,Pass) Values('" + this.textBox1.Text.ToString() + "','" + this.textBox2.Text + "');";
temp = oleDbCmd.ExecuteNonQuery();
if (temp > 0)
{
textBox1.Text = null;
textBox2.Text = null;
MessageBox.Show("Registration Success!");
this.Hide();
Form1 frm = new Form1();
frm.Show();
}
personalConn.Close();
}
}
catch (Exception)
{
MessageBox.Show("Invalid!, Duplicate Data.");
}
}
Notes: textBox1= username
textBox2= password Your attention is much highly appreciated. Thank you so much in advance.
Here is code which uses oledbcommand parameters using ? placeholder as mentioned in MSDN Reference. Also I have added using block which should Close opened connection implicitly.
using(OleDbConnection con = new OleDbConnection(connParam))
using(OleDbCommand cmd = new OleDbCommand("select count(*) from data where Users = ?"))
{
con.Open();
cmd.Connection = con;
cmd.Parameters.AddWithValue("#UserName", textBox1.Text);
object objRes = cmd.ExecuteScalar();
if (objRes == null || (int)objRes == 0)
{
cmd.Parameters.Clear();
cmd.CommandText = "INSERT INTO data (Users,Pass) values(?, ?);";
cmd.Parameters.AddWithValue("#Users", textBox1.Text);
cmd.Parameters.AddWithValue("#Pass", textBox2.Text);
int iRes = cmd.ExecuteNonQuery();
if(iRes > 0)
MessageBox.Show("Registration Success!");
}
else
errorProvider2.SetError(textBox1, "This username has been using by another user.");
}
You almost never use data (in this case, a username) as the primary key for a record in a database. Chance are, your access database is set up the same way.
This means that there is nothing at the DBMS layer that will stop this from occurring, short of making the username the primary key (not recommended).
The solution is to perform a SELECT query to get the count of records with that username, and only allow the insert if the count is 0. You might be able to write a trigger to do this for you, and make the DBMS "reject" the insert, but given your (apparent) level with databases, I wouldn't try that at this point.
To get the count:
SELECT Count(*) FROM Users WHERE userName=#userName
A paramaterized query here is crucial to protect against SQL injection.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Text.RegularExpressions;
namespace Login
{
public partial class Register : Form
{
public Register()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
if(text1Box1.Text == "" || textBox2.Text == "")
{
MessageBox.Show("Mandatory fields password or user is empty");
retrun; //I'm not sure if this return is need. Remove it if MessageBox "breaks" the execution of the code below.
}
OleDbCommand cmd = new OleDbCommand(#"Select * from Data where User=#User");
cmd.Parameters.AddWithValue("#User", textBox1.Text);
DataSet dst = SqlManager.GetDataSet(cmd, "Data");
if(dst.Tables[0].Rows > 0)
{
MessageBox.Show("User already exist");
return; //again i'm not sure that this return is needed.
}
Insert("Data", "User", textBox1.Text, "Pass", textBox2.Text);
textBox1.Text = null;
textBox2.Text = null;
MessageBox.Show("Registration Success!");
this.Hide();
Form1 frm = new Form1();
frm.Show();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You need 1 class make it SqlManager.
public class SqlManager
{
private String connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\Majel\Tic Tac Toe\Database\data.accdb";
public static GetOleDbConnection(OleDbCommand cmd)
{
if(cmd.Connection == null)
{
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
cmd.Connection = conn;
return conn;
}
return cmd.Connection;
}
public static int ExecuteNonQuery(SqlCommand cmd)
{
OleDbConnection conn = GetSqlConnection(cmd);
try
{
return cmd.ExecuteNonQuery();
}
catch
{
throw;
}
finally
{
conn.Close();
}
}
public static DataSet GetDataSet(SqlCommand cmd)
{
return GetDataSet(cmd, "Table");
}
public static DataSet GetDataSet(SqlCommand cmd, string defaultTable)
{
OleDbConnection conn = GetSqlConnection(cmd);
try
{
DataSet resultDst = new DataSet();
using (OleDbDataAdapter adapter = new OleDbDataAdapter(cmd))
{
adapter.Fill(resultDst, defaultTable);
}
return resultDst;
}
catch
{
throw;
}
finally
{
conn.Close();
}
}
}
Here is another method you can put in the form class:
public virtual void Insert(string TableName, params object[] colValues)
{
if (colValues == null || colValues.Length % 2 != 0)
throw new ArgumentException("Invalid column values passed in. Expects pairs (ColumnName, ColumnValue).");
OleDbCommand cmd = new OleDbCommand("INSERT INTO " + TableName + " ( {0} ) VALUES ( {1} )");
string insertCols = string.Empty;
string insertParams = string.Empty;
for (int i = 0; i < colValues.Length; i += 2)
{
string separator = ", ";
if (i == colValues.Length - 2)
separator = "";
string param = "#P" + i;
insertCols += colValues[i] + separator;
insertParams += param + separator;
cmd.Parameters.AddWithValue(param, colValues[i + 1]);
}
cmd.CommandText = string.Format(cmd.CommandText, insertCols, insertParams);
DA.SqlManager.ExecuteNonQuery(cmd);
}
Like other guys tell you use parameters in this case you will avoid sql injection. Read in wikipedia about it. Also I add some structure for your program, it is not perfect but I should write a lot for more. It is possible to have some typos here, because I wrote the code here. How you make the check, you fetch the data from database for the user which you write in textbox1.Text. If the dataSet have rows that means at the moment there is existing user with this name. If you don't know what is data set read System.Data.
You should learn to write data access in other classes !
Try this with your Existing Code :
oleDbCmd.CommandText = "INSERT INTO data(Users,Pass) Values('" + this.textBox1.Text.ToString() + "','" + this.textBox2.Text + "') SELECT '" + this.textBox1.Text.ToString() + "','" + this.textBox2.Text + "' WHERE NOT EXISTS(SELECT Users,Pass FROM data WHERE Users='" + this.textBox1.Text.ToString() +"');";
temp = oleDbCmd.ExecuteNonQuery();
if (temp > 0)
{
textBox1.Text = null;
textBox2.Text = null;
MessageBox.Show("Registration Success!");
this.Hide();
Form1 frm = new Form1();
frm.Show();
}
else
{
MessageBox.Show("Username is already Present !!!");
}
It returns 0 if the username is already present in data.

"Invalid operator for data type. Operator equals minus, type equals varchar."

Im trying to make a code which checks my table for existing records with the same name but i am receiving an error "Invalid operator for data type. Operator equals minus, type equals varchar." I understand the error but i dont understand why i cant convert it into an int.
this is my code, any help to make it work will be appreciated!
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)
{
if (IsPostBack)
{
SqlConnection studConn = new SqlConnection(ConfigurationManager.ConnectionStrings["StudConnectionString"].ConnectionString);
studConn.Open();
string checkuser = "select count(*) from StudTable where-'" + TextBoxName.Text + "'";
SqlCommand studCom = new SqlCommand(checkuser, studConn);
int temp = Convert.ToInt32 (studCom.ExecuteScalar().ToString());
studConn.Close();
if (temp == 1)
{
Response.Write("User already exists");
}
}
}
protected void Button1_Click(object sender, System.EventArgs e)
{
try
{
Guid studGUID = Guid.NewGuid();
SqlConnection studConn = new SqlConnection(ConfigurationManager.ConnectionStrings["StudConnectionString"].ConnectionString);
studConn.Open();
string insertQuery = "insert into StudTable (ID,Name,Email,Age,Continent,School,Password) values (#ID,#name,#email,#age,#cont,#school,#pass)";
SqlCommand studCom = new SqlCommand(insertQuery, studConn);
studCom.Parameters.AddWithValue("#ID", studGUID.ToString());
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("#pass", TextBoxPass.Text);
studCom.ExecuteNonQuery();
Response.Redirect("Backend.aspx");
Response.Write("Your Registration is Sucessful");
studConn.Close();
}
catch (Exception ex)
{
Response.Write("Error:" +ex.ToString());
}
}
}
Thanks!
You need to change your command text and use parameterized queries instead of string concatenation
string checkuser = "select count(*) from StudTable where Name = #Name";
SqlCommand studCom = new SqlCommand(checkuser, studConn);
studCom.Parameters.AddWithValue("#Name", TextBoxName.Text);
You should remove (-) after Where and also use equality operator = to check for equality.
I just got this error when making an insert command in SSMS:
I found a '-' in my sql command that I didn't realize was there (I had been putting lots of comments in my insert command in SSMS '-- and some text' after each column and had an errant minus '-' sign). Apparently this error focuses on errant minus signs.

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