How to Insert User(Client Side) Entry By Default? - c#

I have
Admin Side and Client-Side
and I have only one table for admin login and client login see the Reference Image
When User Login Then Insert an Entry as a User?
Reference:
https://imgur.com/a/PDoVSi9
I want to ex:
Database Entry
UserType: User
EmailId: benssok#gmail.com
Password: bens1234
FirstName: nicks
LastName: andrew
Code:
c#
Registation ClientSide:
protected void Button1_Click(object sender, EventArgs e)
{
string firstname = txtFirstName.Text;
string lastname = txtLastName.Text;
string emailid = txtEmailId.Text;
string password = txtclientpassword.Text;
ClientLogin_Click(firstname, lastname, emailid, password);
}`enter code here`
void ClientLogin_Click(string firstname,string lastname,string emailid,string Password)
{
string conn = ConfigurationManager.ConnectionStrings["connstr"].ToString();
SqlConnection cn = new SqlConnection(conn);
string Insertquery = "Insert into tbladminclient(FirstName,LastName,EmailId,Password) values(#FirstName,#LastName,#EmailId,#Password)";
SqlCommand cmd = new SqlCommand(Insertquery, cn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#FirstName", firstname);
cmd.Parameters.AddWithValue("#LastName", lastname);
cmd.Parameters.AddWithValue("#EmailId", emailid);
cmd.Parameters.AddWithValue("#Password", Password);
try
{
cn.Open();
int validateOperation = cmd.ExecuteNonQuery();
if (validateOperation > 0)
{
Response.Write("successfully Registration");
Response.Redirect("ClientLogin.aspx");
}
else
{
Response.Write("Not successfully Registration");
}
}
catch (SqlException e)
{
Response.Write("error");
}
finally
{
cn.Close();
}
}
AdminLogin Page //Problem Occured when Same Login(AdminSide) and sameLogin(ClientSide) what the differance? How to resolve this problem ? How to Identify User(clientside) and admin(adminside)Login??
protected void Button1_Click(object sender, EventArgs e)
{
string userName = txtEmailId.Text;
string Password = txtUserPassword.Text;
Login_Click(userName, Password);
}
void Login_Click(string emailid, string Password)
{
string conn = ConfigurationManager.ConnectionStrings["connstr"].ToString();
SqlConnection cn = new SqlConnection(conn);
SqlCommand cmd = new SqlCommand("select * from tbladminclient where EmailId=#EmailId and Password=#Password", cn);
cn.Open();
cmd.Parameters.AddWithValue("#EmailId", emailid);
cmd.Parameters.AddWithValue("#Password", Password);
SqlDataReader dr = cmd.ExecuteReader(); //data read from the database
if (dr.HasRows == true) //HasRows means one or more row read from the database
{
Response.Write("successfully Login");
}
else
{
Response.Write("Not successfully Login");
}
cn.Close();
}
problem is when Same Login(AdminSide) and sameLogin(ClientSide) what the differance? How to resolve this problem ? How to Identify User(clientside) and admin(adminside)Login??

First when user(client-side) registration form fill up go to database and execute query
ALTER TABLE [tbladminclient]
ADD CONSTRAINT df_UserType
DEFAULT 'User' FOR UserType; //whenever you insert then Bydefault Entry is User:
how to identify user is client or admin
Code:
User LogIn
protected void Button1_Click(object sender, EventArgs e)
{
string emailid = txtemailId.Text;
string password = txtPassword.Text;
Client_Login(emailid,password);
}
void Client_Login(string emailid,string password)
{
string conn = ConfigurationManager.ConnectionStrings["connstr"].ToString();
SqlConnection cn = new SqlConnection(conn);
SqlCommand cmd = new SqlCommand("select * from tbladminclient where EmailId=#EmailId and Password=#Password", cn);
cn.Open();
cmd.Parameters.AddWithValue("#EmailId", emailid);
cmd.Parameters.AddWithValue("#Password", password);
SqlDataReader dr = cmd.ExecuteReader(); //data read from the database
if (dr.HasRows == true)//HasRows means one or more row read from the database
{
if (dr.Read())
{
if (dr["UserType"].ToString() == "User")
{
Response.Write("successfully Client Login");
}
else
{
Response.Write("Not successfully Client Login");
}
}
}
else
{
Response.Write("Not Found");
}
cn.Close();
}
Admin LogIn
protected void Button1_Click(object sender, EventArgs e)
{
string userName = txtEmailId.Text;
string Password = txtUserPassword.Text;
Login_Click(userName, Password);
}
void Login_Click(string emailid, string Password/*string UserType*/)
{
string conn = ConfigurationManager.ConnectionStrings["connstr"].ToString();
SqlConnection cn = new SqlConnection(conn);
SqlCommand cmd = new SqlCommand("select * from tbladminclient where EmailId=#EmailId and Password=#Password", cn);
cn.Open();
cmd.Parameters.AddWithValue("#EmailId", emailid);
cmd.Parameters.AddWithValue("#Password", Password);
SqlDataReader dr = cmd.ExecuteReader(); //data read from the database
if (dr.HasRows == true)//HasRows means one or more row read from the database
{
if (dr.Read())
{
if (dr["UserType"].ToString() == "admin")
{
Response.Write("Successfully Admin Login");
}
else
{
Response.Write("Not successfully Admin Login");
}
}
}
else
{
Response.Write("Not Found");
}
cn.Close();
}

Related

How can I update password using C#?

I can't find my problem. Can anyone help me to check it. I'm new in C#.
public void Btnchange_Click(object sender, EventArgs args)
MySqlConnection con = new MySqlConnection("server=localhost;user id=root;persistsecurityinfo=True;database=user;password=1234");
MySqlDataAdapter sda = new MySqlDataAdapter("select Password from user.register where Password='" + textoldpassword.Text + "'", con);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count.ToString() == "1")
{
if (textnewpassword.Text == textconfirmpassword.Text)
{
con.Open();
MySqlCommand cmd = new MySqlCommand("update user.register set Password ='" + textconfirmpassword.Text + "' where Password ='" + textoldpassword.Text + "'", con);
cmd.ExecuteNonQuery();
con.Close();
lblmsg.Text = "Succesfully Updated";
lblmsg.ForeColor = Color.Green;
}
else
{
lblmsg.Text = "New password and confirm password should be same!";
}
I expect it can update and change my password.
There are many many (mostly) minor mistakes in your code:
use some kind of Id fields in your sql tables
never do an update like you did (update the field WHERE this field is equals to...)
create your own class and bind the query result to this class
when a class implements IDisposable interface, always use the keyword 'using'
never ever user string concatenation in sql queries!!! SQL INJECTION!!! always use parametrized sql queries
Here's a simple example for your form. Let's suppose your
user.register table has the following columns:
- Id
- Username
- Password
Now let's create your own class (maybe right under your button click
event, so it can be private this time):
private class MyUser
{
public int Id { get; set; }
public string Username { get; set; }
public string Password { get; set; }
}
Then your button click event should look like this:
private void Btnchange_Click(object sender, EventArgs e) {
if (!textnewpassword.Text.Trim().Equals(textconfirmpassword.Text.Trim()))
{
throw new ArgumentException("New password and confirm password should be same!");
}
List<MyUser> myUsers = new List<MyUser>();
using (MySqlConnection con =
new MySqlConnection(
"server=localhost;user id=root;persistsecurityinfo=True;database=user;password=1234"))
{
using (MySqlCommand cmd = new MySqlCommand("select * from user.register where Username=#user and Password=#pass", con))
{
cmd.Parameters.AddWithValue("#user", textusername.Text.Trim());
cmd.Parameters.AddWithValue("#pass", textoldpassword.Text.Trim());
if (cmd.Connection.State != ConnectionState.Open) cmd.Connection.Open();
using (MySqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
myUsers.Add(new MyUser
{
Id = (int)dr["Id"],
Username = dr["Username"].ToString(),
Password = dr["Password"].ToString()
});
}
}
if (cmd.Connection.State == ConnectionState.Open) cmd.Connection.Close();
}
if (!myUsers.Any())
{
throw new ArgumentException("No users found with the given username/password pair!");
}
if (myUsers.Count != 1)
{
throw new ArgumentException("More than 1 user has the same username and password in the database!");
}
MyUser user = myUsers.First();
user.Password = textnewpassword.Text.Trim();
using (MySqlCommand cmd = new MySqlCommand("update user.register set Password=#pass where Id=#id"))
{
cmd.Parameters.AddWithValue("#pass", user.Password);
cmd.Parameters.AddWithValue("#id", user.Id);
if (cmd.Connection.State != ConnectionState.Open) cmd.Connection.Open();
cmd.ExecuteNonQuery();
if (cmd.Connection.State == ConnectionState.Open) cmd.Connection.Close();
}
} }
...and so on.

