Asp.net code-behind login errors? - asp.net

I am getting an error when it is determining whether the username is false or not. I am using asp.net in code-behind. It is highlighted below. If someone can tell me what the error is that would be amazing!
protected void Login_Authenticate(object sender, AuthenticateEventArgs e)
{
Boolean blnresult;
blnresult = false;
**blnresult = Authentication(Login.UserName);**
if (blnresult == true)
{
e.Authenticated = true;
Session["Check"] = true;
}
else
e.Authenticated = false;
}
private bool Authentication(TextBox textBox)
{
throw new NotImplementedException();
}
protected static Boolean Authentication(string Username, string Password)
{
string sqlstring;
sqlstring = "SELECT userID FROM import_log.dbo.user_verification WHERE userID =" + Username + "";
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection("Data Source = ietm-fwb-sql1; Initial Catalog = import_log; Persist Security Info = True; User ID = sa; Password = fwbadmin");
System.Data.SqlClient.SqlCommand comm = new System.Data.SqlClient.SqlCommand(sqlstring, con);
System.Data.SqlClient.SqlDataReader reader;
con.Open();
reader = comm.ExecuteReader();
if (reader.Read())
return true;
else
return false;
}
}
}

Related

Using a checkbox to change an existing database value

I currently have a checkbox that remains checked or unchecked based on the value in the database. I want the checkbox to be able to change dynamically, so that if it's checked upon loading the page and I change it to unchecked, it will change the database value as well as redirect to a different page. Right now I am unable to change the database value and redirect to a different page. I have autopost back set to true currently.
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection dataConnection = new SqlConnection(#"Data Source=184.168.47.21;Initial Catalog=RecruitPursuit;Persist Security Info=True;User ID=RecruitPursuit;Password=Recruit20!8"))
using (SqlCommand dataCommand =
new SqlCommand("select SportHasPositions from Sport Where Sport_Id = #Sport_Id", dataConnection))
{
SqlParameter param2 = new SqlParameter();
param2.ParameterName = "#Sport_Id";
param2.Value = Session["SportID"];
dataCommand.Parameters.Add(param2);
dataConnection.Open();
sportHasPositions = dataCommand.ExecuteScalar().ToString();
}
if (sportHasPositions == "No")
{
CheckBox1.Checked = true;
Panel1.Visible = false;
}
if (sportHasPositions == "Yes")
{
CheckBox1.Checked = false;
Panel1.Visible = true;
}
}
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
if (CheckBox1.Checked == false)
{
String conString = #"Data Source=184.168.47.21;Initial Catalog=RecruitPursuit;Persist Security Info=True;User ID=RecruitPursuit;Password=Recruit20!8";
SqlConnection con = new SqlConnection(conString);
//create a command behavior object
String cmdString = "UPDATE Sport SET SportHasPositions = #SportHasPositions WHERE Sport_Id = #Sport_Id";
SqlCommand cmd = new SqlCommand(cmdString, con);
SqlParameter param0 = new SqlParameter();
param0.ParameterName = "#SportHasPositions";
param0.Value = "Yes";
cmd.Parameters.Add(param0);
SqlParameter param1 = new SqlParameter();
param1.ParameterName = "#Sport_Id";
param1.Value = Session["SportID"];
cmd.Parameters.Add(param1);
int added = 0;
try
{
con.Open();
added = cmd.ExecuteNonQuery();
}
catch (Exception err)
{
// Output.Text = err.Message;
}
finally
{
con.Close();
}
Response.Redirect("Pick Positions.aspx");
}
if (CheckBox1.Checked == true)
{
String conString = #"Data Source=184.168.47.21;Initial Catalog=RecruitPursuit;Persist Security Info=True;User ID=RecruitPursuit;Password=Recruit20!8";
SqlConnection con = new SqlConnection(conString);
//create a command behavior object
String cmdString = "UPDATE Sport SET SportHasPositions = #SportHasPositions WHERE Sport_Id = #Sport_Id";
SqlCommand cmd = new SqlCommand(cmdString, con);
SqlParameter param0 = new SqlParameter();
param0.ParameterName = "#SportHasPositions";
param0.Value = "No";
cmd.Parameters.Add(param0);
SqlParameter param1 = new SqlParameter();
param1.ParameterName = "#Sport_Id";
param1.Value = Session["SportID"];
cmd.Parameters.Add(param1);
int added = 0;
try
{
con.Open();
added = cmd.ExecuteNonQuery();
}
catch (Exception err)
{
// Output.Text = err.Message;
}
finally
{
con.Close();
}
}
}
The problem is that the asp.net life cycle runs the Page_Load event before the CheckBox1_CheckedChanged event. Since in your Page_Load, you are setting the checkbox, even if the user changed it, the Page_Load changes it back before the CheckBox1_CheckedChanged can change it in the database. To fix this you can use the Page.IsPostBack
flag so the Page_Load only sets the Checkbox on the initial page load.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack) {
using (SqlConnection dataConnection = new SqlConnection(#"Data Source=184.168.47.21;Initial Catalog=RecruitPursuit;Persist Security Info=True;User ID=RecruitPursuit;Password=Recruit20!8"))
using (SqlCommand dataCommand =
new SqlCommand("select SportHasPositions from Sport Where Sport_Id = #Sport_Id", dataConnection))
{
SqlParameter param2 = new SqlParameter();
param2.ParameterName = "#Sport_Id";
param2.Value = Session["SportID"];
dataCommand.Parameters.Add(param2);
dataConnection.Open();
sportHasPositions = dataCommand.ExecuteScalar().ToString();
}
if (sportHasPositions == "No")
{
CheckBox1.Checked = true;
Panel1.Visible = false;
}
if (sportHasPositions == "Yes")
{
CheckBox1.Checked = false;
Panel1.Visible = true;
}
}
}

Restricting user access in asp.net

I am working on asp.net application. I want only logged in users to access the Game page. When the users log in, the id and pass are authenticated from the SQL then they are logged in. and I want the logged in users to have an access to Games.aspx.
Here is the login code,
public partial class Login : System.Web.UI.Page
{
//"Data Source=MUNIZA\\SQLEXPRESS;Initial Catalog=LD_Server;Integrated Security=True";
protected void Page_Load(object sender, EventArgs e)
{
lbInfo.Enabled = false;
}
public bool IsAuthenticated
{
get { return Convert.ToBoolean(Session["sIsAuthenticated"] ?? false); }
set { Session["sIsAuthenticated"] = value; }
}
protected void Button1_Click(object sender, EventArgs e)
{
string strcon = "Data Source=MUNIZA\\SQLEXPRESS;Initial Catalog=LD_Server;Integrated Security=True";
SqlConnection con = new SqlConnection(strcon);
SqlCommand com = new SqlCommand("spStudentProfile", con);
com.CommandType = CommandType.StoredProcedure;
SqlParameter p1 = new SqlParameter("RegNo", TextBox2.Text);
SqlParameter p2 = new SqlParameter("Password", TextBox1.Text);
com.Parameters.Add(p1);
com.Parameters.Add(p2);
con.Open();
SqlDataReader rd = com.ExecuteReader();
if (rd.HasRows)
{
IsAuthenticated = true;
rd.Read();
Response.Redirect("~/Games.aspx");
}
else
{
IsAuthenticated = false;
lbInfo.Enabled = true;
lbInfo.Text = "Invalid username or password.";
}
}
It is the login code on every page,
<%
string url = "~/Login.aspx", text = "Log in";
if (Convert.ToBoolean(Session["sIsAuthenticated"] ?? false))
{ url = "~/Home.aspx"; text = "Log out"; }
%>
<%: text %>
</div>

using Session for creating login for mutiple users has error and further which can evaluate the rights of users

I have tried many things but its just showing error "Object reference not set to an instance of an object."
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
else if (Session["StudId"] != null)
{
Label1.Text = Session["StudId"].ToString();
}
I have written this code in my login page dragging all the required databases strings i.e. typeid,students,faculty,admin and accemployee in the page.
public partial class Login : System.Web.UI.Page
{private string strcon = WebConfigurationManager.ConnectionStrings["StudentConnectionString1"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Request.Cookies["UName"] != null)
TextBox1.Text = Request.Cookies["UName"].Value;
if (Request.Cookies["PWD"] != null)
TextBox2.Attributes["value"] = Request.Cookies["PWD"].Value;
if (Request.Cookies["UName"] != null && Request.Cookies["PWD"] != null)
CheckBox1.Checked = true;
}
}
protected void Button1_Click1(object sender, EventArgs e)
{
if (DropDownList1.SelectedItem.Value == "1")
{
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("Select StudFirstName from Student where StudId=#sid and Password=#pw", con);
cmd.Parameters.AddWithValue("#sid", TextBox1.Text);
cmd.Parameters.AddWithValue("#pw", TextBox2.Text);
con.Open();
string name = Convert.ToString(cmd.ExecuteScalar());
con.Close();
if (String.IsNullOrEmpty(name))
Label1.Text = "Sorry! Invalid User ID or Password!";
else
{
if (CheckBox1.Checked)
{
Response.Cookies["UName"].Value = TextBox1.Text;
Response.Cookies["PWD"].Value = TextBox2.Text;
Response.Cookies["UName"].Expires = DateTime.Now.AddMonths(2);
Response.Cookies["PWD"].Expires = DateTime.Now.AddMonths(2);
}
Session.Add("StudId", TextBox1.Text);
Session.Add("StudFirstName", name);
Session.Add("Password", TextBox2.Text);
FormsAuthentication.RedirectFromLoginPage(name, false);
}
}
else if (DropDownList1.SelectedItem.Value == "2")
{
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("Select FacultyFirstName from Faculty where FacultyId=#fid and Password=#pw", con);
cmd.Parameters.AddWithValue("#fid", TextBox1.Text);
cmd.Parameters.AddWithValue("#pw", TextBox2.Text);
con.Open();
string name = Convert.ToString(cmd.ExecuteScalar());
con.Close();
if (String.IsNullOrEmpty(name))
Label1.Text = "Sorry! Invalid User ID or Password!";
else
{
if (CheckBox1.Checked)
{
Response.Cookies["UName"].Value = TextBox1.Text;
Response.Cookies["PWD"].Value = TextBox2.Text;
Response.Cookies["UName"].Expires = DateTime.Now.AddMonths(2);
Response.Cookies["PWD"].Expires = DateTime.Now.AddMonths(2);
}
Session["FacultyId"] = TextBox1.Text;
Session.Add("FacultyFisrtName", name);
Session["Password"] = TextBox2.Text;
FormsAuthentication.RedirectFromLoginPage(name, false);
}
}
else if (DropDownList1.SelectedItem.Value == "3")
{
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("Select AccEmployeeName from AccEmployee where AccEmployeeId=#aid and Password=#pw", con);
cmd.Parameters.AddWithValue("#aid", TextBox1.Text);
cmd.Parameters.AddWithValue("#pw", TextBox2.Text);
con.Open();
string name = Convert.ToString(cmd.ExecuteScalar());
con.Close();
if (String.IsNullOrEmpty(name))
Label1.Text = "Sorry! Invalid User ID or Password!";
else
{
if (CheckBox1.Checked)
{
Response.Cookies["UName"].Value = TextBox1.Text;
Response.Cookies["PWD"].Value = TextBox2.Text;
Response.Cookies["UName"].Expires = DateTime.Now.AddMonths(2);
Response.Cookies["PWD"].Expires = DateTime.Now.AddMonths(2);
}
Session["AccEmployeeFacultyId"] = TextBox1.Text;
Session.Add("AccEmployeeName", name);
Session["Password"] = TextBox2.Text;
FormsAuthentication.RedirectFromLoginPage(name, false);
}
}
else if (DropDownList1.SelectedItem.Value == "4")
{
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("Select from Admin where AdminId=#pid and Password=#pw", con);
cmd.Parameters.AddWithValue("#pid", TextBox1.Text);
cmd.Parameters.AddWithValue("#pw", TextBox2.Text);
con.Open();
string name = Convert.ToString(cmd.ExecuteScalar());
con.Close();
if (String.IsNullOrEmpty(name))
Label1.Text = "Sorry! Invalid User ID or Password!";
else
{
if (CheckBox1.Checked)
{
Response.Cookies["UName"].Value = TextBox1.Text;
Response.Cookies["PWD"].Value = TextBox2.Text;
Response.Cookies["UName"].Expires = DateTime.Now.AddMonths(2);
Response.Cookies["PWD"].Expires = DateTime.Now.AddMonths(2);
}
string adminName = "Pujan";
Session["AdminId"]=TextBox1.Text;
Session["AdminName"] = adminName;
Session["Password"]=TextBox2.Text;
FormsAuthentication.RedirectFromLoginPage(name, false);
}
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Label2.Text = DropDownList1.SelectedItem.Text;
}
`
}
.....................................................................................
Now the error occurs in the masterpage.master.cs which is shown below....
public partial class MasterPage : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["StudId"] == null)
Response.Redirect("Login.aspx");
else if (Session["StudId"] != null)
{
Label1.Text = Session["StudId"].ToString();
}
else if (Session["FacultyFirstName"] == null)
{
Response.Redirect("Login.aspx");
}
else if (Session["FacultyFirstName"] != null)
{
Label1.Text = Session["FacultyFirstName"].ToString();
}
else if (Session["AccEmployeeName"] == null)
{
Response.Redirect("Login.aspx");
}
else if (Session["AccEmployeeName"] != null)
{
Label1.Text = Session["AccEmployeeName"].ToString();
}
else if (Session["AdminName"] == null)
{
Response.Redirect("Login.aspx");
}
else if (Session["AdminName"] != null)
{
Label1.Text = Session["AdminName"].ToString();
}
}
protected void LinkButton1_Click1(object sender, EventArgs e)
{
FormsAuthentication.SignOut();
Response.Redirect("Login.aspx");
}
}
Please suggest me how to get rid of the error in session or wateva it is......Thank you in advance :)
System.NullReferenceException: Object reference not set to an instance of an object.
This error means that the value that is being provided is a null and the Server cannot use it for a process, that requires a parameter to work on.
Sometimes this happens when you're trying to use a variable in a method, and the variable gets a null value. Null value means that there is no value or no data for this thing.
In your code I guess that this error would generate when the site is first loading. At that time, there is no Session for the Server to load or work on. Thus the values are all null throwing this Null exception.
You can try to cover up the code inside an if else block to check whether there is a cookie present for the Session, or try out a try catch block to minimize this exception and do the work depending on the condition.
An example would be:
try {
/* your code here */
} catch (System.NullReferenceException) {
/* create a session or fill up the variable */
}
This block would run the code of yours, and if the exception provided inside the Catch method gets thrown it would execute the code inside the catch block.
Second thing was to use if else:
if(variable != null) {
/* your code here */
} else {
/* set the value */
}
You just check for the value of that particular variable, and check it. If its a null valued variable, then you can skip the execution of the code block and fill the variable with a value and then come back to the current space and re-execute it.
For exception details: http://msdn.microsoft.com/en-us/library/system.nullreferenceexception(v=vs.110).aspx

Session disappears on return to home page

I have a web site running on Azure where a user can login then navigate to other pages (naturally). My problem is that when I return to the Index/Homepage the session just disappears. I thought it my have something to do with the login control and its authentication method in the code behind but I tried putting another login on another page with the same authenticate event but that is completely fine.
I haven't found anyone with a similar problem.
here is the code behind for index.aspx
string Connection = ConfigurationManager.ConnectionStrings["****"].ConnectionString;
protected void Page_Load(object sender, EventArgs e) {}
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e) {
string Username = Login1.UserName;
string pwd = Login1.Password;
SqlConnection connection = new SqlConnection(Connection);
connection.Open();
//SqlCommand comm = new SqlCommand("SELECT COUNT([*****], [*****]) FROM ***** WHERE [****] = '***' AND [****] = '****'", connection);
string sqlUserName = "SELECT [****] ,[****] FROM ***** WHERE [*****] ='" + * * * * * +"' AND [*****] ='" + * * * +"'";
SqlCommand cmd = new SqlCommand(sqlUserName, connection);
string CurrentName;
CurrentName = (string) cmd.ExecuteScalar();
if(CurrentName != null) {
Login1.FailureText = "Welcome";
Session["User"] = Username;
Session["LoggedIn"] = true;
Label1.Text = Session["User"].ToString();
if((bool) Session["LoggedIn"] == true && Session["User"].ToString() == "admin1") {
HyperLink3.Visible = true;
} else if((bool) Session["LoggedIn"] == true) {
HyperLink1.Visible = true;
}
} else {
Session["User"] = "";
}
}
}
Your if statement must be bugging out somewhere, or CurrentName is null.
if (CurrentName != null)
{
Login1.FailureText = "Welcome";
Session["User"] = Username;
Session["LoggedIn"] = true ;
Label1.Text = Session["User"].ToString();
if ((bool)Session["LoggedIn"] == true && Session["User"].ToString() == "admin1")
{
HyperLink3.Visible = true;
}
else if ((bool)Session["LoggedIn"] == true)
{
HyperLink1.Visible = true;
}
}
else
{
Session["User"] = "";
}
The most likely culprit is the preceding SQL query. Double check your syntax with the SQL query. I'm not sure what the asterisk variables are you have combined in there, but they could be causing an issue. You should proceed with line-by-line debugging of that script. Catch it mid-way through and check the value of CurrentName.

Login validation and redirection

I am trying to implement a Login validation using C# 2005 in ASP.net 2.0 web application. The SQL Server database contains a table named "UserList" with columns LoginId, Password and Role. The Login webform should authenticate the LoginId and password and depending upon the Role assigned to that user/visitor should redirect to a specific webform with a pre-defined menu options. The role might be Admin, DEO, Accounts or Member. How should I implement it? I have tried the following:
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
try
{
string uname = Login1.UserName.Trim();
string password = Login1.Password.Trim();
int flag = AuthenticateUser(uname, password);
if (flag == 1)
{
e.Authenticated = true;
Login1.DestinationPageUrl = "~/MenuAdmin.aspx";
}
else if (flag == 2)
{
e.Authenticated = true;
Login1.DestinationPageUrl = "~/MenuDEO.aspx";
}
else if (flag == 3)
{
e.Authenticated = true;
Login1.DestinationPageUrl = "~/MenuAccts.aspx";
}
else if (flag == 4)
{
e.Authenticated = true;
Login1.DestinationPageUrl = "~/MenuMember.aspx";
}
else
{
e.Authenticated = false;
}
}
catch (Exception)
{
e.Authenticated = false;
}
}
private int AuthenticateUser(string uname, string password)
{
int bflag = 0;
string connString = ConfigurationManager.ConnectionStrings["LoginDemoConnString"].ConnectionString;
string strSQL = "Select * FROM UserList where ULoginId ='" + uname + "' AND UPassword ='" + password + "'";
DataTable dt = new DataTable();
SqlConnection m_conn;
SqlDataAdapter m_dataAdapter;
try
{
m_conn = new SqlConnection(connString);
m_conn.Open();
m_dataAdapter = new SqlDataAdapter(strSQL, m_conn);
m_dataAdapter.Fill(dt);
m_conn.Close();
}
catch (Exception ex)
{
dt = null;
}
finally
{
//m_conn.Close();
}
if (dt.Rows.Count > 0)
{
if (dt.Rows[0][3].ToString() == "Administrator")
bflag = 1;
else if (dt.Rows[0][3].ToString() == "DEO")
bflag = 2;
else if (dt.Rows[0][3].ToString() == "Accts")
bflag = 3;
else
bflag = 4;
}
return bflag;
}
Well first of all I guess each role in the sql table has id so you can get rid of the ifs in the AuthenticateUser and just return the id. Or you can also return the actual role and just do something with this data in the Login1_Authenticate function.
Now you can also get rid of the ifs in the Login1_Authenticate function if you will use dictionary where the key is role and value is pageURL so you can just write something like that:
int flag = AuthenticateUser();
Login1.DestinationPageUrl = roles.ElementAt(flag).Value;

Resources