Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1009
  • Last Modified:

How to destroy Session data

Hello Experts,

I have an application that creates three sessoins once an employee successfully logs into my application. I have a LinkButton with code that logs an employee out once he/she has finished on the site. But for some reason if an employee clicks on the log out link they are redirected back to the login page which fine but if they navigate somewhere else on the page it will still display the session values. How can I completely remove them so that if a user clicks around after they logout the sessions will no longer be displayed?

Logout Code:

    protected void lb_logout_Click(object sender, EventArgs e)
    {
        Session.Abandon();
        Session.Clear();
        Session["empid"] = null;
        Session["fname"] = null;
        Session["lname"] = null;
        Response.Redirect("../application/index.aspx");
    }

I have also just tried the following below with no luck.

    protected void lb_logout_Click(object sender, EventArgs e)
    {
        Session.Abandon();
        Response.Redirect("../application/index.aspx");
    }
0
asp_net2
Asked:
asp_net2
  • 20
  • 8
  • 6
  • +1
1 Solution
 
Christopher KileCommented:
I don't understand the part where your application "creates three sessions."  Do you mean it creates three session variables?

Also, is your session in-memory or is it persisted to another medium such as a file or SQL Server?
0
 
asp_net2Author Commented:
Hi cpkilekofp,

Sorry, I did not include that part. I have the following piece of code that is used on every page. This piece of code will retrieve users information if they login to the system. This is how I'm getting the session values.

protected void EmployeeLoginInfo()
    {
        string emp_username = HttpContext.Current.User.Identity.Name;

        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["WellnessTracker"].ConnectionString);

        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "RetrieveEmployeeLoginInfo";
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Connection = conn;

        cmd.Parameters.Add("@emp_username", SqlDbType.VarChar, 50).Value = emp_username;

        DataTable dtEmployeeInfo = new DataTable();
        SqlDataAdapter adp = new SqlDataAdapter();

        try
        {
            conn.Open();

            adp.SelectCommand = cmd;
            adp.Fill(dtEmployeeInfo);

            if (dtEmployeeInfo != null)
            {
                DataRow data = dtEmployeeInfo.Rows[0];

                Session["fname"] = data["emp_firstname"].ToString();
                Session["lname"] = data["emp_lastname"].ToString();
                Session["empid"] = data["emp_id"].ToString();
            }
        }

        catch (Exception ex)
        {
            ex.Message.ToString();
        }

        finally
        {
            conn.Close();
        }
    }
0
 
Christopher KileCommented:
You said you are using this code on "every page", correct?  You should only be using this code on your login page.
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
asp_net2Author Commented:
Why, I have this code running on all pages only becuase I need to display the "Hello, Guest" and I need to hide the LinkButton control if a user has not logged in yet.

If a user logs in then I need to display Hello, First Name and Last Name along with the LinkButton "logout" control.

The session only gets created when users logs in. But the user may still be able to access other pages and if so I need to display their name if they are logged in. If not then display "Hello, Guest" which is what I have now.

The problem that I face is that when a user logs out from clicking on the LinkButton control if removes the session value but if you click to the other pages or hit the back button it still displays the login name when it should not.
0
 
Christopher KileCommented:
You have the whole code for looking up the user name from the database in every page?  Not just "check the session for session variables name first name, last name and emp. id"?
0
 
asp_net2Author Commented:
Yes, every page has the following code below and it gets called in the Page_Load. Is that a bad thing?


protected void EmployeeLoginInfo()
    {
        string emp_username = HttpContext.Current.User.Identity.Name;

        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["WellnessTracker"].ConnectionString);

        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "RetrieveEmployeeLoginInfo";
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Connection = conn;

        cmd.Parameters.Add("@emp_username", SqlDbType.VarChar, 50).Value = emp_username;

        DataTable dtEmployeeInfo = new DataTable();
        SqlDataAdapter adp = new SqlDataAdapter();

        try
        {
            conn.Open();

            adp.SelectCommand = cmd;
            adp.Fill(dtEmployeeInfo);

            if (dtEmployeeInfo != null)
            {
                DataRow data = dtEmployeeInfo.Rows[0];

                Session["fname"] = data["emp_firstname"].ToString();
                Session["lname"] = data["emp_lastname"].ToString();
                Session["empid"] = data["emp_id"].ToString();
            }
        }

        catch (Exception ex)
        {
            ex.Message.ToString();
        }

        finally
        {
            conn.Close();
        }
    }
0
 
Christopher KileCommented:
Yes, it is.   Your Session is the object that is supposed to carry these values from screen to screen.  Since you're reinitilizing these Session variables every time you enter a screen, your logout code to clear out the Session is useless as this code recreates those values instantly.  Eliminate this function from every location except your login form itself.
0
 
asp_net2Author Commented:
Ok, just so I understand I need to remove the EmployeeLoginInfo() method from all pages except for the login page?

Now how do I check if the session values exist on the index.aspx, info.aspx, contact.aspx pages. If the session values exist then display "Hello, First Name + Last Name" along with enabling the LinkButton to give user ability to logout. If the session values DO NOT exist then only display "Hello, Guest"?
0
 
asp_net2Author Commented:
The following code below is what I was using to determine if the values existed or not in Page_Load. But I thought that I need to call the EmployeeLoginInfo() method first to retrieve the data. I appeciate your help, this is the last step that I need to fix before I have this application finished.

        if ((Session["empid"] == null) || (Session["empid"].ToString() == ""))
        {
            lblFullNameSession.Text = "Hello, Guest";
            lb_logout.Visible = false;
        }
        else
        {
            string FirstName = Convert.ToString(Session["fname"]);
            string LastName = Convert.ToString(Session["lname"]);
            string EmpID = Convert.ToString(Session["empid"]);

            lblFullNameSession.Text = "Hello, " + FirstName + " " + LastName;
            lb_logout.Visible = true;
        }
