ASP.NET C# Validating username and password - c#

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

Related

How to determine the user role that received from database if admin or not

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 !

IndexOutOfRange exception in SqlDataReader in asp.net c#

I am fed up with this error. At the time of login I am authenticating user and then loading some important information in session variables. I hosted my application on IIS and client computers use the application through IP address. Here is my c# code...
protected void btnLogin_Click(object sender, EventArgs e)
{
Session["UserName"] = txtUserName.Text;
string DefaultYear = GetDefaultFinYear();
if (DefaultYear != string.Empty)
{
DefaultYear = "connect" + DefaultYear;
Connections.Init(DefaultYear);
SqlDataAdapter adp = new SqlDataAdapter();
SqlDataReader dr = null;
try
{
adp = new SqlDataAdapter("CheckLogin_sp", Connections.Connection[Session["UserName"].ToString()]);
adp.SelectCommand.Parameters.AddWithValue("#UserName", txtUserName.Text.Trim());
adp.SelectCommand.Parameters.AddWithValue("#Pwd", txtPassword.Text.Trim());
adp.SelectCommand.Parameters.AddWithValue("option", "Authenticate".Trim());
adp.SelectCommand.CommandType = CommandType.StoredProcedure;
if (Connections.Connection[Session["UserName"].ToString()].State == ConnectionState.Closed)
{
Connections.Connection[Session["UserName"].ToString()].Open();
}
dr = adp.SelectCommand.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
Session["Name"] = dr[0].ToString();
Session["CompanyName"] = dr[1].ToString();
Session["UserId"] = dr[2].ToString();
Session["Center"] = dr[3].ToString();
Session["ClientCode"] = dr[4].ToString();
Session["UserImage"] = dr[5].ToString();
Session["CurrentDatabase"] = dr[6].ToString();
Connections.BillReport = dr[7].ToString();
Connections.DuesReport = dr[8].ToString();
Connections.GeneralReport = dr[9].ToString();
Connections.PendingReport = dr[10].ToString();
Connections.RadiologyReport = dr[11].ToString();
Connections.HistoReport = dr[12].ToString();
}
Session["value"] = "admin";
Response.Redirect("~/Masters/home.aspx", false);
}
else
{
MessageBox.Show("Invalid Password");
txtUserName.Text = string.Empty;
}
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
finally
{
Connections.Connection[Session["UserName"].ToString()].Close();
adp.Dispose();
dr.Close();
dr.Dispose();
}
}
else
{
MessageBox.Show("Invalid UserName");
}
}
Not every time this error occurs but sometimes when multiple computers access the application this error comes on following line
Session["Name"] = dr[0].ToString();
Note:- Once this error occurs it resolve only when the server computer restart.
I believe wrapping your code in the stored procedure with a transaction would fix your problem.
BEGIN TRY
BEGIN TRANSACTION CheckLogin
--Existing SQL code
COMMIT TRANSACTION CheckLogin
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION CheckLogin
END CATCH
All stored procedures called from a web application should use transactions.

Using sessions in 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 ?

Handling multiple buttons in same asp.net page

hello everyone i am using two buttons on same asp.net webpage.both contain different codes
first button fetches the data from database here is the code
protected void Button1_Click(object sender, EventArgs e)
{
string username = Request.QueryString["username"];
SqlConnection conn = new SqlConnection("Data Source=ADMIN-PC\\SQLEXPRESS;Initial Catalog=swa1;User Id=swa1;Password=swa1;");
conn.Open();
try
{
string checkaddress = "select address,city,zipcode from regforswa where username=" + username;
SqlCommand com = new SqlCommand(checkaddress, conn);
using (var reader = com.ExecuteReader())
{
while (reader.Read())
{
var tmp = reader["address"];
if (tmp != DBNull.Value)
{
laddress.Visible = true;
laddress.Text = reader["address"].ToString();
}
var cty = reader["city"];
if (cty != DBNull.Value)
{
lcity.Visible = true;
lcity.Text = reader["city"].ToString();
}
var zip = reader["zipcode"];
if (zip != DBNull.Value)
{
lzipcode.Visible = true;
lzipcode.Text = reader["zipcode"].ToString();
}
}
}
}
finally
{
conn.Close();
}
}
second button updates the value in the database using textbox values here is the code
protected void submit_Click(object sender, EventArgs e)
{
string username = Request.QueryString["username"];
string address=TextBox4.Text;
string city=TextBox5.Text;
string zipcode=TextBox6.Text;
SqlConnection conn = new SqlConnection("Data Source=ADMIN-PC\\SQLEXPRESS;Initial Catalog=swa1;User Id=swa1;Password=swa1;");
conn.Open();
try
{
string updateaddress = "UPDATE regforswa SET address=#address,city=#city,zipcode=#zipcode WHERE username="+username;
SqlCommand com = new SqlCommand(updateaddress, conn);
com.Parameters.AddWithValue("#address",address);
com.Parameters.AddWithValue("#city",city);
com.Parameters.AddWithValue("#zipcode",zipcode);
// com.Parameters.AddWithValue("#username",username);
if (com.ExecuteNonQuery() == 1)
{
result.Visible = true;
result.Text = "congradulations.your address has been changed";
}
else
{
result.Visible = true;
result.Text = "sorry please try again";
}
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
finally
{
conn.Close();
}
}
but the problem is when i hit the first button the validation controls related to second button does not allow the page to be reloaded so i can not fetch the data.
my question is can we use two buttons on same webpage but with different functionality to perform?
I think you can use "Validation groups" to fix your problem. http://msdn.microsoft.com/en-us/library/ms227424(v=vs.100).aspx

Use ContentEditable to Save Into DB With ASP.NET?

I'm trying to create a web page where a user can edit the text and when they are done, they hit save and the new text entered is saved into the database.
I'm not getting any errors in my code, but for some reason, the old text is just being rewritten into the db instead of the new text.
Here is my code-behind:
protected void saveBtn_Click(object sender, EventArgs e)
{
string newName;
string newIntro;
string newEduc;
string newWork;
h1New.Text = h1.Text;
newName = h1New.Text;
newIntro = intro.Text;
newEduc = educ.Text;
newWork = employ.Text;
string connectionInfo = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionInfo))
{
connection.Open();
SqlCommand myCommand = new SqlCommand("UPDATE simpleContent SET userName = #newName, infoContent = #newIntro, educContent = #newEduc, workContent = #newWork WHERE userID = #userName", connection);
try
{
string username = HttpContext.Current.User.Identity.Name;
myCommand.Parameters.AddWithValue("#userName", username.ToString());
myCommand.Parameters.AddWithValue("#newName", newName.ToString());
myCommand.Parameters.AddWithValue("#newIntro", newIntro.ToString());
myCommand.Parameters.AddWithValue("#newEduc", newEduc.ToString());
myCommand.Parameters.AddWithValue("#newWork", newWork.ToString());
myCommand.ExecuteNonQuery();
connection.Close();
}
catch
{
Response.Redirect("http://www.google.co.uk");
}
}
}
I would appreciate any pointers that you may have.
try to put you code in format:
protected void saveBtn_Click(object sender, EventArgs e)
{
// add variables
string connectionInfo = (...)
string commandText = (...)
using (...){
SqlCommand myCommand = (...)
// add parameters
try
{
connection.Open();
myCommand.ExecuteNonQuery();
connection.Close();
}
catch (Exception ex)
{
(...)
}
}

Categories

Resources