Using sessions in c# - c#

This is my code using sessions in C# for login. I have business logic and data access layer written for this, but my code is not working as expected. Even if there is no record in DB, i am able to login and it redirects to error.aspx
Default.aspx.cs
public void LoginButton_Click(object sender, System.EventArgs e)
{
int id;
if (LoginName.Text!=""&& Password.Text!="")
{
try
{
sessionVars = BL_Authenticate.AuthenticateUser(sessionVars, LoginName.Text, Password.Text);
Response.Redirect("home.aspx");
}
catch (Exception ex)
{
Session["Exception"] = ex.Message.ToString();
Response.Redirect("error.aspx");
}
//else
//{
// Response.Redirect("error.aspx");
//}
if (sessionVars.Tables[0].Rows.Count >= 1)
{
try
{
Session["User"] = (string)sessionVars.Tables[0].Rows[0]["FirstName"];
Session["User"] += (string)" ";
Session["User"] += (string)sessionVars.Tables[0].Rows[0]["LastName"];
}
catch (Exception ex)
{
Session["Exception"] = ex.Message.ToString();
Response.Redirect("error.aspx");
}
id = (int)sessionVars.Tables[0].Rows[0][0];
if (id >= 1)
{
try
{
Session["Role"] = "Admin";
FormsAuthentication.Authenticate((string)sessionVars.Tables[0].Rows[0]["Login"], (string)sessionVars.Tables[0].Rows[0]["Password"]);
}
catch (Exception ex)
{
Session["Exception"] = ex.Message.ToString();
Response.Redirect("error.aspx");
}
if (FormsAuthentication.GetRedirectUrl("Admin", false) == "/UserInterface/home.aspx")
{
FormsAuthentication.RedirectFromLoginPage("admin", false);
Response.Redirect("home.aspx");
}
else
FormsAuthentication.RedirectFromLoginPage("admin", false);
}
else
{
Session["Role"] = "User";
FormsAuthentication.RedirectFromLoginPage("user", false);
}
}
else
{
errorMessage.Text = "Sorry, wrong username or password.";
}
}
}
}
BL_Authenticate
public class BL_Authenticate
{
public static DataSet AuthenticateUser(DataSet user, string login, string password)
{
return DAL_Authenticate.AuthenticateUser(user, login, password);
}
}
DAL_Authenticate
public static DataSet AuthenticateUser(DataSet dataset, string login, string password)
{
try
{
//Dispose all objects that have a .Dispose()
SqlDataAdapter adapter = new SqlDataAdapter();
conn = DAL_DataBaseConnection.GetConnection();
SqlCommand cmd = new SqlCommand("authentication", conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter param = cmd.Parameters.Add("#Login", SqlDbType.VarChar, 255);
param.Value = login;
param = cmd.Parameters.Add("#Password", SqlDbType.VarChar, 255);
param.Value = password;
adapter.SelectCommand = cmd;
adapter.Fill(dataset);
}
finally
{
conn.Close();
}
return dataset;
}

One normal thing I see is that if the login fails, it redirect to an error page, so there is no mistake there, are you sure your login as work at that point ?

Related

Checking if username already exists in database before registering

I am trying to add functionality to check the entered username and see if it exists in the MySql database before the user is successfully registered. I've tried looking at other similar questions and but because I lack the experience I cannot seem to implement it properly in my code.
Here's what I have so far:
private void button1_Click(object sender, EventArgs e)
{
string user = tbUser.Text;
string pass = tbPass.Text;
string email = tbEmail.Text;
if (tbUser.Text == "" || tbPass.Text == "" || tbEmail.Text == "")
{
MessageBox.Show("Please fill out all fields.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else {
bool exists = false;
string checkuser = $"SELECT COUNT(*) from users where name = {user}";
try
{
if (OpenConnection())
{
MySqlCommand cmd = new MySqlCommand(checkuser, conn);
try
{
cmd.Parameters.AddWithValue("name", tbUser.Text);
exists = (int)cmd.ExecuteScalar() > 0;
}
catch (Exception ex)
{
}
if (exists)
MessageBox.Show("Username already exists.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
else
{
Register(user, pass, email);
MessageBox.Show("Successfully Registered!");
this.Close();
}
}
}
catch (Exception ex)
{
}
}
}
public bool Register(string user, string pass, string email)
{
string register = $"INSERT INTO users (name, password, email) VALUES('{user}', '{pass}', '{email}');";
try
{
if (OpenConnection())
{
MySqlCommand cmd = new MySqlCommand(register, conn);
try
{
cmd.ExecuteNonQuery();
return true;
}
catch (Exception ex)
{
return false;
}
}
else
{
conn.Close();
return false;
}
}
catch (Exception ex)
{
conn.Close();
return false;
}
}
private bool OpenConnection()
{
try
{
conn.Open();
return true;
}
catch (MySqlException ex)
{
switch (ex.Number)
{
case 0:
MessageBox.Show("Connection to the server failed.");
break;
case 1045:
MessageBox.Show("Database username or password is incorrect.");
break;
}
return false;
}
}
The above code doesn't work in registering the user & neither does it work in checking if the username exists. Would appreciate any help in pointing me in the right direction :)
The syntax, as far as I know, to declare a parameter in a command text isn't {user} but #user.
So this line of code of yours
string checkuser = $"SELECT COUNT(*) from users where name = {user}";
Should be
string checkuser = $"SELECT COUNT(*) from users where name = #user";
And the "#user" must correspond to the parameters name you are adding.
You falsly call the parameter name instead of user on this line
cmd.Parameters.AddWithValue("name", tbUser.Text);
So it should look like this
cmd.Parameters.AddWithValue("user", tbUser.Text);
As #Transcendent already mentioned in the comments in your Register method you never acutally add the 3 parameters used in the command text, to your parameters collections so those line are simply missing
cmd.Parameters.AddWithValue("user", tbUser.Text);
cmd.Parameters.AddWithValue("pass", tbPass.Text); //this line assumes there is a textbox called tbPass
cmd.Parameters.AddWithValue("email", tbEmail.Text); //this line assumes there is a textbox called tbEmail

Exception is not Passed from API to Application

I'm using a Web API MVC code, I get an exception in the database layer, but when it passed to the application layer, it's returning without any exception.
I am unable to handle the exception from web API
Database Layer
public int DBPostGeneralConfig(GeneralConfigtDets Getgencon)
{
int result = 0;
SqlConnection sqlConnection = null;
try
{
string user = !string.IsNullOrEmpty(System.Environment.UserName) ? System.Environment.UserName : string.Empty;
string sqlConnectString = MyConnectionString;
sqlConnection = new SqlConnection(sqlConnectString);
SqlCommand sqlCommand = new SqlCommand("InsertUpdateDeleGeneralConfig", sqlConnection);
sqlCommand.CommandTimeout = MySQLCommandTimeOut;
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.Parameters.AddWithValue("#Action", "INSERT");
sqlCommand.Parameters.AddWithValue("#ID", System.Guid.NewGuid().ToString());
sqlCommand.Parameters.AddWithValue("#Name", Getgencon.Name);
sqlCommand.Parameters.AddWithValue("#Value", Getgencon.Value);
sqlCommand.Parameters.AddWithValue("#updatedBy", user);
sqlCommand.Parameters.AddWithValue("#updatedOn", DateTime.Now);
sqlConnection.Open();
result = sqlCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
DBCall.LogError(ex, "DBPostGeneralConfig");
result = -1;
}
finally
{
if (sqlConnection.State != ConnectionState.Closed)
{
sqlConnection.Close();
}
}
return result;
}
Application Layer
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddNewGeneralConfig(GeneralConfigDets Configval)
{
if (ModelState.IsValid)
{
try
{
ServiceRepositary serviceObj = new ServiceRepositary();
HttpResponseMessage response = serviceObj.PostResponse("api/GeneralConfiguration/AddNewGeneralConfig", Configval);
response.EnsureSuccessStatusCode();
}
catch (Exception)
{
ModelState.AddModelError(string.Empty, "Server error. Please contact administrator.");
}
TempData["Message"] = "Added Successfully";
}
return RedirectToAction("GetGeneralConfig", "GeneralConfig");
}

C# UWP Login form checking credentials in MySQL remote database

I got stuck after couple of hours of research. I'm trying to make a basic Universal Windows App with login form - after clicking a button, credentials in textboxes are checked with remote MySQL database. If valid, app shoud navigate to another specified page. If not, error message is displayed.
I can't find error in my code below. After clicking the button Windows' blue circle spins and after couple of seconds returns to VS2017. No errors and warnings. State.ToString() returns 'Open' so I do have a connection with DB. What I'm doing wrong?
public sealed partial class MainPage : Page
{
const string connString = "server=my_server;pwd=pass;uid=user_id;database=mydb;persistsecurityinfo=True";
MySqlConnection conn = new MySqlConnection(connString);
public MainPage()
{
this.InitializeComponent();
}
private void DbConnection()
{
try
{
conn.Open();
}
catch (MySqlException e)
{
throw;
}
}
private bool DataValidation(string user, string pass)
{
DbConnection();
MySqlCommand cmd = new MySqlCommand("SELECT Username, Password FROM Users WHERE Username=#user AND Password=#pass;");
cmd.Parameters.AddWithValue("#user", user);
cmd.Parameters.AddWithValue("#pass", pass);
cmd.Connection = conn;
MySqlDataReader login = cmd.ExecuteReader();
if (login.Read())
{
conn.Close();
return true;
}
else
{
conn.Close();
return false;
}
}
private void LoginBtn_Click(object sender, RoutedEventArgs e)
{
string user = UserTextBox.Text;
string pass = PassTextBox.Text;
if (user == "" || pass == "")
{
StatusTextBlock.Text = ("No emty fields allowed. Try again...");
return;
}
bool loginSuccessful = DataValidation(user, pass);
if (loginSuccessful)
{
this.Frame.Navigate(typeof(Page2), null);
}
else
{
StatusTextBlock.Text = "Invalid e-mail or password. Try again...";
}
}
}
Complete working solution:
using MySql.Data.MySqlClient;
namespace Project
{
public sealed partial class MainPage : Page
{
const string connString = "server=server_name;user id=uid;pwd=password;persistsecurityinfo=True;database=db_name";
public MainPage()
{
this.InitializeComponent();
}
private bool DataValidation(string user, string pass)
{
using (MySqlConnection conn = new MySqlConnection(connString))
using (MySqlCommand cmd = new MySqlCommand("SELECT " +
"Username, Password " +
"FROM users " +
"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();
if (login.Read())
{
conn.Close();
return true;
}
else
{
conn.Close();
return false;
}
}
}
private void LoginBtn_Click(object sender, RoutedEventArgs e)
{
string user = UserTextBox.Text;
string pass = PassBox.Password;
if (user == "" || pass == "")
{
StatusTextBlock.Text = ("Your text");
return;
}
bool loginSuccessful = DataValidation(user, pass);
if (loginSuccessful)
{
this.Frame.Navigate(typeof(Page2), null);
}
else
{
StatusTextBlock.Text = "Your text";
}
}
}
}

ASP.NET C# Validating username and password

Im trying to validate username and password from an MySql server. Login validation is working, but I can't for the life of me figure out why the "Create new user" validation isn't working.
Here are the code for registering new user. What happens is;
catch (Exception)
{
Label1.Text = "Brukernavnet er allerede i bruk";
}
Seems like this part ^ is ruining it for me somehow, whenever i test run this code I get this message.
protected void newBtn_Click(object sender, EventArgs e)
{
String cs = "Database=trafikkskole; User=user; Password=password";
MySqlConnection dbconnect = new MySqlConnection(cs);
try
{
dbconnect.Open();
cmd.CommandText = "INSERT INTO user (username, password) VALUES (#un, #pw)";
cmd.Parameters.AddWithValue("#un", inputUser.Text);
cmd.Parameters.AddWithValue("#pw", inputPw.Text);
cmd.Connection = dbconnect;
int a = cmd.ExecuteNonQuery();
if (a > 0)
{
Label1.Text = "Gratulerer! Du har nå laget en bruker!";
}
else
{
Label1.Text = "ERROR";
}
}
catch (Exception)
{
Label1.Text = "Brukernavnet er allerede i bruk";
}
finally
{
dbconnect.Close();
}
}
}
EDIT:
If I try it like this:
protected void newBtn_Click(object sender, EventArgs e)
{
String cs = "Database=trafikkskole; User=root; Password=root";
MySqlConnection dbconnect = new MySqlConnection(cs);
String sql = "SELECT * FROM user";
MySqlCommand cmd = new MySqlCommand(sql, dbconnect);
da = new MySqlDataAdapter(cmd);
MySqlCommandBuilder cb = new MySqlCommandBuilder(da);
ds = new DataSet("TEST");
da.Fill(ds, "user");
Response.Write(ds.Tables["user"].Rows.Count);
try
{
dbconnect.Open();
cmd.CommandText = "INSERT INTO user (username, password) VALUES (#un, #pw)";
cmd.Parameters.AddWithValue("#un", inputUser.Text);
cmd.Parameters.AddWithValue("#pw", inputPw.Text);
cmd.Connection = dbconnect;
int a = cmd.ExecuteNonQuery();
if (a > 0)
{
Label1.Text = "Gratulerer! Du har nå laget en bruker!";
}
else
{
Label1.Text = "ERROR";
}
}
catch (Exception Exception)
{
Label1.Text = "Brukernavnet er allerede i bruk";
}
finally
{
dbconnect.Close();
}
}
}
This ends up with the possibility of making a user without username or password.
There are a number of things that could be going wrong. You should examine the exception.message to get insights as to what it could be.
For example, put a break point in the catch statement and see if the exception thrown for things like... does the username already exist and SQL is throwing an error. ... or are the username/password null, too long, etc...
Regardless, change the catch statement to catch(Exception exception) and see what the exception is.
I want to thank everyone for trying, found a working solution, will post it here for future reference.
protected void newBtn_Click(object sender, EventArgs e)
{
String cs = "Database=trafikkskole; User=root; Password=root";
MySqlConnection dbconnect = new MySqlConnection(cs);
try
{
if (!string.IsNullOrWhiteSpace(inputUser.Text) && !string.IsNullOrWhiteSpace(inputPw.Text))
{
dbconnect.Open();
Label1.Text = "Gratulerer! Du har nå laget en bruker!";
string qry = "INSERT INTO user(username, password) VALUES (#un, #pw)";
cmd = new MySqlCommand(qry, dbconnect);
cmd.Parameters.AddWithValue("#un", inputUser.Text);
cmd.Parameters.AddWithValue("#pw", inputPw.Text);
cmd.Connection = dbconnect;
cmd.ExecuteNonQuery();
}
else
{
Label1.Text = "ERROR";
}
}
catch (Exception)
{
Label1.Text = "Brukernavnet er allerede i bruk";
}
finally
{
dbconnect.Close();
}
}

Validate Login Errors

I am using the following C# code for a Login Page but I get an error that says:
"Please make sure that the username and the password is Correct"
protected void btnlogin_Click(object sender, EventArgs e)
{
int Results = 0;
if (txtUsername.Text != string.Empty && txtPassword.Text != string.Empty)
{
Results = Validate_Logon(txtUsername.Text.Trim(), txtPassword.Text.Trim());
if (Results == 1)
{
lblMessage.Text = "Login is Good, Send the User to another page or enable controls";
}
else
{
lblMessage.Text = "Invalid Login";
lblMessage.ForeColor = System.Drawing.Color.Red;
//Dont Give too much information this might tell a hacker what is wrong in the login
}
}
else
{
lblMessage.Text = "Please make sure that the username and the password is Correct";
}
}
public int Validate_Logon(String Username, String Password)
{
SqlConnection con = new SqlConnection(#"***************");
SqlCommand cmdselect = new SqlCommand();
cmdselect.CommandType = CommandType.StoredProcedure;
cmdselect.CommandText = "[dbo].[Log_Members]";
cmdselect.Parameters.Add("#Username", SqlDbType.VarChar, 256).Value = Username;
cmdselect.Parameters.Add("#UPassword", SqlDbType.VarChar, 55).Value = Password;
cmdselect.Parameters.Add("#OutRes", SqlDbType.Int, 4);
cmdselect.Parameters["#OutRes"].Direction = ParameterDirection.Output;
cmdselect.Connection = con;
int Results = 0;
try
{
con.Open();
cmdselect.ExecuteNonQuery();
Results = (int)cmdselect.Parameters["#OutRes"].Value;
}
catch (SqlException ex)
{
lblMessage.Text = ex.Message;
}
finally
{
cmdselect.Dispose();
if (con != null)
{
con.Close();
}
}
return Results;
}
Please I need to know what is wrong with the code above
It is very straightforward:
if (txtUsername.Text != string.Empty && txtPassword.Text != string.Empty)
This line is returning false, so the else executes, which is:
else
{
lblMessage.Text = "Please make sure that the username and the password is Correct";
}
Debug your code.
Well, why don't you check that the you actually entered text into both the username and the password text boxes?

Categories

Resources