Check if username exists before pressing submit button - c#

i have this code-behind:
protected void cmdSave_Click(object sender, EventArgs e)
{
string sFilePath = Server.MapPath("Database3.accdb");
OleDbConnection Conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + sFilePath + ";Persist Security Info=False;");
using (Conn)
{
Conn.Open();
OleDbCommand myCommand = new OleDbCommand("SELECT COUNT(*) FROM colaborador WHERE username=#username", Conn);
myCommand.Parameters.Add("?", OleDbType.VarChar).Value = HttpContext.Current.User.Identity.Name;
int totalRegistos = (int)myCommand.ExecuteScalar();
if (totalRegistos > 0)
{
// user already answered
lblInfo0.Text = "The user already asnwered";
}
else
{
// the user didn't asnwered
string insertCmd = "INSERT INTO colaborador(Empresa,Empresa2,Telemovel,username) VALUES (#Empresa,#Empresa2,#Telemovel,#username)";
// insere na tabela colaborador os campos empresa, empres2, user os valores #
{
OleDbCommand myCommand2 = new OleDbCommand(insertCmd, Conn);
myCommand2.Parameters.AddWithValue("#Empresa", empresa.Text);
myCommand2.Parameters.AddWithValue("#Empresa2", empresa2.Text);
myCommand2.Parameters.AddWithValue("#Telemovel", telemovel.Text);
myCommand2.Parameters.AddWithValue("#username", HttpContext.Current.User.Identity.Name);
Response.Write(myCommand.ExecuteNonQuery());
lblInfo.Text = "Data saved!";
lblInfo.ForeColor = System.Drawing.Color.Green;
}
}
}
}
this working fine with no errors and save into db also if the username exist say a message "user already answered"
however i need press submit button.
there's any way to say the message (if the username already exist) before field the text.box? how can i change my code to do that?

if (!IsPostBack)
{
string sFilePath = Server.MapPath("Database3.accdb");
OleDbConnection Conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + sFilePath + ";Persist Security Info=False;");
using (Conn)
{
Conn.Open();
OleDbCommand myCommand = new OleDbCommand("SELECT COUNT(*) FROM colaborador WHERE username=#username", Conn);
myCommand.Parameters.Add("?", OleDbType.VarChar).Value = HttpContext.Current.User.Identity.Name;
int totalRegistos = (int)myCommand.ExecuteScalar();
if (totalRegistos > 0)
{
// Já registado
lblInfo0.Text = "O username já existe na base de dados";
empresa.Enabled = false;
empresa2.Enabled = false;
telemovel.Enabled = false;
cmdSave.Visible = false;
}
}
}

Related

How to open next form base on select query base on flag