0
 
Christopher KileCommented:
That is exactly how I do it in my own web applications.  Good luck.
0
 
asp_net2Author Commented:
Ok, so I only need to call the EmployeeLoginInfo() Event one time at the Login screen?
0
 
Christopher KileCommented:
Correct.  Once that's done, your logout code (either version) should work as you expected.
0
 
Jesus RodriguezIT ManagerCommented:
And also use Session.RemoveAll()
0
 
Christopher KileCommented:
If you use Session.Abandon(), you don't need Session.RemoveAll():

http://forums.asp.net/t/766816.aspx
0
 
asp_net2Author Commented:
@cpkilekofp / @k-designers,

Ok, not sure what I'm doing wrong but I tried your solution cpkilekofp in regards to removing the Event EmployeeLoginInfo() from all pages except for the login page and I also tried to add the following to my LogOut Event code but if I logout and navigate to the home, contact, and information pages I can still see my first and last name even though I got rid of the EmployeeLoginInfo() Event code. Please see my updated Page_Load and LogOut code for the home, contact, and information pages, they are all the same.

I'm also going to include my login code which does call the EmployeeLoginInfo() code.

Login CodeBehind:

protected void Page_Load(object sender, EventArgs e)
    {
        lblLoginError.Visible = false;

        EmployeeLoginInfo();

        string FirstName = Convert.ToString(Session["fname"]);
        string LastName = Convert.ToString(Session["lname"]);
        string EmpID = Convert.ToString(Session["empid"]);

        if (Session["empid"] != DBNull.Value)
        {
            lblFullNameSession.Text = "Hello, " + "Guest";
            lb_logout.Visible = false;
        }
        else
        {
            lblFullNameSession.Text = "Hello, " + FirstName + " " + LastName;
        }
    }

    protected void EmployeeLoginInfo()
    {
        string emp_username = HttpContext.Current.User.Identity.Name;

        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["WellnessTracker"].ConnectionString);

        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "RetrieveEmployeeLoginInfo";
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Connection = conn;

        cmd.Parameters.Add("@emp_username", SqlDbType.VarChar, 50).Value = emp_username;

        DataTable dtEmployeeInfo = new DataTable();
        SqlDataAdapter adp = new SqlDataAdapter();

        try
        {
            conn.Open();

            adp.SelectCommand = cmd;
            adp.Fill(dtEmployeeInfo);

            if (dtEmployeeInfo != null)
            {
                DataRow data = dtEmployeeInfo.Rows[0];

                Session["fname"] = data["emp_firstname"].ToString();
                Session["lname"] = data["emp_lastname"].ToString();
                Session["empid"] = data["emp_id"].ToString();
            }
        }

        catch (Exception ex)
        {
            ex.Message.ToString();
        }

        finally
        {
            conn.Close();
        }
    }

    protected override void Render(HtmlTextWriter writer)
    {
        ClientScript.RegisterOnSubmitStatement(this.GetType(), "DisableButton", "$('#btn_login').attr('disabled', 'disabled')");
        base.Render(writer);
    }

    // Method to check your user credentials.
    private bool IsValidPassword(string userName, string password)
    {
        byte[] correctHash = null;
        using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["WellnessTracker"].ConnectionString))
        {
            SqlCommand cm = new SqlCommand("[dbo].[GetEmployeePassword]", conn);
            cm.CommandType = CommandType.StoredProcedure;
            cm.Parameters.Add("@emp_username", SqlDbType.VarChar, 50).Value = userName;
            conn.Open();
            correctHash = cm.ExecuteScalar() as byte[];
        }

        if (correctHash == null)
        {
            // User not found.
            return false;
        }
        else
        {
            return PasswordHash.ValidatePassword(password, correctHash);
        }
    }

    protected void btn_login_Click(object sender, EventArgs e)
    {
        if (IsValidPassword(txtUserName.Text, txtPassword.Text))
        {
            Session["UserNameSessionID"] = txtUserName.Text;
            FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, false);
        }
        else
        {
            lblLoginError.Visible = true;
            lblLoginError.Text = "Invalid Credentials!";
        }
    }

    protected void lb_logout_Click(object sender, EventArgs e)
    {
        Session.RemoveAll();
        Session.Abandon();
        Response.Redirect("index.aspx");
    }





Page_Load code for home, contact, and information pages:

    protected void Page_Load(object sender, EventArgs e)
    {
        if ((Session["empid"] == null) || (Session["empid"].ToString() == ""))
        {
            lblFullNameSession.Text = "Hello, Guest";
            lb_logout.Visible = false;
        }
        else
        {
            string FirstName = Convert.ToString(Session["fname"]);
            string LastName = Convert.ToString(Session["lname"]);
            string EmpID = Convert.ToString(Session["empid"]);

            lblFullNameSession.Text = "Hello, " + FirstName + " " + LastName;
            lb_logout.Visible = true;
        }
}





LogOut Code:

    protected void lb_logout_Click(object sender, EventArgs e)
    {
        Session.Abandon();
        Session.RemoveAll();
        Session["empid"] = null;
        Response.Redirect("application/index.aspx");
    }
0
 
asp_net2Author Commented:
@cpkilekofp / @k-designers,

Hello Experts, any ideas how I can remove those session values? Am I doing something wrong in the code I supplied above?
0
 
Jesus RodriguezIT ManagerCommented:
Ok.. Seems like you get a little lost with the code. Let's try this.

