In my code behind, I have this
{
Label2.Text = "[" + HttpContext.Current.User.Identity.Name + "]";
}
to identify the username in domain. So far so good. It works properly in IIS.
However, I would like to store the username into a database. How can I do that?
The idea is to record the person who answer to this:
string insertCmd = "INSERT INTO worker(Business,Business2,Mobile) VALUES (#Business,#Business2,#Mobile)";
using (Conn)
{
Conn.Open();
OleDbCommand myCommand = new OleDbCommand(insertCmd, Conn);
myCommand.Parameters.AddWithValue("#Business", business.Text);
myCommand.Parameters.AddWithValue("#Business2", business2.Text);
myCommand.Parameters.AddWithValue("#Mobile", mobile.Text);
myCommand.ExecuteNonQuery();
Label1.Text = "Saved Successfull!";
Label1.ForeColor = System.Drawing.Color.Green;
}
I have the answer inserted into the database, but how can I save the person who answer? Can I save the label into the database table? Or is it impossible?
Just add a username field to your table and add another parameter:
string insertCmd = "INSERT INTO worker(Business,Business2,Mobile,username) VALUES (#Business,#Business2,#Mobile,#username)";
using (Conn) {
Conn.Open();
OleDbCommand myCommand = new OleDbCommand(insertCmd, Conn);
myCommand.Parameters.AddWithValue("#Business", business.Text);
myCommand.Parameters.AddWithValue("#Business2", business2.Text);
myCommand.Parameters.AddWithValue("#Mobile", mobile.Text);
myCommand.Parameters.AddWithValue("#username", HttpContext.Current.User.Identity.Name);
myCommand.ExecuteNonQuery();
Label1.Text = "Saved Successfull!";
Label1.ForeColor = System.Drawing.Color.Green;
}
Related
Can anyone explain me how does it matches username and password from data table and logs in the user?
DataTable dtForNameAndRole = LoadDataByQuery(sql);
try
{
**if (dtForNameAndRole.Rows.Count > 0)**
{
Session["username"] = dtForNameAndRole.Rows[0]["username"].ToString(); //userID;
Session["password"] = dtForNameAndRole.Rows[0]["password"].ToString(); //userID;
txtpassword.Text = string.Empty;
txtusername.Text = string.Empty;
Response.Redirect("Dashboard.aspx");
Can you please use the below code it'll help you!
using (SqlConnection sqlcon = new SqlConnection(connectionString)){
//string user = txtEmail.Text;
//string pass = txtPassword.Text;
sqlcon.Open();
SqlCommand cmd = new SqlCommand("select count(*) from [dbo].[Register] where Email=#Email and Password=#Password", sqlcon);
cmd.Parameters.AddWithValue("#Email", txtEmail.Text);
cmd.Parameters.AddWithValue("#Password", ToSHA2569(txtPassword.Text));
var isCorrectPassword = cmd.ExecuteScalar();
if ((int)isCorrectPassword >= 1)
{
//sqlcon.Close(); //taken care of because of the using command
Response.Redirect("default.aspx");
}
else
{
// sqlcon.Close();
lblWrong.Text = "Password not correct";
}
}
I have a table in my database and two textbox and a button in my ASP.NET. I want to call database and select product name and code and if the entrance is correct I want to ok message, otherwise false!
Here is my code, but I did not get correct result.
try
{
string constring = System.Configuration.ConfigurationManager.ConnectionStrings["WebDataBaseConnectionString"].ConnectionString;
SqlConnection scon = new SqlConnection(constring);
scon.Open();
SqlCommand cmd = new SqlCommand("select * from Product where Name=#Name and Code=#Code", scon);
cmd.Parameters.AddWithValue("#Name", txtName.Text);
cmd.Parameters.AddWithValue("#Code", txtCode.Text);
SqlDataReader dr = cmd.ExecuteReader();
scon.Close();
Label1.Text = "The Product is in our list.Thank you";
}
catch(Exception)
{
Label1.Text = "The Product is not in our list.Sorry!";
}
Your query is modified as below
try
{
string constring = System.Configuration.ConfigurationManager.ConnectionStrings["WebDataBaseConnectionString"].ConnectionString;
SqlConnection scon = new SqlConnection(constring);
scon.Open();
SqlCommand cmd = new SqlCommand("select * from Product where Name=#Name and Code=#Code", scon);
cmd.Parameters.Add("#Name", SqlDbType.Varchar).Value = txtName.Text;--Update the datatype as per your table
cmd.Parameters.Add("#Code", SqlDbType.Varchar).Value = txtCode.Text;--Update the datatype as per your table
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
--If you want to check the whether your query has returned something or not then below statement should be ommitted. Else you can check for a specific value while reader is reading from the dataset.
while (dr.Read())
{
--The returned data may be an enumerable list or if you are checking for the rows the read statement may be ommitted.
--To get the data from the reader you can specify the column name.
--for example
--Label1.Text=dr["somecolumnname"].ToString();
Label1.Text = "The Product is in our list.Thank you";
}
}
else
{
Label1.Text = "The Product is not in our list.Sorry!";
}
scon.Close();
}
catch (Exception)
{
Label1.Text = "The Product is not in our list.Sorry!";
}
Hope this answer will help you in resolving your query.
I am having a problem while login, the registered user's name, email and password is saved in the database and the email is the username. When i am logging through email and password it shows the error "There is no row at position 0."
Here's my code :
con.Open();
cmd = new SqlCommand("select * from userinfo where username='" + t1.Text.ToString() + "' and password='" + t2.Text.ToString() + "'", con);
da = new SqlDataAdapter(cmd);
da.Fill(ds, "abc");
Session["name"] = ds.Tables["abc"].Rows[0][1].ToString();
con.Close();
cmd = new SqlCommand("SELECT * FROM userinfo WHERE username = #username AND password = #password", con);
cmd.Paramater.AddWithValue("#username", t1.Text.ToString());
cmd.Paramater.AddWithValue("#password", t2.Text.ToString());
con.open();
SqlDataReader dr = cmd.ExecuteReader();
dr.read();
if(dr.hasRows){
Session["name"] = dr["username"].ToString();
}
con.close();
Try not to throw variables into a sql command. SQL injection and all. Try and pass the paramater
Because reason is the no one record found in Db same as a passing username and password and you can directly access so its give exception. Please add one if condition below like.
con.Open();
cmd = new SqlCommand("SELECT * FROM userinfo WHERE username = #username AND password = #password", con);
cmd.Paramater.AddWithValue("#username", t1.Text.ToString());
cmd.Paramater.AddWithValue("#password", t2.Text.ToString());
da = new SqlDataAdapter(cmd);
da.Fill(ds, "abc");
if(ds.Tables["abc"].Rows.Count>0)
{
Session["name"] = ds.Tables["abc"].Rows[0][1].ToString();
}
con.Close();
The exception is because there are no records in that table.
There are no rows, so there is no Rows[0].
Try something like this:
using (var con = new SqlConnection(connectionString))
{
con.Open();
cmd = new SqlCommand("SELECT * FROM userinfo WHERE username = #1 AND password = #2", con);
cmd.Paramater.AddWithValue("#1", t1.Text);
cmd.Paramater.AddWithValue("#2", t2.Text);
da = new SqlDataAdapter(cmd);
da.Fill(ds, "abc");
if(ds.Tables["abc"].Rows.Any())
Session["name"] = ds.Tables["abc"].Rows[0][1].ToString();
con.Close();
}
You should use parameters when constructing SQL queries to avoid injection attacks.
Don't forget that SqlConnection is IDisposable, so should be in a using statement (you might already be doing this, but i've included it here just in case).
It also looks like the user's password is being compared to the input from a TextBox (or a similar control)? If so, the user's password should not be stored in plain text in the database as this is a security issue. Consider hashing the stored password, doing the same with the user's input, and comparing that instead.
This wasn't part of the question, I know, but worth pointing out just in case.
this programm when i enter username and password go to data base and compare from table,but when i enter username admin ,password admin(exist in table)
compalier show error "Incorrect syntax near 'admin'" in line
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\1\Documents\DB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
conn.Open();
string checkuser = "select count(*) from [Users] where Username '" + TextBoxUserName.Text + "'";
SqlCommand com = new SqlCommand(checkuser,conn);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
conn.Close();
if (temp == 1)
{
conn.Open();
string checkpassword = "select Password from Users where Password'" + TextBoxPassword.Text + "'";
SqlCommand passComm = new SqlCommand(checkpassword, conn);
string password = passComm.ExecuteScalar().ToString();
if (password == TextBoxPassword.Text)
{
//Session["NEW"] = TextBoxUserName.Text;
Response.Redirect("Welcome.aspx");
}
else
{
Response.Redirect("Error.aspx");
}
}
The error is simply caused by the missing equals before the values concatenated in the sql command text.
But also fixing it, your code is wrong for other reasons.
You should ALWAYS use a parameterized query to avoid Sql Injection and parsing problems,
You could remove the COUNT function that causes an unnecessary load of all records just to confirm the existence of your searched data
You need to identify your user searching for both password and
username on the SAME record, as it is now, the code above search first the username
and then a password, but I can type an existing user name (first if passed) and use
a password of a different user (second if passed) and then gain access to
your site.
.
string checkuser = "IF EXISTS(select 1 from [Users] where Username = #usr AND Password=#pwd)
SELECT 1 ELSE SELECT 0";
using(SqlConnection conn = new SqlConnection(....))
using(SqlCommand com = new SqlCommand(checkuser,conn))
{
conn.Open();
com.Parameters.AddWithValue("#usr", TextBoxUserName.Text);
com.Parameters.AddWithValue("#pwd", TextBoxPassword.Text);
int temp = Convert.ToInt32(com.ExecuteScalar());
if (temp == 1)
Response.Redirect("Welcome.aspx");
else
Response.Redirect("Error.aspx");
}
Other things changed in the example above are the USING STATEMENT to be sure that your connection and command are disposed at the end of the operation also in case of exceptions
Try changing this line
string checkuser = "select count(*) from [Users] where Username '" + TextBoxUserName.Text + "'";
to this
string checkuser = "select count(*) from [Users] where Username = '" + TextBoxUserName.Text + "'";
you are missing an = sign
you'll need to do the same to your password select as well, you also missed the = sign there.
string checkpassword = "select Password from Users where Password = '" + TextBoxPassword.Text + "'";
When checking the Password, you should also include the UserName:
string checkpassword = "select Password from Users where UserName = '" + TexBoxUserName.Text + "' AND Password = '" + TextBoxPassword.Text + "'";
If you do not include the UserName the it is only validating that some user has that password.
The following code will prevent SQL injection by paramterizing the command text
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\1\Documents\DB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
conn.Open();
string checkuser = "SELECT Count(UserName) FROM USERS WHERE UserName = #UserName";
SqlCommand com = new SqlCommand(checkuser,conn);
SqlParameter parmUserName = new SqlParameter("UserName", TextBoxUserName.Text);
com.Parameters.Add(parmUserName);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
conn.Close();
if (temp == 1)
{
conn.Open();
string checkpassword = "SELECT Password FROM USERS WHERE UserName = #UserName AND Password = #Password";
SqlCommand passComm = new SqlCommand(checkpassword, conn);
SqlParameter parmPassword = new SqlParameter("Password", TextBoxPAssword.Text);
com.Parameters.Add(parmUserName);
com.Parameters.Add(parmPassword);
string password = passComm.ExecuteScalar().ToString();
aspx
TextBox1.Text
World.aspx
TextBox1.Text
I want the pages Hello.aspx and World.aspx having same value of validation
please help me anybody have the idea about this
You need to save the value on the first page using cookies or database or something else.
Then retrieve the value in the second page and compare the values in the validation function or event.
using(SqlConnection cn = new SqlConnection(connStr))
{
using(SqlCommand cmd = new SqlCommand())
{
cmd.Connection = cn;
string sql = string.Format(#"select email from customers where customer_id = '{0}'", customer_id);
cmd.CommandType = CommandType.Text;
//try and catch block would go here
cmd.CommandText = sql;
cn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
string email = rdr[0].ToString();
cn.Close();
}
}