I am creating one application my requirement is what when column name Status is N in Registration table, then current form should hide and Login form should be open.
If Status is not N then its should be open Registration_Form. I'm trying but it's causing
Error creating window handle
on the rf.Show() call.
on insert button code
string status = "Y";
//Random random = new Random();
//int randomNumber = random.Next(0, 100);
string random1 = System.Web.Security.Membership.GeneratePassword(10, 0);
string concate = textBox1.Text + "-" + textBox2.Text + "-" + textBox3.Text.Substring(textBox3.Text.Length - 4) + "-" + random1;
string connectionString = null;
connectionString = ConfigurationManager.ConnectionStrings["AccessConnectionString"].ConnectionString;
con.ConnectionString = connectionString;
string SqlString = "Insert Into Registration (Name,Last_Name,Contact_No,Address,Insert_Date,Registration_key,Status) Values (?,?,?,?,?,?,?)";
//using (OleDbCommand cmd = new OleDbCommand(SqlString, con))
//{
OleDbCommand cmd = new OleDbCommand(SqlString, con);
con.Open();
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Name", textBox1.Text);
cmd.Parameters.AddWithValue("#Last_Name", textBox2.Text);
cmd.Parameters.AddWithValue("#Contact_No", textBox3.Text);
cmd.Parameters.AddWithValue("#Address", textBox4.Text);
cmd.Parameters.AddWithValue("#Insert_Date", textBox5.Text);
cmd.Parameters.AddWithValue("#Registration_key", concate);
cmd.Parameters.AddWithValue("#Status", status);
//}
int n = cmd.ExecuteNonQuery();
con.Close();
if (n > 0)
{
MessageBox.Show("Data Inserted Successfully,NOW PLEASE ACTIVATE APPLICATION PUTTING ACTIVATE KEY ", "Data Inserted ", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
on update button code --
string Status = "N";
string connectionString = null;
connectionString = ConfigurationManager.ConnectionStrings["AccessConnectionString"].ConnectionString;
con.ConnectionString = connectionString;
string recover = "SELECT Registration_key from Registration where Registration_key='" + textBox6.Text + "'";
OleDbCommand cmd = new OleDbCommand(recover, con);
con.Open();
OleDbDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
textBox6.Text = reader["Registration_key"].ToString();
if (con.State == ConnectionState.Open)
{
con.Close();
}
string cmd1 = "update Registration set Status=#Status where Registration_key=#Registration_key";
cmd = new OleDbCommand(cmd1, con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Status", Status);
cmd.Parameters.AddWithValue("#Registration_key", textBox6.Text);
con.Open();
int n2 = cmd.ExecuteNonQuery();
con.Close();
this.Hide();
Login_Page lp = new Login_Page();
lp.Show();
}
else
{
MessageBox.Show("Invalid Activated Key", "Invalid", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
con.Close();
on load event--
string connectionString = null;
connectionString = ConfigurationManager.ConnectionStrings["AccessConnectionString"].ConnectionString;
con.ConnectionString = connectionString;
string Comparing="N";
string query = "select Status from Registration where Status='N'";
con.Open();
OleDbCommand cmd = new OleDbCommand(query, con);
string compare = Convert.ToString(cmd.ExecuteScalar());
con.Close();
if (compare == Comparing)
{
this.Hide();
Login_Page lp = new Login_Page();
lp.Show();
}
else if (compare != Comparing)
{
Registration_Form rf = new Registration_Form();
rf.Show();
}
i got a solution i remove e
lse if (compare != Comparing)
{
Registration_Form rf = new Registration_Form();
rf.Show();
}
this and instead that normal use else condition
connectionString = ConfigurationManager.ConnectionStrings["AccessConnectionString"].ConnectionString;
con.ConnectionString = connectionString;
string Comparing="N";
string query = "select Status from Registration where Status='N'";
con.Open();
OleDbCommand cmd = new OleDbCommand(query, con);
string compare = Convert.ToString(cmd.ExecuteScalar());
con.Close();
if (compare == Comparing)
{
this.Hide();
Login_Page lp = new Login_Page();
lp.Show();
}
else
{
MessageBox.Show("Pls Register yourself");
}
this code giving me what requirement i want

Query regarding password hashing. Cannot log in

i am trying to encrypt a password and be able to log in with it. here is my hash code inside my businesslayer folder under shopping cart class.
public static string CreateSHAHash(string Phrase)
{
SHA512Managed HashTool = new SHA512Managed();
Byte[] PhraseAsByte = System.Text.Encoding.UTF8.GetBytes(string.Concat(Phrase));
Byte[] EncryptedBytes = HashTool.ComputeHash(PhraseAsByte);
HashTool.Clear();
return Convert.ToBase64String(EncryptedBytes);
}
and here is my registration code where i included the hash with the password. i am successful in registering an account and having an encrypted password in my database with this:
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());
}
}
However, when i try to log in with the password that i have registered, its not letting me in. here is the code:
protected void btn_Login_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source = 'PAULO'; Initial Catalog=ShoppingCartDB;Integrated Security =True");
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());
conn.Close();
if (temp == 1)
{
conn.Open();
string checkPassword = "select Password from UserData where Username ='" + txtUser.Text + "'";
SqlCommand passCom = new SqlCommand(checkPassword, conn);
string password = passCom.ExecuteScalar().ToString();
if (password == BusinessLayer.ShoppingCart.CreateSHAHash(txtPassword.Text))
{
Session["New"] = txtUser.Text;
Response.Write("<script>alert('Logged In')</script>");
Response.Redirect("OrderNow.aspx");
}
else
{
lblcrederror.Text = ("Credentials dont match");
}
}
else
{
lblcrederror.Text = ("Credentials dont match");
}
}
what am i missing here? thank you

Why won't my labels stay changed

when i run my code the labels stay the same but when i debug it i can see the text changes and then changes back when it is done runnning
public void getData(string a)
{
SqlConnection conn = new SqlConnection(#"Data Source=MASSI\FABERSERVER;Initial Catalog=Data.mdf;Integrated Security=True");
conn.Open();
SqlCommand command = new SqlCommand("Select UserID,UserName,Email FROM Login Where UserName= '" + a + "'", conn);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
label1.Text = reader["UserID"].ToString();
label2.Text = reader["UserName"].ToString();
label3.Text = reader["Email"].ToString();
}
conn.Close();
}
Just in case, try this:
public void getData(string a) {
SqlConnection conn = new SqlConnection(#"Data Source=MASSI\FABERSERVER;Initial Catalog=Data.mdf;Integrated Security=True");
conn.Open();
SqlCommand command = new SqlCommand("Select UserID,UserName,Email FROM Login Where UserName= '" + a + "'", conn);
SqlDataReader reader = command.ExecuteReader();
string id, name, email;
while (reader.Read())
{
id = reader["UserID"].ToString();
name = reader["UserName"].ToString();
email = reader["Email"].ToString();
}
conn.Close();
label1.Text = id;
label2.Text = name;
label3.Text = email;
}
}
Hope, it helps.

Retrieve a hashed password