On Clik button for Login put this code:
  {
        string emp_username = HttpContext.Current.User.Identity.Name;

        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["WellnessTracker"].ConnectionString);

        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "RetrieveEmployeeLoginInfo";
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Connection = conn;

        cmd.Parameters.Add("@emp_username", SqlDbType.VarChar, 50).Value = emp_username;

        DataTable dtEmployeeInfo = new DataTable();
        SqlDataAdapter adp = new SqlDataAdapter();

        try
        {
            conn.Open();

            adp.SelectCommand = cmd;
            adp.Fill(dtEmployeeInfo);

            if (dtEmployeeInfo != null)
            {
                DataRow data = dtEmployeeInfo.Rows[0];

                Session["fname"] = data["emp_firstname"].ToString();
                Session["lname"] = data["emp_lastname"].ToString();
                Session["empid"] = data["emp_id"].ToString();
            }
        }

        catch (Exception ex)
        {
            ex.Message.ToString();
        }

        finally
        {
            conn.Close();
        }
    }


Then On Each page Load put this One

{
        if ((Session["empid"] == null) || (Session["empid"].ToString() == ""))
        {
            lblFullNameSession.Text = "Hello, Guest";
            lb_logout.Visible = false;
        }
        else
        {
            string FirstName = Convert.ToString(Session["fname"]);
            string LastName = Convert.ToString(Session["lname"]);
            string EmpID = Convert.ToString(Session["empid"]);

            lblFullNameSession.Text = "Hello, " + FirstName + " " + LastName;
            lb_logout.Visible = true;
        }
}

If you wnat to redirect some pages in case that the user are not authorize then add the redirect code on this section

 if ((Session["empid"] == null) || (Session["empid"].ToString() == ""))
        {
            lblFullNameSession.Text = "Hello, Guest";
            lb_logout.Visible = false;
            Response.redirect('MyLoginPage.aspx')

Are you working with Maser Pages??
0
 
asp_net2Author Commented:
@k-designers,

I don't think I'm lost with the code. I have tried what you are explaining but it still holds the values if I navigate to other pages. Please see my Login code below. It appears that I'm creating a Session called "UserNameSessionID" and maybe that is what I have to use instead of "empid".

Login CodeBehind:

protected void Page_Load(object sender, EventArgs e)
    {
        lblLoginError.Visible = false;

        EmployeeLoginInfo();

        string FirstName = Convert.ToString(Session["fname"]);
        string LastName = Convert.ToString(Session["lname"]);
        string EmpID = Convert.ToString(Session["empid"]);

        if (Session["empid"] != DBNull.Value)
        {
            lblFullNameSession.Text = "Hello, " + "Guest";
            lb_logout.Visible = false;
        }
        else
        {
            lblFullNameSession.Text = "Hello, " + FirstName + " " + LastName;
        }
    }

    protected void EmployeeLoginInfo()
    {
        string emp_username = HttpContext.Current.User.Identity.Name;

        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["WellnessTracker"].ConnectionString);

        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "RetrieveEmployeeLoginInfo";
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Connection = conn;

        cmd.Parameters.Add("@emp_username", SqlDbType.VarChar, 50).Value = emp_username;

        DataTable dtEmployeeInfo = new DataTable();
        SqlDataAdapter adp = new SqlDataAdapter();

        try
        {
            conn.Open();

            adp.SelectCommand = cmd;
            adp.Fill(dtEmployeeInfo);

            if (dtEmployeeInfo != null)
            {
                DataRow data = dtEmployeeInfo.Rows[0];

                Session["fname"] = data["emp_firstname"].ToString();
                Session["lname"] = data["emp_lastname"].ToString();
                Session["empid"] = data["emp_id"].ToString();
            }
        }

        catch (Exception ex)
        {
            ex.Message.ToString();
        }

        finally
        {
            conn.Close();
        }
    }

    protected override void Render(HtmlTextWriter writer)
    {
        ClientScript.RegisterOnSubmitStatement(this.GetType(), "DisableButton", "$('#btn_login').attr('disabled', 'disabled')");
        base.Render(writer);
    }

    // Method to check your user credentials.
    private bool IsValidPassword(string userName, string password)
    {
        byte[] correctHash = null;
        using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["WellnessTracker"].ConnectionString))
        {
            SqlCommand cm = new SqlCommand("[dbo].[GetEmployeePassword]", conn);
            cm.CommandType = CommandType.StoredProcedure;
            cm.Parameters.Add("@emp_username", SqlDbType.VarChar, 50).Value = userName;
            conn.Open();
            correctHash = cm.ExecuteScalar() as byte[];
        }

        if (correctHash == null)
        {
            // User not found.
            return false;
        }
        else
        {
            return PasswordHash.ValidatePassword(password, correctHash);
        }
    }

    protected void btn_login_Click(object sender, EventArgs e)
    {
        if (IsValidPassword(txtUserName.Text, txtPassword.Text))
        {
            Session["UserNameSessionID"] = txtUserName.Text;
            FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, false);
        }
        else
        {
            lblLoginError.Visible = true;
            lblLoginError.Text = "Invalid Credentials!";
        }
    }

    protected void lb_logout_Click(object sender, EventArgs e)
    {
        Session.Abandon();
        Response.Redirect("index.aspx");
    }
0
 
asp_net2Author Commented:
Also, the code you are referring to above is the code for the EmployeeLogin() method and not for the login code. I never posted the Login code until now.
0
 
StephanLead Software EngineerCommented:
It is simple. On every page load you create your session when logged in or loggig in. Before th onclick event is raised. The pageload is hit. And your logout removes only the session. Not the authentication cookie e.g. Where your usename comes from. (httpcontext.current.user.identity.name)

Use formsauthentication.signout() to remove it when hitting logout (event). Also remove the session creation from rhe page load and move it to the method that validates the credentials.
0
 
asp_net2Author Commented:
@stephanonline,

Can you show me what I need based on the code I supplied?
0
 
StephanLead Software EngineerCommented:
I am on a mobile atm so bare with me to try:

Add the following line to your lb_logout_Click

FormsAuthentication.SignOut();

Move the EmployeeLoginInfo() from the page load into the btn_login_click when auhentication is OK. Maybe rewrite th EmployeeLoginInfo to accept a parameter username since you know this at that moment.
0
 
asp_net2Author Commented:
@stephanonline,

