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;
}
}
}
}
}
Related
In this database table (administration), there are 4 attributes (email, name, password and mobile phone). I need that inside the if I can use each one of them but I don't know how I can access them.
How can I do this?
private void button_login_Click(object sender, EventArgs e)
{
String username, user_password;
username = txt_username.Text;
user_password = txt_password.Text;
try
{
String query = "SELECT * FROM administracao WHERE email = '"+txt_username.Text+"' AND password = '"+txt_password.Text+"'";
SqlDataAdapter sda = new SqlDataAdapter(query, conn);
DataTable dtable = new DataTable();
sda.Fill(dtable);
if (dtable.Rows.Count > 0)
{
// username = txt_username.Text;
// user_password = txt_password.Text;
/* Menuform form2 = new Menuform();
form2.Show();
this.Hide();*/
}
else
{
MessageBox.Show("Invalid Login details", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
txt_username.Clear();
txt_password.Clear();
txt_username.Focus();
}
}
catch
{
MessageBox.Show("Error");
}
finally
{
conn.Close();
}
}
For communication with database I would strongly recommend Entity Framework.
In your case you can use SqlDataReader to get output data from sql query
Code Example:
public void GetData()
{
var query = "your query";
var connectionString = "your connection string";
using (var connection = new SqlConnection(connectionString))
{
var command = new SqlCommand(query, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
// Iterate all selected rows
while (reader.Read())
{
int value1 = (int)reader["Int column name"];
string value2 = (string)reader["String column name"];
}
}
finally
{
reader.Close();
}
}
}
NOTE:
In real project NEVER store passwords as plaintext. How to do it properly
As people already mentioned in the comments, when you decide to execute query directly from the code NEVER combine query like you did, because of SQL Injection. Use parametrized SqlCommands. How to do it
I have a database that contains a table named "User(login,password,firstname,lastname)" . And I need to make login page . I've watched some tutorials , but it didn't help . I need to check if login and password exist in the database . and then redirect(if correct) to other page . This is what I already did:
OleDbConnection con = new OleDbConnection();
public bool check()
{
con.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Volodia\Documents\WebSiteDatabase.accdb";
con.Open();
string commandstring = "SELECT login,password FROM User";
//objadapter = new SqlDataAdapter(CommandString, sqlconn.ConnectionString);
OleDbDataAdapter objadapter = new OleDbDataAdapter(commandstring, con.ConnectionString);
DataSet dataset = new DataSet();
objadapter.Fill(dataset, "User");// it shows "Syntax error in FROM clause." here
DataTable datatable = dataset.Tables[0];
for (int i = 0; i < datatable.Rows.Count; i++)
{
string unam = datatable.Rows[i]["login"].ToString();
string upwd = datatable.Rows[i]["password"].ToString();
if ((unam == TextBox1.Text)&&(upwd==TextBox2.Text))
{
return true;
}
}
return false;
}
protected void Button1_Click(object sender, EventArgs e)
{
if (check() == true)
{
Response.Redirect("WebForm2.aspx");
}
}
The word PASSWORD is a reserved keyword for MS-Access Jet SQL. If you want to use it you need to enclose it in square brackets, the same for USER
string commandstring = "SELECT login, [password] FROM [User]";
This will resolve the immediate problem of the Syntax Error but let me add some other code to show a different approach
public bool check()
{
string conString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Volodia\Documents\WebSiteDatabase.accdb";
using(OleDbConnection con = new OleDbConnection(conString)
{
con.Open();
string commandstring = "SELECT count(*) as cntUser FROM [User] " +
"WHERE login = ? AND [password] = ?";
using(OleDbCommand cmd = new OleDbCommand(commandstring, con))
{
cmd.Parameters.AddWithValue("#p1", TextBox1.Text);
cmd.Parameters.AddWithValue("#p2", TextBox2.Text);
int result = (int)cmd.ExecuteScalar();
if(result > 0)
return true;
}
}
return false;
}
First, do not use a global connection object but create and use the
connection only when needed.
Second, encapsulate the disposable objects like the connection and
the command with the using statement that will ensure a correct close
and dispose,
Third, pass the login and the password as conditions for the where
clause (more on this later)
Fourth, use the parametrized query to avoid syntax errors and sql
injection
Usually is not a good practice to store a password in clear text inside the database. You need to store only the hash of the password and recalculate this hash every time you need to check the user authenticity
I am generating a random number admission no and this is my DAL
public static int randomgen()
{
int id=0;
int number = r.Next(100);
HttpContext.Current.Session["number"] = "SN" + (" ") + number.ToString();
SqlConnection con = DBConnection.OpenConnection();
try
{
string sql1 = "select admissionno from tblstudent_details";
SqlCommand cmd=new SqlCommand(sql1,con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
id = Convert.ToInt32(dr[0]);
}
dr.Close();
return id;
}
catch (Exception)
{
throw;
}
}
and i am checking if there is any duplicate is getting generated but i am getting an error like Input string is not in a correct format?Where i am doing wrong?Is any better way than this?
You asked if there is a better way...
From what I understand about the question what you are trying to do is pick a random value and then check the database to see if that value already exists. You want to return a value back to the UI to tell the UI whether the value exists or not...
Here is a couple alternatives to consider...
public static bool randomgen()
{
bool isFound = false;
string admissionNumber = "SN " + r.Next(100);
HttpContext.Current.Session["number"] = admissionNumber;
using (SqlConnection con = new SqlConnection()) // use "using" to guarantee connection is closed
{
string sql1 = "SELECT CASE WHEN EXISTS(SELECT admissionno FROM tlblstudent_details WHERE admissionno = #admissionno) THEN 1 ELSE 0 END";
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = sql;
cmd.Parameters.AddWithValue("#admissionno", number);
using (SqlDataReader dr = cmd.ExecuteReader())
{
if (dr.Read())
{
isFound = (Convert.ToInt32(dr[0]) == 1)
}
}
}
}
return isFound;
}
This way you let SQL Server check to see if the value exists.
Another approach...
Not sure if you are required to prompt the user if the value is not unique, if that is not a requirement then I would consider a different approach; Keep trying until you find a unique value...Like this...
public static int randomgen()
{
bool isFound = true;
while (isFound)
{
string admissionNumber = "SN " + r.Next(100);
using (SqlConnection con = new SqlConnection()) // use "using" to guarantee connection is closed
{
string sql1 = "SELECT CASE WHEN EXISTS(SELECT admissionno FROM tlblstudent_details WHERE admissionno = #admissionno) THEN 1 ELSE 0 END";
using (SqlCommand cmd = con.CreateCommand(sql1))
{
cmd.Parameters.AddWithValue("#admissionno", admissionNumber);
using (SqlDataReader dr = cmd.ExecuteReader())
{
if (dr.Read())
{
isFound = (Convert.ToInt32(dr[0]) == 1)
}
}
}
}
return number;
}
This keeps checking until a unique value is returned. Then you return that unique value to the calling method. Now you set HttpContent.Current session from the caller, leaving the responsibility of this method to only be finding a unique Admission Number. The downside to the second approach is that it may take a long time to find a unique value, depending on how many values are already used, especially considering you are only allowing 100 values.
Hope this gives you good alternatives to consider. Let me know if you have additional questions.
i have a php code.here is the code,i gonna to translate it to .NET but in some point i'm getting some trouble.
function processInput($conn, $MessageArray, $mobilenumber, $date, $odd)
{
$strSQLUSER="SELECT * FROM tbl_tiduser WHERE username='".addslashes($MessageArray[0])."' AND stat!='1' AND stat!='4'";
$result_user=odbc_exec($conn,$strSQLUSER) or die("Could not connect to database");
here is the converted .NET code
public class ProcessInput
{
private string msg_arr;
private string MooseSeenInput(string MobileNo,string Date,string odd,params Array[] msg_arr)
{
SqlCommand com = new SqlCommand("SELECT * FROM tbl_tiduser WHERE username=#username AND stat!='1' AND stat!='4'", mycon);
com.Parameters.AddWithValue("#username",username);
using (SqlDataReader reader = com.ExecuteReader())
// whats the next part need to come here ???
}
this is incomplete.i'm not going to compile it....
private static void ReadOrderData(string connectionString)
{
string queryString =
"SELECT OrderID, CustomerID FROM dbo.Orders;";
using (SqlConnection connection =
new SqlConnection(connectionString))
{
SqlCommand command =
new SqlCommand(queryString, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
// Call Read before accessing data.
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader[0], reader[1]));
}
// Call Close when done reading.
reader.Close();
}
}
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.aspx
I would use something like this to get the column(s) you're after:
string username = null;
using (SqlDataReader reader = com.ExecuteReader()) {
if (reader.read()) {
username = (string)reader["mydbcolumnname"];
}
reader.Close();
}
Note that if you want to pull all the result rows (as opposed to stepping through them) then you'd normally use a SqlDataAdapter to fill a DataSet (instead of the reader), eg:
string username;
using (SqlDataAdapter adapter = new SqlDataAdapter(com))
{
using (DataSet ds)
{
adapter.Fill(ds);
username = (string)ds.Tables[0].Rows[0]["mycolumnname"];
}
}
I'm all for easy; I would write a class that mirrors the record I'm reading, i.e.
public class User {
public int Id {get;set;}
public string Name {get;set;}
}
and use "dapper":
var user = myCon.Query<User>(
"SELECT * FROM tbl_tiduser WHERE username=#username AND stat not in ('1','4')",
new {username}).SingleOrDefault();
if(user == null) { /* not found, presumably throw an exception */ }
string name = user.Name; // etc
Then you don't need to mess with commands, readers, parameters etc (see how the username is being made into a db parameter cleanly?).
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
}