Paladine, firstly thanks for the tutorials you've posted here, they seem great, but i'm having trouble getting it to work for me. Hoping you could help.
I'm trying to build a login page, connecting to an SQL server database using C#, so i've mixed up a few of your tutorials to try to achieve this. here is my C# code for the login page, it uses a connection from another C# file rather than your Web.Config suggestion, but i know the connection works as it is used successfully for other code:
private void Submit1_ServerClick(object sender, System.EventArgs e)
{
if(Page.IsValid)
{
if(ValidateUser(usernameTxtBx.Text.Trim(), passwordTxtBx.Text.Trim()))
{
FormsAuthentication.RedirectFromLoginPage (usernameTxtBx.Text, false);
}
else
{
messageLbl.Text = "Invalid Login, please try again!";
}
}
}
private bool ValidateUser(string txtUser, string txtPass)
{
// Connect to Database
DataAccess.DBConnection.GetLoginConnection();
// Access Stored Procedure
SqlCommand cmd = new SqlCommand("proc_ValidateUser", conn);
cmd.CommandType = CommandType.StoredProcedure;
// Create Parameters
SqlParameter objParam1;
SqlParameter objParam2;
SqlParameter returnParam;
objParam1 = cmd.Parameters.Add("@usrName", SqlDbType.NVarChar);
objParam2 = cmd.Parameters.Add("@usrPassword", SqlDbType.NVarChar);
returnParam = cmd.Parameters.Add("@Num_of_User", SqlDbType.Int);
// Set the direction of the parameters
objParam1.Direction = ParameterDirection.Input;
objParam2.Direction = ParameterDirection.Input;
returnParam.Direction = ParameterDirection.ReturnValue;
// Set the values of the parameters
objParam1.Value = txtUser;
objParam2.Value = txtPass;
try
{
if(conn.State.Equals(ConnectionState.Closed))
{
conn.Open();
cmd.ExecuteNonQuery();
}
if((int)returnParam.Value < 1)
{
messageLbl.Text = "Invalid Login!";
return false;
}
else
{
conn.Close();
return true;
}
}
catch (Exception ex)
{
messageLbl.Text = ex + "Error connecting to database!";
return false;
}
finally
{
// Ensures connection has closed
conn.Close();
}
}
Here is my connection code:
public static SqlConnection GetLoginConnection()
{
SqlConnection conn = new SqlConnection("Server=(local);Database=YLCdbSQL;Integrated Security=SSPI");
return conn;
}
Here is my stored procedure code
CREATE PROCEDURE proc_ValidateUser
(@usrName nvarchar(15) = NULL,
@usrPassword nvarchar(15) = NULL,
@Num_of_User int = 0
)
AS
SET @Num_of_User = (SELECT COUNT(*) AS Num_of_User
FROM tblUser
WHERE usrName=@usrName AND usrPassword=@usrPassword)
RETURN @Num_of_User
GO
I have a Default.aspx page created too, and everything builds with no errors.
However, when i go to the login page and type in Username and password, regardless of wheter or not the entries are correct, the login page basically refreshes, leaving the username text box filled, and the password text box blank. No error message is shown in the messageLbl control.
Any ideas what the problem might be?
Thanks again.