Not sure how you want me to do what your saying or even why. Can you explain why I need to use FormsAuthentication.SignOut() rather than Session.Abandon() instead?

Also, I believe I fixed this issue by adding the following code to ever page's Page_Load Event. Tell me what you think. The page in the response.redirect is the login page.

string FirstName = Convert.ToString(Session["fname"]);
        string LastName = Convert.ToString(Session["lname"]);
        string EmpID = Convert.ToString(Session["empid"]);

        lblFullNameSession.Text = "Hello, " + FirstName + " " + LastName;
        hf_emp_id.Value = EmpID;

        if ((Session["UserNameSessionID"] == null) || (Session["UserNameSessionID"].ToString() == ""))
        {
            Response.Redirect("../index.aspx");
        }
0
 
asp_net2Author Commented:
@stephanonline,

Also, I appreciate your help and replys and I'm not trying to second guess what you are telling me it's just hard for me to grasp compared to the other stuff people have been telling me to do. So if you can explain to me the reason behind your solution it will help me to understand what you mean.
0
 
StephanLead Software EngineerCommented:
ASP.NET has by default FormsAuthentication, and inside your code of the btn_login_click event, you are firing FormsAuthentication.RedirectFromLoginPage(txtUsername.Text, true);

This is setting the formsauthentication cookie. This cookie is used for the formsauthentication that ASP.NET uses.

That's how you can use HttpContext.Current.User.Identity.Name.
In order to remove this cookie you can use FormsAuthentication.SignOut();

You can also validate if a user is logged in using HttpContext.Current.User.Identity.IsAuthenticated
Another way is using <location path="index.aspx"><system.web><authorization><deny users="?" /></authorization></system.web></location> to prevent access to unauthenticated users (in the web.config). ASP.NET handles the rest, it redirects you to the login page you have defined in the web.config and gives the returnurl in the querystring in order to return the user when whe needed authentication.

You can look here for more depth:
http://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication.aspx
(this is also asked for certification on asp.net ;-) )

This cleans up your code and don't have to do every check on the page you need, just add to the web.config.. So much easier.

When you want to set a session when you have authenticated, the best place is when the authentication has taken place.
0
 
asp_net2Author Commented:
@stephanonline,

Ok, I did try your technique but had problems with other pages still retrieving the Session data "FirstName", "LastName", and "EmpID" on other pages once I logged out.

Each page include the following code below on every page's Page_Load as so far this technique has worked fine. I just implemented it on every page and have had no problems.

As you can see I when I run the LogOut code it kills the "UserNameSessionID" Session value. But if I place the session value "empid" instead of "UserNameSessionID" then the code below does not work and it will show the FirstName, LastName, and EmpID values on every page's Page_Load. I also have the EmployeeInfo() method removed from every Page_Load as before I did not. Also, take a look at my web.config file.

web.config file:

    <authentication mode="Forms">
      <forms loginUrl="application/index.aspx" timeout="5" protection="All" defaultUrl="application/secure/index.aspx" path="/"/>
    </authentication>
    <sessionState mode="InProc" timeout="5"/>
  </system.web>
  <location path="application/secure">
    <system.web>
      <authorization>
        <deny users="?"/>
      </authorization>
    </system.web>
  </location>

Code for every page's Page_Load:

        string FirstName = Convert.ToString(Session["fname"]);
        string LastName = Convert.ToString(Session["lname"]);
        string EmpID = Convert.ToString(Session["empid"]);

        lblFullNameSession.Text = "Hello, " + FirstName + " " + LastName;
        hf_emp_id.Value = EmpID;

        if ((Session["UserNameSessionID"] == null) || (Session["UserNameSessionID"].ToString() == ""))
        {
            Response.Redirect("../index.aspx");
        }

LogOut code for each page:

    protected void lb_Logout_Click(object sender, EventArgs e)
    {
        Session.Abandon();
        Response.Redirect("../index.aspx");
    }
0
 
asp_net2Author Commented:
@stephanonline,

Should I also include the following below on every LogOut code to kill the cookie created during Authentication along with what I'm using now for the LogOut code?

FormsAuthentication.SignOut();

Thanks again for your help. I truly appreciate it.
0
 
StephanLead Software EngineerCommented:
Change the lb_Logout_click to this:

protected void lb_Logout_Click(object sender, EventArgs e)
    {
        FormsAuthentication.SignOut();
        Session.Abandon();
        Response.Redirect("../index.aspx");
    }

Open in new window


Wrap an if-statement around the code you posted with this:

if (HttpContext.Current.User.Identity.IsAuthenticated)
{
string FirstName = Convert.ToString(Session["fname"]);
        string LastName = Convert.ToString(Session["lname"]);
        string EmpID = Convert.ToString(Session["empid"]);

        lblFullNameSession.Text = string.Concat("Hello, ", FirstName, " ", LastName);
        hf_emp_id.Value = EmpID
}else {
     Reponse.Redirect("../index.aspx");
}

Open in new window


I think this is the simpliest way for you atm. without any major changes.
If you want to get this, I think it's best to do this through chat.
0
 
asp_net2Author Commented:
Ok, could you please explain the difference from your method compared to mine in regards to which is better and why?

Also, when I ran your code I get the following error below.

Error:

Compiler Error Message: CS0103: The name 'EmpID' does not exist in the current context.

The error is hightlighted on Line 67.

Line 65:
Line 66:             // cmd.Parameters.AddWithValue("@emp_id", SqlDbType.Int).Value = emp_id;
Line 67:             cmd.Parameters.AddWithValue("@emp_id", SqlDbType.Int).Value = EmpID;
Line 68:
Line 69:             DataTable dtAnnualPhysical = new DataTable("Modify");


Your method:

LogOut Code:

protected void lb_Logout_Click(object sender, EventArgs e)
    {
        FormsAuthentication.SignOut();
        Session.Abandon();
        Response.Redirect("../index.aspx");
    }