Storing bcrypt hashes password in mySQL database.

So I'm making a login form in WPF. What I want to happen is that if I add a new user to my database the password gets hashed and stored in my database. This is not working and I don't know what I'm doing wrong. it's not even adding a new user without a hashed password. I would appreciate some help.
Click event to add a new user :
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
clsDB cdb = new clsDB();
cdb.Adduser(tbUsername.Text, tbPassword.Text);
MessageBox.Show("user toegevoegd!");
this.Close();
}
this is the database class :
class clsDB
{
MySqlConnection conn = new MySqlConnection("server=localhost;Database=loginbcrypt;Uid=root;pwd=");
public int GetUserid(string un, string pwd)
{
int iUserID = 0;
conn.Open();
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "select UserId from users where Username = #username and Password = #password";
cmd.Parameters.AddWithValue("#username", un);
cmd.Parameters.AddWithValue("#password", pwd);
string sUserId = cmd.ExecuteScalar().ToString();
iUserID = int.Parse(sUserId);
conn.Close();
return iUserID;
}
public void Adduser(string un, string pwd)
{
try
{
conn.Open();
pwd = pwd + "$Y.N3T~J";
string salt = BCrypt.Net.BCrypt.GenerateSalt();
string hashToStoreInDatabase = BCrypt.Net.BCrypt.HashPassword(pwd, salt);
bool doesPasswordMatch = BCrypt.Net.BCrypt.Verify(pwd, un);
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "insert into users (Username, Password) values (#username, #password)";
cmd.Parameters.AddWithValue("#username", un);
cmd.Parameters.AddWithValue("#password", pwd);
cmd.ExecuteNonQuery();
}
catch (Exception)
{
}
finally
{
conn.Close();
}
}
}

