Asp.net Session Variable from SQL DB - c#

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
}

Related

How do i save a registered user to the database?

I'm trying to add an user with an sqL query, and table, which works when i don't close the form. When i close the form it says that the user isn't registered, the code works, but i can't resolve this. It's as it doesn't save the users session data.
using System;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace SchoolManagementApplication
{
public partial class LoginDialog : Form
{
public LoginDialog()
{
InitializeComponent();
}
private bool VerifyUserCredentials(string username, string password, bool isLogin)
{
bool isValidUser = false;
// Connection string
string connectionString = Properties.Settings.Default.UnPConnectionString;
// SQL query for login
string loginQuery = "SELECT COUNT(*) FROM [Table2] WHERE Username = #Username AND Password = #Password";
// SQL query for registration
string registerQuery = "INSERT INTO [Table2] (Username, Password) VALUES (#Username, #Password)";
// Create a new connection
using (SqlConnection connection = new SqlConnection(connectionString))
{
// Open the connection
connection.Open();
// If the user wants to login
if (isLogin)
{
// Create a new command
using (SqlCommand command = new SqlCommand(loginQuery, connection))
{
// Add parameters to the query
command.Parameters.AddWithValue("#Username", username);
command.Parameters.AddWithValue("#Password", password);
// Execute the query
int result = (int)command.ExecuteScalar();
// Check if the result is greater than 0
if (result > 0)
{
isValidUser = true;
}
}
}
// If the user wants to register
else
{
// Create a new command
using (SqlCommand command = new SqlCommand(registerQuery, connection))
{
// Add parameters to the query
command.Parameters.AddWithValue("#Username", username);
command.Parameters.AddWithValue("#Password", password);
// Execute the query
int result = command.ExecuteNonQuery();
// Check if the result is greater than 0
if (result > 0)
{
isValidUser = true;
}
}
}
}
return isValidUser;
}
private void BtnOK_Click(object sender, EventArgs e)
{
// Get the entered username and password
string username = tbxUsername.Text;
string password = tbxPassword.Text;
// Verify the user credentials
if (VerifyUserCredentials(username, password, true))
{
MessageBox.Show(string.Format("Welcome: {0}", username));
// Code to open the main application goes here
this.Hide();
MainInterface MI = new MainInterface();
MI.Show();
}
else
{
MessageBox.Show("Invalid credentials. Please try again.");
// Clear the textboxes
tbxUsername.Text = "";
tbxPassword.Text = "";
}
}
private void Btn_register_Click(object sender, EventArgs e)
{
// Get the entered username and password
string username = tbxUsername.Text;
string password = tbxPassword.Text;
// Verify the user credentials
if (VerifyUserCredentials(username, password, false))
{
MessageBox.Show(string.Format("Successful registration: {0}", username));
}
else
{
MessageBox.Show("Registration failed. Please try again.");
}
}
}
}

How to query specific column in a UWP application?

I need to create a login that displays user data after login in a gridview / datatable
I'm able to display the username / password but not the user ID that's needed.
I've also tried creating a class where the values gets stored after login
private bool DataValidation(string user, string pass)
{
using (MySqlConnection conn = new MySqlConnection(connectionString))
using (MySqlCommand cmd = new MySqlCommand("SELECT * "+
"FROM member " +
"WHERE username=#user AND password=#pass;", conn))
{
cmd.Parameters.AddWithValue("#user", user);
cmd.Parameters.AddWithValue("#pass", pass);
cmd.Connection = conn;
cmd.Connection.Open();
MySqlDataReader login = cmd.ExecuteReader();
List<Connect> connectList = new List<Connect>();
while (login.Read())
{
Connect connect = new Connect();
connect.username = login.GetString(0);
connect.password = login.GetString(1);
connect.userID = login.GetString(4);
connectList.Add(connect);
}
if(connectList.Count > 0)
{
return true;
}
else
{
return false;
}
}
I'm mostly not sure how to store or display the values after they have been queried
Based on our conversation in the comments, let's focus on this code:
MySqlDataReader login = cmd.ExecuteReader();
if (login.Read())
{
conn.Close();
return true;
}
else
{
conn.Close();
return false;
}
The only thing we are doing here is finding out if login contains any rows. But we are not doing anything with those rows.
Let's try something like this instead:
MySqlDataReader login = cmd.ExecuteReader();
while (login.Read())
{
var something1 = login.GetString(0); // this will get the value of the first column
var something2 = login.GetString(1); // this will get the value of the second column
}
Or, if you are adding the results to an object:
MySqlDataReader login = cmd.ExecuteReader();
List<MyObject> myObjectList = new List<MyObject>;
while (login.Read())
{
MyObject myObject = new MyObject;
myObject.something1 = login.GetString(0); // this will get the value of the first column
myObject.something2 = login.GetString(1); // this will get the value of the first column
myObjectList.Add(myObject);
}
if (myObjectList.Count > 0)
{
return true;
}
else
{
return false;
}
You will need to adjust to meet your needs, but hopefully, this will get you there.
More info here: SqlDataReader.Read Method

object cannot be cast from DBNULL to other types model mvc5

I am creating a web app with mvc5 i have multiple users in my database
for eg
USERS
user1) username=ibrahim Password=1ibrahim
user2) username=admin password=4321
when i am logging in from user 1(ibrahim) the page is successfully redirecting to welcome page,
but when i am logging in from user to(admin) the error is coming
An exception of type 'System.InvalidCastException' occurred in
mscorlib.dll but was not handled in user code
Additional information: Object cannot be cast from DBNull to other
types.
on user = Convert.ToBoolean(cmd.ExecuteScalar()); this line
here is my code
public class loginuser
{
SqlCommand cmd;
public string role { get; set; }
public string username { get; set; }
public string password { get; set; }
public bool getlogintype(string role, string username, string password)
{
string tru = "";
string fals = "";
bool user;
string strname = "";
SqlConnection con = new SqlConnection("Data Source=erp.hti-india.com,1434;Initial Catalog=erp;Connect Timeout=3600;User Id=erprakesh;Password=14erprakesh14");
List<object> login = new List<object>();
if (role == "Admin" || role == "Super Admin" || role !=null)
{
cmd = new SqlCommand("select * from [admin] where userid='" + username + "' and pass ='" + password + "'", con);
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
user = true;
//HttpContext.Current.Session["userid"] = username.ToString();
//HttpContext.Current.Session["tru"] = tru.ToString();
// want to redirect to welcome page if condition satisfied.
}
else
{
user = false;
//want to show the label error message(declare as string errormsg)
}
con.Close();
}
con.Open();
user = Convert.ToBoolean(cmd.ExecuteScalar());
con.Close();
return user;
}
}
Your query returns null, represented by DBNull.Value. You should check on that before converting to a boolean:
object result = cmd.ExecuteScalar();
if (result == DBNull.Value)
{
user = false; // or something like that
}
else
{
user = Convert.ToBoolean(result);
}
Be aware that your statement is vulnerable for SQL injection. Always use parameterized queries! Also be careful with your select *. If you add columns you might end up in problems. Only select the field you require.

How to check if value already exists

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
}

MySqlCommand: no rows returned

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;
}
}
}
}
}

Categories

Resources