Page_Load Code:

if (HttpContext.Current.User.Identity.IsAuthenticated)
{
string FirstName = Convert.ToString(Session["fname"]);
        string LastName = Convert.ToString(Session["lname"]);
        string EmpID = Convert.ToString(Session["empid"]);

        lblFullNameSession.Text = string.Concat("Hello, ", FirstName, " ", LastName);
        hf_emp_id.Value = EmpID
}else {
     Reponse.Redirect("../index.aspx");
}


My method:

LogOut Code:

    protected void lb_Logout_Click(object sender, EventArgs e)
    {
        Session.Abandon();
        Response.Redirect("../index.aspx");
    }


Page_Load Code:

        string FirstName = Convert.ToString(Session["fname"]);
        string LastName = Convert.ToString(Session["lname"]);
        string EmpID = Convert.ToString(Session["empid"]);

        lblFullNameSession.Text = "Hello, " + FirstName + " " + LastName;
        hf_emp_id.Value = EmpID;

        if ((Session["UserNameSessionID"] == null) || (Session["UserNameSessionID"].ToString() == ""))
        {
            Response.Redirect("../index.aspx");
        }
0
 
StephanLead Software EngineerCommented:
My bad, I forgot the semicolumn on the hf_emp_id.Value = EmpID

if (HttpContext.Current.User.Identity.IsAuthenticated)
{
string FirstName = Convert.ToString(Session["fname"]);
        string LastName = Convert.ToString(Session["lname"]);
        string EmpID = Convert.ToString(Session["empid"]);

        lblFullNameSession.Text = string.Concat("Hello, ", FirstName, " ", LastName);
        hf_emp_id.Value = EmpID;
}else {
     Reponse.Redirect("../index.aspx");
}

Open in new window


The code I use is based on the asp.net authentication and not upon sessions.
So if you signOut (remove the authentication cookie, Then IsAuthenticated is false.
0
 
asp_net2Author Commented:
That didn't help either. Below is my full Page_Load. The error still happens when  using your code on the same line with the Full Page_Load below. It almost appears that I cannot not access the EmpID value since it's wrapped in the if statement.

Full Page_Load:

protected void Page_Load(object sender, EventArgs e)
    {
        //string FirstName = Convert.ToString(Session["fname"]);
        //string LastName = Convert.ToString(Session["lname"]);
        //string EmpID = Convert.ToString(Session["empid"]);

        //lblFullNameSession.Text = "Hello, " + FirstName + " " + LastName;
        //hf_emp_id.Value = EmpID;

        //if ((Session["UserNameSessionID"] == null) || (Session["UserNameSessionID"].ToString() == ""))
        //{
        //    Response.Redirect("../index.aspx");
        //}

        if (HttpContext.Current.User.Identity.IsAuthenticated)
        {
            string FirstName = Convert.ToString(Session["fname"]);
            string LastName = Convert.ToString(Session["lname"]);
            string EmpID = Convert.ToString(Session["empid"]);

            lblFullNameSession.Text = string.Concat("Hello, ", FirstName, " ", LastName);
            hf_emp_id.Value = EmpID;
        }
        else
        {
            Response.Redirect("../index.aspx");
        }

        lblVerificationFormFileName.Visible = false;
        lblFileSize.Visible = false;
        lblInsertError.Visible = false;
        lblVerificationFormTypeError.Visible = false;

        // EmployeeLoginInfo();
        SectionsCompleted();

        if (!IsPostBack)
        {
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["WellnessTracker"].ConnectionString);

            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "RetrieveAnnualPhysicalValuesByEMP_ID";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Connection = conn;

            // cmd.Parameters.AddWithValue("@emp_id", SqlDbType.Int).Value = emp_id;
            cmd.Parameters.AddWithValue("@emp_id", SqlDbType.Int).Value = EmpID;

            DataTable dtAnnualPhysical = new DataTable("Modify");

            SqlDataAdapter adp = new SqlDataAdapter();

            try
            {
                conn.Open();

                adp.SelectCommand = cmd;
                adp.Fill(dtAnnualPhysical);

                if ((dtAnnualPhysical != null))
                {
                    DataRow data = dtAnnualPhysical.Rows[0];
                    hf_ap_id.Value = data["ap_id"].ToString();

                    lblVerificationFormFileName.Text = "No file is uploaded";

                    txtDateCompleted.Text = string.Empty;
                    if (data["ap_date"] != DBNull.Value && !string.IsNullOrEmpty(Convert.ToString(data["ap_date"])))
                        txtDateCompleted.Text = Convert.ToDateTime(data["ap_date"]).ToShortDateString();

                    string ap_pdf_filename = null;
                    if (data["ap_pdf_filename"] != DBNull.Value)
                    {
                        ap_pdf_filename = data["ap_pdf_filename"].ToString();
                    }

                    if (!string.IsNullOrEmpty(ap_pdf_filename))
                    {
                        lblVerificationFormFileName.Visible = true;
                        lblVerificationFormFileName.Text = "Your File has been uploaded: " + ap_pdf_filename;
                    }

                    if (data["ap_section_complete"].ToString() == "1")
                    {
                        btn_AnnualPhysical.Enabled = false;
                        cb_AnnualPhysical.Checked = true;
                    }

                    else
                    {
                        cb_AnnualPhysical.Checked = false;
                    }
                }
            }

            catch (Exception ex)
            {
                ex.Message.ToString();
            }

            finally
            {
                conn.Close();
            }
        }
0
 
StephanLead Software EngineerCommented:
That's the problem, I didn't know there was more code in your page load.

move the following code at the end of your page load so that the EmpID is availble;

 }
        else 
        {
            Response.Redirect("../index.aspx");
        } 

Open in new window



I cannot answer you anymore today since I'm not on the pc. I will anwers tomorrow if needed.
0
 