How to stop adding duplicate username into database table?

I'm working with ASP.Net web application project . in my Registration form the Username and the Email will be check if it's exist in the database or not. but my problem is if the username and the Email are exist the user can register normally and his data will be added in the database! how i can stop it from adding these data and forced the user to change the username or the Email if one of them is exist ! please any help ?
my .aspx.cs page :
protected void Button1_Click(object sender, EventArgs e)
{
byte[] License;
Stream s = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(s);
License = br.ReadBytes((Int32)s.Length);
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString);
conn.Open();
string insertQuery = "insert into DeliveryMen (Name,Username,Password,Email,Phone,City,License) values (#name ,#username, #password, #email ,#phone ,#city,#License)";
SqlCommand com = new SqlCommand(insertQuery, conn);
com.Parameters.AddWithValue("#name", TextBoxName.Text);
com.Parameters.AddWithValue("#username", TextBoxUsername.Text);
com.Parameters.AddWithValue("#password", TextBoxPassword.Text);
com.Parameters.AddWithValue("#email", TextBoxEmail.Text);
com.Parameters.AddWithValue("#phone", TextBoxPhone.Text);
com.Parameters.AddWithValue("#city", DropDownList1.SelectedItem.ToString());
com.Parameters.AddWithValue("#License", License);
com.ExecuteNonQuery();
Response.Write("DONE");
conn.Close();
}
catch (Exception ex)
{ Response.Write("Error:" + ex.ToString()); }
}
protected void TextBoxUsername_TextChanged(object sender, EventArgs e)
{ // to check if the Username if exist
if (!string.IsNullOrEmpty(TextBoxUsername.Text))
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select * from DeliveryMen where Username=#Username", con);
cmd.Parameters.AddWithValue("#Username", TextBoxUsername.Text);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
checkusername.Visible = true;
imgstatus.ImageUrl = "NotAvailable.jpg";
lblStatus.Text = "UserName Already Taken";
System.Threading.Thread.Sleep(2000);
}
else
{
checkusername.Visible = true;
imgstatus.ImageUrl = "Icon_Available.gif";
lblStatus.Text = "UserName Available";
System.Threading.Thread.Sleep(2000);
}
}
else
{
checkusername.Visible = false;
}
}
protected void TextBoxEmail_TextChanged(object sender, EventArgs e)
{ // to check if the Email if exist
if (!string.IsNullOrEmpty(TextBoxEmail.Text))
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select * from DeliveryMen where Email=#email", con);
cmd.Parameters.AddWithValue("#Email", TextBoxEmail.Text);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
Div1.Visible = true;
Image1.ImageUrl = "NotAvailable.jpg";
Label2.Text = "the Email Already Taken";
System.Threading.Thread.Sleep(2000);
}
else
{
Div1.Visible = true;
Image1.ImageUrl = "Icon_Available.gif";
Label2.Text = "the Email Available";
System.Threading.Thread.Sleep(2000);
}
}
else
{
Div1.Visible = false;
}
}
Set unique constraints on your Username and email columns, your sql insert will throw an exception and you can handle that and notifiy the client accordingly.
See https://msdn.microsoft.com/en-GB/library/ms190024.aspx
use an insert stored procedure instead of inline insert query and in stored procedure before insert check where this username email id exist or not.
if (not exists(select 1 from DeliveryMen where Username= #Username and Email=#Email))
begin
insert into DeliveryMen (Name,Username,Password,Email,Phone,City,License) values (#name ,#username, #password, #email ,#phone ,#city,#License)
end
The primary key needs to be set in the database itself.
Suppose 'username' is your primary key and therefore unique. Then you can check whether it already exists in the database or not as follows:
private void button2_Click(object sender, EventArgs e
{
conn.Open();
com.Connection = conn;
sql = "SELECT COUNT(*) FROM lapusers WHERE [username] = #username";
com.CommandText = sql;
com.Parameters.Clear();
com.Parameters.AddWithValue("#username", userlapbox.Text);
int numRecords = (int)com.ExecuteScalar();
if (numrecords == 0)
{
sql = "INSERT INTO lapusers([username],[fillingcode],[branch],[department],[agency])VALUES(#username,#fillingcode,#branch,#department,#agency)";
com.CommandText = sql;
com.Parameters.Clear();
com.Parameters.AddWithValue("#username", userlapbox.Text);
com.Parameters.AddWithValue("#fillingcode", userfilllapbox.Text);
com.Parameters.AddWithValue("#branch", comboBox2.Text);
com.Parameters.AddWithValue("#department", comboBox1.Text);
com.Parameters.AddWithValue("#agency", comboBox3.Text);
com.ExecuteNonQuery();
MessageBox.Show("Created Successfully ..");
}
else
{
MessageBox.Show("A record with a user name of {0} already exists", userlapbox.Text);
}
conn.Close();
}

Username check is not working when user registers -asp.net

i want to check if the username already exists in the database and if yes, error message will prompt that says "username already exist". now i have this code but its not working. program still accepts the username even if it is duplicated from the database. can someone help me out pls? here is my whole registration code:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string checkuser = "select count(*) from UserData where Username = '" + txtUser.Text + "'";
SqlCommand scm = new SqlCommand(checkuser, conn);
int temp = Convert.ToInt32(scm.ExecuteScalar().ToString());
if (temp == 1) // check if user already exist.
{
Response.Write("User already existing");
}
conn.Close();
}
}
protected void btn_Registration_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string insertQuery = "insert into UserData(Username,Firstname,Lastname,Email,Password,CustomerType,DeliveryAddress,Zip,ContactNumber)values(#Username,#Firstname,#Lastname,#Email,#Password,#CustomerType,#DeliveryAddress,#Zip,#ContactNumber)";
SqlCommand scm = new SqlCommand(insertQuery, conn);
scm.Parameters.AddWithValue("#Username", txtUser.Text);
scm.Parameters.AddWithValue("#Firstname", txtFN.Text);
scm.Parameters.AddWithValue("#Lastname", txtLN.Text);
scm.Parameters.AddWithValue("#Email", txtEmail.Text);
scm.Parameters.AddWithValue("#Password", BusinessLayer.ShoppingCart.CreateSHAHash(txtPW.Text));
scm.Parameters.AddWithValue("#CustomerType", RadioButtonList1.SelectedItem.ToString());
scm.Parameters.AddWithValue("#DeliveryAddress", txtAddress.Text);
scm.Parameters.AddWithValue("#Zip", txtZip.Text);
scm.Parameters.AddWithValue("#ContactNumber", txtContact.Text);
scm.ExecuteNonQuery();
Session["Contact"]= txtContact.Text;
Session["Email"] = txtEmail.Text;
Session["DeliveryAddress"] = txtAddress.Text;
label_register_success.Text = ("Registration Successful!");
//Response.Redirect("Home.aspx");
conn.Close();
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
}
You validate data on Page_Load? I think, you can choose to these solusions
You have to do it in btn_Registration_Click before you insert the
data, or
Maybe, you can modify it to do in sp and throw message through it if data is
duplicated and do the checking there.
It should be like this (according to solution 1)
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
}
}
protected void btn_Registration_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string checkuser = "select count(*) from UserData where Username = '" + txtUser.Text + "'";
SqlCommand scm = new SqlCommand(checkuser, conn);
int temp = Convert.ToInt32(scm.ExecuteScalar().ToString());
if (temp > 0) // check if user already exist.
{
Response.Write("User already existing");
}
else
{
string insertQuery = "insert into UserData(Username,Firstname,Lastname,Email,Password,CustomerType,DeliveryAddress,Zip,ContactNumber)values(#Username,#Firstname,#Lastname,#Email,#Password,#CustomerType,#DeliveryAddress,#Zip,#ContactNumber)";
scm = new SqlCommand(insertQuery, conn);
scm.Parameters.AddWithValue("#Username", txtUser.Text);
scm.Parameters.AddWithValue("#Firstname", txtFN.Text);
scm.Parameters.AddWithValue("#Lastname", txtLN.Text);
scm.Parameters.AddWithValue("#Email", txtEmail.Text);
scm.Parameters.AddWithValue("#Password", BusinessLayer.ShoppingCart.CreateSHAHash(txtPW.Text));
scm.Parameters.AddWithValue("#CustomerType", RadioButtonList1.SelectedItem.ToString());
scm.Parameters.AddWithValue("#DeliveryAddress", txtAddress.Text);
scm.Parameters.AddWithValue("#Zip", txtZip.Text);
scm.Parameters.AddWithValue("#ContactNumber", txtContact.Text);
scm.ExecuteNonQuery();
Session["Contact"]= txtContact.Text;
Session["Email"] = txtEmail.Text;
Session["DeliveryAddress"] = txtAddress.Text;
label_register_success.Text = ("Registration Successful!");
//Response.Redirect("Home.aspx");
}
conn.Close();
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
}

