I am trying to find a lot of time how to check if value exists and I can not find it, I need to check it twice:
in the sign up
in the log in
Here is my code block:
SqlConnection c = new SqlConnection(str);
SqlCommand cmdUsername = new SqlCommand("SELECT 1 FROM Users WHERE UserName = #userName;", c);
cmdUsername.Parameters.AddWithValue("userName", userName);
cmdUsername.CommandType = System.Data.CommandType.Text;
SqlCommand cmdEmail = new SqlCommand("SELECT 1 FROM Users WHERE Email = #email;", c);
cmdUsername.Parameters.AddWithValue("email", email);
c.Open();
nameExists = (int)cmdUsername.ExecuteScalar();
emailExists = (int)cmdEmail.ExecuteScalar();
c.Close();
When I am entering an email it marks the line
emailExists = (int)cmdEmail.ExecuteScalar();
And in the log in all is ok.
Please help me! Thank you all.
Assuming you want to prevent duplicate User Name or Email you have to do the following.
1. Set the ID column as INT and set it to Identity column from column properties.
2. Set your Email or User Name as primary key to prevent either Email or User Name from duplication, The best practice is to make the Email column as primary key where there are a lot of cases that the users have same name but with unique emails.
Hope that helps!
And to check whether username or email exist already here how you do it!
SqlCommand check_User_Name = new SqlCommand("SELECT COUNT(*) FROM [Table] WHERE ([user] = #user || [email] = #email)" , c);
check_User_Name.Parameters.AddWithValue("#user", txtBox_UserName.Text);
check_User_Name.Parameters.AddWithValue("#email", txtBox_Email.Text);
int UserExist = (int)check_User_Name.ExecuteScalar();
if(UserExist > 0)
{
//Username exist
}
else
{
//Username doesn't exist.
}
Using your code, just optimized it a bit.
Just one call to database
Always close the connection even if a exception occurs
Returns false when not found or na exception occurs, true otherwis
You can also add a check to the password if this is a login check.
public bool ValidData(string username, string email, string connectionString)
{
var c = new SqlConnection(connectionString);
var cmdUsername = new SqlCommand("SELECT COUNT(*) FROM Users WHERE UserName = #userName AND email = #email;", c);
cmdUsername.Parameters.AddWithValue("userName", username);
cmdUsername.CommandType = System.Data.CommandType.Text;
cmdUsername.Parameters.AddWithValue("email", email);
c.Open();
try
{
return (int) cmdUsername.ExecuteScalar() > 0;
}
catch (Exception ex)
{
//log exception
return false;
}
finally
{
c.Close();
}
}
If you just need the username or the email change:
var cmdUsername = new SqlCommand("SELECT COUNT(*) FROM Users WHERE UserName = #userName AND email = #email;", c);
to:
var cmdUsername = new SqlCommand("SELECT COUNT(*) FROM Users WHERE UserName = #userName OR email = #email;", c);
Try this -
string myConnection=str;//this is your connection string
string userName="";
string email="";
string parameteruserName = "";//your parameter should goes here
string parameterEmail = "";//your parameter should goes here
try
{
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand(SELECT COUNT(*) as count FROM Users WHERE UserName =" +parameteruserName+" or Email ="+parameterEmail
) "+ ";",
myConnection);
myReader = myCommand.ExecuteReader();
while(myReader.Read())
{
userName= myReader["count"].ToString();
}
myReader.close();
myConnection.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
if(Convert.ToInt32(userName)>0){
//your user name is exists
}
Related
i want to create user CNIC account. for that i have picked a CNIC from tbl_1 and stored it into tbl_2 . And give a textbox to the user to enter only password because his cnic already exists in tbl_2. and i used "if" condition where i checked that if his CNIC is present in tbl_2 then he can enter password. but password isn't getting stored in tbl_2!!
protected void btnSubmitPassword_Click(object sender, EventArgs e)
{
try
{
string query = "select * from userlogin";
cmd.CommandText = query;
cmd.Connection = con;
MySqlDataReader msdr = cmd.ExecuteReader();
while (msdr.Read())
{
if (msdr[0].ToString() == txtUserCNIC.Text.ToString())
{
flag = true;
}
}
if (flag == true)
{
MySqlCommand mscmd = new MySqlCommand("insert into userlogin(UserPassword)values(#Password)", con);
mscmd.Parameters.AddWithValue("#Password", txtNewPassword.Text);
mscmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
Response.Write("" + ex);
}
}
If then CNIC alreay exist in table2 (userlogin) then you should use update and non insert .. Insert for create a new row .. instead for change an existing row, in SQL , you need UPDATE
update userlogin
set UserPassword = #Password
where CNIC = the_user_CNIC
and you should not use var in SQL you are at risk for SQL injection for avoid this you should take a look at prepared statement and binding param
I have code here where it will check if the entered username and password are correct, my problem is that in my database I have a Username: "ADMIN" and Password: "ADMIN" but whenever I try to input "admin" for both username and password it still allows me to go to the main window which means my bool was true.
Here is my code:
public bool IsAccountValid(string userLogin, string userPassword)
{
bool flag = false;
try
{
accessToDatabase.OpeningDatabase();
String query = "SELECT * FROM Users where Username=#Username AND Password=#Password";
SqlCommand sqlCmd = accessToDatabase.Command(query);
sqlCmd.CommandType = CommandType.Text;
sqlCmd.Parameters.AddWithValue("#Username", userLogin);
sqlCmd.Parameters.AddWithValue("#Password", userPassword);
if (sqlCmd.ExecuteScalar() != null)
flag = true;
else
flag = false;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
accessToDatabase.ClosingDataBase();
}
return flag; //returns false if query does not exists...
}
You can use ExecuteReader on SqlCommand to read values- which you can compare against user provided values. User Name shouldn't be case sensitive though.
My response assumes that username is unique in your user table - which i believe is pretty much valid assumption.
Since you only need username and pwd, you might want to modify your select query to :
SELECT UserName, Password
FROM Users
WHERE Username = #Username AND Password = #Password
Probably your revised snippet in that case would be something like :
public bool IsAccountValid(string userLogin, string userPassword)
{
bool flag = false;
try
{
accessToDatabase.OpeningDatabase();
String query = "SELECT * FROM Users where Username=#Username AND Password=#Password";
SqlCommand sqlCmd = accessToDatabase.Command(query);
sqlCmd.CommandType = CommandType.Text;
sqlCmd.Parameters.AddWithValue("#Username", userLogin);
sqlCmd.Parameters.AddWithValue("#Password", userPassword);
var reader = sqlCmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
if(userPassword == reader[0].ToString())
{
flag = true;
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
accessToDatabase.ClosingDataBase();
}
return flag; //returns false if query does not exists...
}
Other alternative would be modify your sql query itself to ensure it takes care of case sensitive match in where clause like here
In that case, you need not to make any changes to your ADO.NET code.
Better way would be to change query for case sensitive search:
String query = "SELECT * FROM Users where
Username=#Username COLLATE SQL_Latin1_General_CP1_CS_AS
AND Password=#Password COLLATE SQL_Latin1_General_CP1_CS_AS";
Another method is do binary casting:
String query = "SELECT * FROM Users
where CAST(Username as varbinary(100))=CAST(#Username as varbinary(100))
AND CAST(Password as varbinary(100))=CAST(#Password as varbinary(100))";
i want to to take the user name and password to the database and get the user role according to the inserted user name and password but this code does not work
public bool Login(out string Msg)
{
bool b = true;
Msg = "";
SqlConnection con = new SqlConnection(connection.connectstr);
try
{
con.Open();
SqlCommand com = new SqlCommand("user_proc", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.Add("#u_name", SqlDbType.NVarChar).Value = this.u_name;
com.Parameters.Add("#u_password", SqlDbType.NVarChar).Value = this.u_password;
com.ExecuteNonQuery();
con.Close();
b = true;
}
catch (Exception ex)
{
con.Close();
Msg = ex.Message;
b = false;
}
return b;
}
and the c# code that should check the role into database and redirect me to server page if admin and client page if not:-
protected void btn_login_Click(object sender, EventArgs e)
{
my_user u = new my_user();
u.u_name = TextBox1.Text;
u.u_password = TextBox2.Text;
string m="";
if (!u.Login(out m))
{
lbl_role.Text = "error";
}
else
{
if (u.u_role == "admin")
{
Response.Redirect("testclient.aspx");
}
else Response.Redirect("testserver.aspx");
}
}
and the database procedure that performs that task is:
create procedure user_proc
(#u_name nvarchar(50) ,
#u_password nvarchar(50),
#u_role nvarchar(50))
as
begin
begin try
begin transaction
if exists (select u_role from user_sys
where u_name=#u_name and u_password= #u_password)
commit
End try
Begin catch
rollback
declare #msg varchar(200)
set #msg = ERROR_MESSAGE()
raiserror(#msg , 16 , 1)
End catch
End
hehe , look, there's no need to do this complicated
In the DB you have a user table with name,pass and role
so, the role is admin or not
then, i suggest
In your app check with SqlExecuteScalar
public bool IsAdmin(string u_name, string u_password)
{
string role="";
string sql = "select u_role from user_sys
where u_name=#u_name and u_password= #u_password";
using (SqlConnection conn = new SqlConnection(connection.connectstr))
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add(new SqlParameter("#u_name", u_name));
cmd.Parameters.Add(new SqlParameter("#u_password", u_password));
try
{
conn.Open();
role = cmd.ExecuteScalar().ToString();
}
catch (Exception ex)
{
//handle error
}
}
return role == "admin";
}
Finally call it
string u_name = TextBox1.Text;
string u_password = TextBox2.Text;
if (IsAdmin(u_username,u_password))
//it is admin
else
//it is not admin
Bye bye and have fun !
I have a database created in a server and I added a row by MySql query browser for testing. This row is visible either with PhpMyAdmin or MySql query browser.
But when I want to reach this table within my program it says me there is no rows (reader.HasRows = false)
cs is the connection string in PublicVariables class
Here is the code
public static int checkuser(string myuser, string mypass)
{
try
{
using (MySqlConnection conn = new MySqlConnection(PublicVariables.cs))
{
string MypassMd5 = MakeMD5(mypass);
conn.Open();
if (conn == null)
Environment.Exit(0);
using (MySqlCommand cmd =
new MySqlCommand("SELECT username, password " + "FROM Users WHERE username = 'myuser'" ,conn))
{
using (MySqlDataReader reader = cmd.ExecuteReader())
{
//DateTime mytime = DateTime.Now ;
if (reader.HasRows)
{
if (Convert.ToString(reader["password"]) != MypassMd5)
{
reader.Close();
conn.Close();
return -1;
}
else
{
PublicVariables.UserId = Convert.ToString(reader["username"]);
PublicVariables.UserDegre = Convert.ToInt16(reader["userdegre"]);
conn.Close();
reader.Close();
return 1;
}
}
else
{
reader.Close();
conn.Close();
return 2;
}
}
}
}
}
catch (MySqlException ex)
{
MessageBox.Show(ex.ToString());
}
return 0;
}
What's wrong in my code?
Well the primary error is in your command string , myuser is a variable and you cannot pass its value putting the variable name inside quotes.
new MySqlCommand("SELECT username, password FROM Users WHERE username = 'myuser'" ,conn)
instead this line should be converted to use a parameterized query
string commandText = "SELECT username, password, userdegre FROM Users WHERE username = #uname";
using (MySqlCommand cmd = new MySqlCommand(commandText ,conn)
{
cmd.Parameters.AddWithValue("#uname", myuser);
....
Looking at your code you have another error after this. You try to read the field userdegre, but this field is not retrieved by your query, so you need to add it to the list of retrieved fields.
But the only field you really need to know is userdegre because you already know the username and the password, so you could remove the datareader and use ExecuteScalar and pass the username and the password as parameters for the WHERE clause. If you get anything in return then you are sure that your user is authenticated by the database.
string commandText = "SELECT userdegre FROM Users WHERE username = #uname AND Password =#pwd";
using(MySqlCommand cmd = new MySqlCommand( commandText ,conn))
{
cmd.Parameters.AddWithValue("#uname", myuser);
cmd.Parameters.AddWithValue("#pwd", MypassMd5);
var result = cmd.ExecuteScalar();
if(result != null)
{
PublicVariables.UserId = myuser;
PublicVariables.UserDegre = result.ToString();
}
}
Don't check reader.HasRows. You need to call reader.Read(), and check the result of that.
Also, some side issues:
MD5 is incredibly weak for a password hash. Really. Just don't use it for that. Look into bcrypt as a much better alternative. Better still if you're not writing authentication code yourself at all. Look for a library for help to get this stuff right... it's just so easy to write authentication code that seems to work, passes all your tests, but has a subtle flaw that gets you hacked a few months down the road.
No need to call conn.Close(). That's what your using blocks are for. They will handle this for you.
I'd remove the try/catch as well. Since you're already returning error conditions to the calling code, I'd leave that as the place where errors are processed, such that your try/catch should go at that level.
You're looking for userdegre in the results that was not in the select list.
Parameterized queries are your friend.
Put it all together you and you end up with this:
public static int checkuser(string myuser, string mypass)
{
string passHash = BCrypt(mypass); //Need to get bcyrpt library and make the function
using (MySqlConnection conn = new MySqlConnection(PublicVariables.cs))
using (MySqlCommand cmd =
new MySqlCommand("SELECT username, password, userdegre FROM Users WHERE username = #user" ,conn))
{
cmd.Parameters.Add("#user", SqlDbType.NVarChar, 20).Value = myuser;
conn.Open();
using (MySqlDataReader reader = cmd.ExecuteReader())
{
if (!reader.Read()) return 2;
if (Convert.ToString(reader["password"]) != MypassMd5) return -1;
PublicVariables.UserId = Convert.ToString(reader["username"]);
PublicVariables.UserDegre = Convert.ToInt16(reader["userdegre"]);
return 1;
}
}
}
I would try something like this new MySqlCommand("SELECT username, password, userdegre " + "FROM Users WHERE username = 'myuser'" ,conn))
adding userdegre the column name in your select statement.
Finally for c# 2008 net 3.5 WORKING COPY of this after the help of #Joel and # Steve is as this:
public static int usertrue(string myuser, string mypass)
{
try
{
using (MySqlConnection conn = new MySqlConnection(PublicVariables.cs))
{
string MypassMd5 = MakeMD5(mypass);
using (MySqlCommand cmd =
new MySqlCommand("SELECT username, password ,userdegre FROM Users WHERE username = #user",conn))
{
cmd.Parameters.Add("#user", MySqlDbType.VarChar, 15).Value = myuser;
conn.Open();
using (MySqlDataReader reader = cmd.ExecuteReader())
{
if (!reader.Read()) return 2;
if (Convert.ToString(reader["password"]) != MypassMd5) return -1; {
PublicVariables.UserId = Convert.ToString(reader["username"]);
PublicVariables.UserDegre = Convert.ToInt16(reader["userdegre"]);
return 1;
}
}
}
}
}
I created a custom login page using Forms Authentication and using a sQL DB to store user data. I am able to create a session variable from the username, but wondering if it is possible to pull a separate field and create a session variable based on that. I would like the session variable to be based off a SalesNumber a 5 digit decimal field. Please give me any comments or suggestions.
cmd = new SqlCommand("Select pwd,SalesNumber from users where uname=#userName", conn);
cmd.Parameters.Add("#userName", System.Data.SqlDbType.VarChar, 25);
cmd.Parameters["#userName"].Value = userName;
Session["userName"] = userName;
Thanks....
Also keep in mind you can store an entire object in the session instead of seperate variables:
UserObject user = DAL.GetUserObject(userName);
Session["CurrentUser"] = user;
// Later...
UserObject user = Session["CurrentUser"] as UserObject;
// ...
To add on, you could wrap it in a nice property:
private UserObject CurrentUser
{
get
{
return this.Session["CurrentUser"] as UserObject;
}
set
{
this.Session["CurrentUser"] = value;
}
}
When you get the SalesNumber from your database query, just use
Session["SalesNumber"] = <the value of the SalesNumber column from the query>
Or is there something else I'm missing in the question...?
in your DAL just create your Login sequence like:
public bool LoginUser(String username, String password)
{
bool r = false;
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConn"].ConnectionString))
{
using(SqlCommand cm = new SqlCommand())
{
cm.Connection = cn;
cm.CommandType = CommandType.Text;
cm.CommandText = "SELECT Name, SalesNumber FROM users WHERE uname = #username AND pwd = #password;";
cm.Parameters.AddWithValue("#username", username);
cm.Parameters.AddWithValue("#password", password);
cn.Open();
SqlDataReader dr = cm.ExecuteReader();
if (dr.HasRows)
{
// user exists
HttpContext.Current.Session["SalesNumber"] = dr["SalesNumber"].ToString();
HttpContext.Current.Session["Username"] = username;
HttpContext.Current.Session["Name"] = dr["Name"].ToString();
r = true;
}
else
{
// Clear all sessions
HttpContext.Current.Session["SalesNumber"] = "";
HttpContext.Current.Session["Username"] = "";
HttpContext.Current.Session["Name"] = "";
}
}
}
return r;
}
from your code, in the login button click event just add
if (dalLogin.LoginUser(TextBoxUsername.Text.Trim(), TextBoxPassword.text.Trim()))
{
// User logged in sucessfuly
// all sessions are available
Response.Redirect("homepage.aspx");
}
else
{
// Username and password did not match! show error
}