asp_net2Author Commented:
@stephanonline,

Sorry, I should have included the rest of the Page_Load. The only thing I would appreciate if you could answer is the following below.

Could you answer the following below please:

What is the difference between using your Page_Load code compared to how I had it?


Also, I tried to move that below but still have the red line on the following line of code below.

Line with error:
cmd.Parameters.AddWithValue("@emp_id", SqlDbType.Int).Value = EmpID;

I have a red line under EmpID. It says "the name "EmpID" does not exist in this current context.
0
 
Christopher KileCommented:
The difference between your code and his code is that he's closing out the FormsAuthorization login created by this code:

if (IsValidPassword(txtUserName.Text, txtPassword.Text))
        {
            Session["UserNameSessionID"] = txtUserName.Text;
           FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, false);

        }

The if-block using HTTPContext is checking to see if FormsAuthorization has a logged-in user, and ONLY displays the info if not.  The call to the .SignOut() function in yout logout code clears the logged-in user from Forms Authorization.

But I've observed something:  you seem to be using the same page for both logins and logouts.  is this correct?
0
 
Jesus RodriguezIT ManagerCommented:
Ok.. let's clarify a little this

- Only One time will check if user has access to the pages or not
Let's say that the site has 5 pages

1- Index.aspx
2- Data1.aspx
3- Data3.aspx
4- Data4.aspx
5- About.aspx
6- Login.aspx

On the index page you will have the login button and the Check for the Session

Index On PageLoad Event

if ((Session["empid"] == null) || (Session["empid"].ToString() == ""))
        {
            lblFullNameSession.Text = "";
            lb_login.visible=True;
            lb_logout.Visible = False;
        }
        else
        {
            string FirstName = Convert.ToString(Session["fname"]);
            string LastName = Convert.ToString(Session["lname"]);
            string EmpID = Convert.ToString(Session["empid"]);

            lblFullNameSession.Text = "Hello, " + FirstName + " " + LastName;
            lb_login.visible=False;
            lb_logout.Visible = true;
        }

Then on the loginbutton

EmployeeLoginInfo()
response.redirect('index.aspx');


The On Data1,..Dat3
On the Page Load check if the Session Variable exist if not Send it back to the index or login page.

if ((Session["empid"] == null) || (Session["empid"].ToString() == ""))
        {
            response.redirect('Index.aspx')
        }
        else
        {
            string FirstName = Convert.ToString(Session["fname"]);
            string LastName = Convert.ToString(Session["lname"]);
            string EmpID = Convert.ToString(Session["empid"]);

            lblFullNameSession.Text = "Hello, " + FirstName + " " + LastName;
            lb_login.visible=False;
            lb_logout.Visible = true;
        }


and on the about page do not check for the variable and let it like this

{
        if ((Session["empid"] == null) || (Session["empid"].ToString() == ""))
        {
            lblFullNameSession.Text = "Hello, Guest";
            lb_logout.Visible = false;
        }
        else
        {
            string FirstName = Convert.ToString(Session["fname"]);
            string LastName = Convert.ToString(Session["lname"]);
            string EmpID = Convert.ToString(Session["empid"]);

            lblFullNameSession.Text = "Hello, " + FirstName + " " + LastName;
            lb_logout.Visible = true;
        }
}
0
 
asp_net2Author Commented:
@cpkilekofp,

>> The difference between your code and his code is that he's closing out the FormsAuthorization login created by this code:

Is that nessecary? Only asking so I can understand.

>> But I've observed something:  you seem to be using the same page for both logins and logouts.  is this correct?

Not sure what you mean by that. EVERY page needs to check whether or not the user is logged in. If so, then display the Session values along with the other code. If not logged in then display "Hello, Guest" and if needed redirect to login page.

I use the following code as of now below to check whether or not the user is logged in. I also have the LogOut code on every page as well.

Now some pages will additional info added to the Page_Load. The only pages that do not have additioanl info to the Page_Load are index.aspx, contact.aspx, and info.aspx. Other pages that required additional info are needed to retrieve data from the DB.

    protected void Page_Load(object sender, EventArgs e)
    {
        if ((Session["UserNameSessionID"] == null) || (Session["UserNameSessionID"].ToString() == ""))
        {
            lblFullNameSession.Text = "Hello, Guest";
            lb_logout.Visible = false;
        }
        else
        {
            string FirstName = Convert.ToString(Session["fname"]);
            string LastName = Convert.ToString(Session["lname"]);
            string EmpID = Convert.ToString(Session["empid"]);

            lblFullNameSession.Text = "Hello, " + FirstName + " " + LastName;
            lb_logout.Visible = true;
        }
    }

    protected void lb_logout_Click(object sender, EventArgs e)
    {
        Session.Abandon();
        Response.Redirect("../application/index.aspx");
    }
0
 
asp_net2Author Commented:
@cpkilekofp,