form validation using c# and sql commands

i am trying to make a windows form to log into another one,
i am using a database with users and passwords
the code is as follows:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=mmtsql.XXX.XXXX.XX.XX;Initial Catalog=mmtXX-XXX;User ID=mmtXX-XXX;Password=mmtXX-XXX");
conn.Open();
SqlCommand mycommand = new SqlCommand("SELECT User, Password FROM UsersData WHERE User = '" + textBox1.Text + "' and Password = '" + textBox2.Text + "'", conn);
SqlDataReader reader = mycommand.ExecuteReader();
if(reader != null)
{
if(reader.Read())
{
Form1 formload = new Form1();
formload.Show();
}
else
{
label3.Text = "Invalid Username or Password !";
}
}
else
{
label3.Text = "Invalid Username or Password !";
}
the problem that a getting is that no matter what i insert into the textboxes, right or wrong i am getting:
Invalid Username or Password !
is there anyway to fix my code?
regards;
I would do it this way, keeping to the method you are using:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(conn_str);
conn.Open();
string sql = "SELECT User, Password
FROM UsersData WHERE User=#user and Password=#password"
SqlCommand mycommand = new SqlCommand(sql, conn);
//parameterize your query!
mycommand.Parameters.AddWithValue("user", txtuser.text);
mycommand.Parameters.AddWithValuye("password", txtpassword.password);
SqlDataReader reader = mycommand.ExecuteReader();
if(reader == null)
{
label3.Text = "Database query failed!";
}
else if(reader.HasRows)
{
Form1 formload = new Form1();
formload.Show();
}
else
{
label3.Text = "Invalid Username or Password !";
}
Use parameterized queries as they will help you against sql injection as mentioned by SLaks.
Change your code to below
using (SqlCommand command = new SqlCommand("SELECT User, Password
FROM UsersData WHERE User=#user and Password=#password", connection))
{
//
// Add new SqlParameter to the command.
//
command.Parameters.Add(new SqlParameter("user ", textbox1.text));
command.Parameters.Add(new SqlParameter("password", textbox2.text));
SqlDataReader reader = command.ExecuteReader();
if (reader == null)
{
Form1 formload = new Form1();
formload.Show();
}
else
{
label3.Text = "Invalid Username or Password !";
}
}

Categories