I already could make the password to become not stored as the original text in the database. But while I want to retrieve it and check between the entered password with in the database, the error appears
Value cannot be null
on this line of code:
string verifyHashedPassword = Convert.ToString(Crypto.VerifyHashedPassword(_registration.hashedPassword, this.textBox2.Text));
Here is the code that I am using for Login:
string connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=..\db1.accdb";
Registration _registration = new Registration();
private void CheckUserDatabase(object sender, EventArgs e)
{
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
string query = "SELECT [Username], [Password], [UserType], [UserStore] FROM [Member] WHERE [Username] = #Username AND [Password] = #Password";
string verifyHashedPassword = Convert.ToString(Crypto.VerifyHashedPassword(_registration.hashedPassword, this.textBox2.Text));
conn.Open();
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
cmd.Parameters.Add("#Username", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["#Username"].Value = this.textBox1.Text;
cmd.Parameters.Add("#Password", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["#Password"].Value = verifyHashedPassword;
using (OleDbDataReader dReader = cmd.ExecuteReader())
{
if (dReader.Read())
{
UserInformation.CurrentLoggedInUser = (string)dReader["Username"];
UserInformation.CurrentLoggedInUserType = (string)dReader["UserType"];
UserInformation.CurrentLoggedInUserStore = (string)dReader["UserStore"];
}
else
{
RecursiveClearTextBoxes(this.Controls);
}
dReader.Close();
conn.Close();
}
}
}
}
Here is the code for Registration:
string connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=..\db1.accdb";
private void AddDatabase(object sender, EventArgs e)
{
string query = "INSERT INTO [Member] ([Username], [Password], [UserType], [UserStore]) VALUES (#Username, #Password, #UserType, #UserStore)";
string hashedPassword = Crypto.HashPassword(this.textBox2.Text);
OleDbConnection _conn = new OleDbConnection(connectionString);
_conn.Open();
using (OleDbCommand cmd = new OleDbCommand(query, _conn))
{
cmd.Parameters.Add("#Username", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["#Username"].Value = this.textBox1.Text;
cmd.Parameters.Add("#Password", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["#Password"].Value = hashedPassword;
cmd.Parameters.Add("#UserType", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["#UserType"].Value = this.textBox3.Text;
cmd.Parameters.Add("#UserStore", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["#UserStore"].Value = this.textBox4.Text;
cmd.ExecuteNonQuery();
DialogResult _dialogResult = MessageBox.Show("Added Successfully", "Success", MessageBoxButtons.OK);
if (_dialogResult == DialogResult.OK)
{
this.Hide();
this.Close();
}
}
}
}
Any help?
Your answer much appreciated!
Thank you

How do I add SQL auth to a C# forms app?

I need to be able to verify a username and password against a sql server and I need code for a C# forms application.
I have it setup with 2 textboxes (1 user and 1 pass) and then I have a login button.
SqlConnection UGIcon = new SqlConnection();
UGIcon.ConnectionString = "Data Source=HP-PC//localhost;Initial Catalog=UGI;Integrated Security=True";
UGIcon.Open();
string userText = textBox11.Text;
string passText = textBox12.Text;
SqlCommand cmd = new SqlCommand("SELECT stUsername,stPassword FROM LoginDetails WHERE stUsername='" + textBox11.Text + "' and stPassword='" + textBox12.Text + "'", UGIcon);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if ( dt.Rows.Count > 0)
{
MessageBox.Show("Login Success!!");
cmd = new SqlCommand("SELECT stRole from LoginDetails where stUsername=#stUsername", UGIcon);
cmd.Parameters.AddWithValue("#stUsername",userText);
string role = cmd.ExecuteScalar().ToString();
MessageBox.Show(role);
UGIcon.Close();
}
else
{
MessageBox.Show("Access Denied!!");
UGIcon.Close();
}
I'm a real believer in using the "using" statements. You can also save yourself a 2nd query by asking for the stRole variable in the original query. The using blocks will automatically dispose of the objects, so when execution leaves this area, the objects will automatically be cleaned up.
using (SqlConnection UGIcon = new SqlConnection("Data Source=localhost\\sqlexpress;Initial Catalog=UGI;Integrated Security=True"))
{
UGIcon.Open();
string userText = textBox11.Text;
string passText = textBox12.Text;
SqlCommand cmd = new SqlCommand("SELECT stUsername,stPassword, stRole FROM LoginDetails WHERE stUsername='" + userText + "' and stPassword='" + passText + "'", UGIcon);
using (SqlDataReader rdr = cmd.ExecuteReader())
{
if (rdr.HasRows)
{
while (rdr.Read())
{
string role = rdr["stRole"].ToString();
MessageBox.Show(role);
}
}
else
{
MessageBox.Show("Access Denied!!");
}
}
}
Pls check this code
SqlConnection thisConnection = new
SqlConnection(#"Server=(local)\sqlexpress;Integrated Security=True;" +
"Database=northwind");
thisConnection.Open();
SqlCommand thisCommand = thisConnection.CreateCommand();
thisCommand.CommandText = "Select count(*) from UserDetails
WHere UserName = "+txtUsername.text.trim().toLower() + " and Password = " +txtPassword.text.trim().toLower();
Object countResult = thisCommand.ExecuteScalar();
Console.WriteLine("Count of Customers = {0}", countResult);
thisConnection.Close();

Categories

Resources