Also, if I add the following code below which is what stehphanonline suggested I use then for some strange reason my images that are located in the SectionComplete() code do not show up, they show up empty image placeholders. If I remove FormsAuthentication.SignOut(); then my images display. What would cause that...

    protected void Page_Load(object sender, EventArgs e)
    {
        if (HttpContext.Current.User.Identity.IsAuthenticated)
        {
            string FirstName = Convert.ToString(Session["fname"]);
            string LastName = Convert.ToString(Session["lname"]);
            string EmpID = Convert.ToString(Session["empid"]);

            lblFullNameSession.Text = string.Concat("Hello, ", FirstName, " ", LastName);
            hf_emp_id.Value = EmpID;


        lblVerificationFormFileName.Visible = false;
        lblFileSize.Visible = false;
        lblInsertError.Visible = false;
        lblVerificationFormTypeError.Visible = false;

        // EmployeeLoginInfo();
        SectionsCompleted();

        if (!IsPostBack)
        {
            // int emp_id = Convert.ToInt32(Session["emp_id"]);

            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["WellnessTracker"].ConnectionString);

            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "RetrieveAnnualPhysicalValuesByEMP_ID";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Connection = conn;

            // cmd.Parameters.AddWithValue("@emp_id", SqlDbType.Int).Value = emp_id;
            cmd.Parameters.AddWithValue("@emp_id", SqlDbType.Int).Value = EmpID;

            DataTable dtAnnualPhysical = new DataTable("Modify");

            SqlDataAdapter adp = new SqlDataAdapter();

            try
            {
                conn.Open();

                adp.SelectCommand = cmd;
                adp.Fill(dtAnnualPhysical);

                if ((dtAnnualPhysical != null))
                {
                    DataRow data = dtAnnualPhysical.Rows[0];
                    hf_ap_id.Value = data["ap_id"].ToString();

                    lblVerificationFormFileName.Text = "No file is uploaded";

                    txtDateCompleted.Text = string.Empty;
                    if (data["ap_date"] != DBNull.Value && !string.IsNullOrEmpty(Convert.ToString(data["ap_date"])))
                        txtDateCompleted.Text = Convert.ToDateTime(data["ap_date"]).ToShortDateString();

                    string ap_pdf_filename = null;
                    if (data["ap_pdf_filename"] != DBNull.Value)
                    {
                        ap_pdf_filename = data["ap_pdf_filename"].ToString();
                    }

                    if (!string.IsNullOrEmpty(ap_pdf_filename))
                    {
                        lblVerificationFormFileName.Visible = true;
                        lblVerificationFormFileName.Text = "Your File has been uploaded: " + ap_pdf_filename;
                    }

                    if (data["ap_section_complete"].ToString() == "1")
                    {
                        btn_AnnualPhysical.Enabled = false;
                        cb_AnnualPhysical.Checked = true;
                    }

                    else
                    {
                        cb_AnnualPhysical.Checked = false;
                    }
                }
            }

            catch (Exception ex)
            {
                ex.Message.ToString();
            }

            finally
            {
                conn.Close();
            }
        }
        }
        else
        {
            Response.Redirect("../index.aspx");
        }
    }

    protected void SectionsCompleted()
    {
        string EmpID = Convert.ToString(Session["empid"]);

        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["WellnessTracker"].ConnectionString);

        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "RetrieveSectionsCompleted";
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Connection = conn;

        cmd.Parameters.AddWithValue("@emp_id", SqlDbType.Int).Value = EmpID;

        DataTable dtSectionCompleted = new DataTable();

        SqlDataAdapter adp = new SqlDataAdapter();

        try
        {
            conn.Open();

            adp.SelectCommand = cmd;
            adp.Fill(dtSectionCompleted);

            DataRow data = dtSectionCompleted.Rows[0];

            string GreenCheck = "../../img/GreenCheckOnly.png";
            string RedX = "../../img/RedXOnly.png";

            if (data["ap_section_complete"].ToString() == "1")
            {
                // hl_AnnualPhysical.Enabled = false;
                hl_AnnualPhysical.ForeColor = System.Drawing.ColorTranslator.FromHtml("#ff6d00");
                img_AnnualPhysical_Check.ImageUrl = GreenCheck;
                img_AnnualPhysical_X.Visible = false;
            }
            else
            {
                hl_AnnualPhysical.Enabled = true;
                img_AnnualPhysical_X.ImageUrl = RedX;
                img_AnnualPhysical_Check.Visible = false;
            }
            if (data["ghpone_section_complete"].ToString() == "1")
            {
                // hl_GeneralHealthOne.Enabled = false;
                hl_GeneralHealthOne.ForeColor = System.Drawing.ColorTranslator.FromHtml("#ff6d00");
                img_GeneralHealthOne_Check.ImageUrl = GreenCheck;
                img_GeneralHealthOne_X.Visible = false;
            }
            else
            {
                hl_GeneralHealthOne.Enabled = true;
                img_GeneralHealthOne_X.ImageUrl = RedX;
                img_GeneralHealthOne_Check.Visible = false;
            }
            if (data["ghpthree_section_complete"].ToString() == "1")
            {
                // hl_GeneralHealthThree.Enabled = false;
                hl_GeneralHealthThree.ForeColor = System.Drawing.ColorTranslator.FromHtml("#ff6d00");
                img_GeneralHealthThree_Check.ImageUrl = GreenCheck;
                img_GeneralHealthThree_X.Visible = false;
            }
            else
            {
                hl_GeneralHealthThree.Enabled = true;
                img_GeneralHealthThree_X.ImageUrl = RedX;
                img_GeneralHealthThree_Check.Visible = false;
            }
            if (data["ghptwo_section_complete"].ToString() == "1")
            {
                // hl_GeneralHealthTwo.Enabled = false;
                hl_GeneralHealthTwo.ForeColor = System.Drawing.ColorTranslator.FromHtml("#ff6d00");
                img_GeneralHealthTwo_Check.ImageUrl = GreenCheck;
                img_GeneralHealthTwo_X.Visible = false;
            }
            else
            {
                hl_GeneralHealthTwo.Enabled = true;
                img_GeneralHealthTwo_X.ImageUrl = RedX;
                img_GeneralHealthTwo_Check.Visible = false;
            }
            if (data["wp_section_complete"].ToString() == "1")
            {
                // hl_WellnessProfile.Enabled = false;
                hl_WellnessProfile.ForeColor = System.Drawing.ColorTranslator.FromHtml("#ff6d00");
                img_WellnessProfile_Check.ImageUrl = GreenCheck;
                img_WellnessProfile_X.Visible = false;
            }
            else
            {
                hl_WellnessProfile.Enabled = true;
                img_WellnessProfile_X.ImageUrl = RedX;
                img_WellnessProfile_Check.Visible = false;
            }
            if (data["phs_section_complete"].ToString() == "1")
            {
                // hl_PreventiveScreenings.Enabled = false;
                hl_PreventiveScreenings.ForeColor = System.Drawing.ColorTranslator.FromHtml("#ff6d00");
                img_PreventiveScreenings_Check.ImageUrl = GreenCheck;
                img_PreventiveScreenings_X.Visible = false;
            }
            else
            {
                hl_PreventiveScreenings.Enabled = true;
                img_PreventiveScreenings_X.ImageUrl = RedX;
                img_PreventiveScreenings_Check.Visible = false;
            }
            if (data["sha_section_complete"].ToString() == "1")
            {
                // hl_SpecificHealth.Enabled = false;
                hl_SpecificHealth.ForeColor = System.Drawing.ColorTranslator.FromHtml("#ff6d00");
                img_SpecificHealth_Check.ImageUrl = GreenCheck;
                img_SpecificHealth_X.Visible = false;
            }
            else
            {
                hl_SpecificHealth.Enabled = true;
                img_SpecificHealth_X.ImageUrl = RedX;
                img_SpecificHealth_Check.Visible = false;
            }
            if (data["phy_section_complete"].ToString() == "1")
            {
                // hl_PhysicalActivity.Enabled = false;
                hl_PhysicalActivity.ForeColor = System.Drawing.ColorTranslator.FromHtml("#ff6d00");
                img_PhysicalActivity_Check.ImageUrl = GreenCheck;
                img_PhysicalActivity_X.Visible = false;
            }
            else
            {
                hl_PhysicalActivity.Enabled = true;
                img_PhysicalActivity_X.ImageUrl = RedX;
                img_PhysicalActivity_Check.Visible = false;
            }
        }

        catch (Exception ex)
        {
            ex.Message.ToString();
        }

        finally
        {
            conn.Close();
        }
    }

    protected void btn_AnnualPhysical_Click(object sender, EventArgs e)
    {
        if (Page.IsValid && cb_AnnualPhysical.Checked == true) // make sure all fields have data and cb_AnnualPhysical is Checked before Inserting to DB.
        {
            if (fuVerificationForm.HasFile) // a file has been uploaded
            {
                //Make sure we are dealing a .pdf file only
                string extension = Path.GetExtension(fuVerificationForm.PostedFile.FileName).ToLower();
                string MIMEType = null;

                switch (extension)
                {
                    case ".pdf":
                        MIMEType = "application/pdf";
                        break;
                    default:
                        lblVerificationFormTypeError.Visible = true;
                        lblVerificationFormTypeError.Text = "PDF files only!";
                        return;
                }

                string filename = fuVerificationForm.PostedFile.FileName.Split(new char[] { '\\' }).Last();
                int fileSize = fuVerificationForm.PostedFile.ContentLength;

                if ((fileSize < 1048576))
                {

                    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["WellnessTracker"].ConnectionString);

                    SqlCommand cmd = new SqlCommand();
                    cmd.CommandText = "InsertAnnualPhysical";
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Connection = conn;

                    // Load PDF InputStream into Byte array
                    byte[] imageBytes = new byte[fuVerificationForm.PostedFile.InputStream.Length + 1];
                    fuVerificationForm.PostedFile.InputStream.Read(imageBytes, 0, imageBytes.Length);

                    cmd.Parameters.AddWithValue("@emp_id", SqlDbType.Int).Value = hf_emp_id.Value;
                    cmd.Parameters.AddWithValue("@ap_pdf_file", SqlDbType.Image).Value = imageBytes;
                    cmd.Parameters.AddWithValue("@ap_pdf_filename", SqlDbType.VarChar).Value = filename;
                    cmd.Parameters.AddWithValue("@ap_pdf_mime", SqlDbType.VarChar).Value = MIMEType;
                    cmd.Parameters.AddWithValue("@ap_pdf_size", SqlDbType.VarChar).Value = fileSize;
                    cmd.Parameters.AddWithValue("@ap_section_complete", SqlDbType.Int).Value = cb_AnnualPhysical.Checked;

                    if (string.IsNullOrEmpty(txtDateCompleted.Text))
                    {
                        cmd.Parameters.AddWithValue("@ap_date", SqlDbType.DateTime).Value = DBNull.Value;
                    }
                    else
                    {
                        cmd.Parameters.AddWithValue("@ap_date", SqlDbType.DateTime).Value = txtDateCompleted.Text;
                    }

                    try
                    {
                        conn.Open();
                        cmd.ExecuteNonQuery();
                    }

                    catch (Exception ex)
                    {
                        lblInsertError.Visible = true;
                        lblInsertError.Text = ("Error on insert: " + ex.Message.ToString());
                    }

                    finally
                    {
                        Response.Redirect("index.aspx");
                        conn.Close();
                    }
                }

                // Allow only files less than 1,048,576 bytes (approximately 1 MB) to be uploaded.
                {
                    lblFileSize.Visible = true;
                    lblFileSize.Text = "File size must be 1MB or smaller";
                }
            }
            else  // no file has been uploaded, we only need to update txtPhysicalDateCompleted
            {
                string filename = fuVerificationForm.PostedFile.FileName.Split(new char[] { '\\' }).Last();
                int fileSize = fuVerificationForm.PostedFile.ContentLength;

                if ((fileSize <= 0))
                {
                    lblFileSize.Visible = true;
                    lblFileSize.Text = "File size must be 1MB or smaller";
                }
            }
        }
    }

    protected void lb_Logout_Click(object sender, EventArgs e)
    {
        FormsAuthentication.SignOut();
        Session.Abandon();
        Response.Redirect("../index.aspx");
    }

Open in new window

0

Featured Post

Get quick recovery of individual SharePoint items

Free tool – Veeam Explorer for Microsoft SharePoint, enables fast, easy restores of SharePoint sites, documents, libraries and lists — all with no agents to manage and no additional licenses to buy.

  • 20
  • 8
  • 6
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now