[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Display text if Session is empty

Posted on 2012-08-22
11
Medium Priority
?
866 Views
Last Modified: 2012-08-23
Hello Experts,

I'm creating an application and I need help with hiding a Label Control if a particular Session variable does not exist or is empty. When a user logs into my system it stores there First, Last names, and EmpID which is there empoyee ID.

If a user signs in then I have there name displayed to a Label Control with a LinkButton allowing them to log out.

However, I need to display "Hello, Guest" if a user has not logged in and I then need to also disable or hide the LinkButton control.

Below is my current Page_Load code that displays the usersname First, Last names and EmpID to a Label Control if they have logged in.


Page_Load CodeBehind:

    protected void Page_Load(object sender, EventArgs e)
    {
        EmployeeLoginInfo();

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


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



HTML Markup:

<li class="rgt"><asp:Label ID="lblFullNameSession" runat="server" CssClass="rgtlabel"></asp:Label>&nbsp;&nbsp;<asp:LinkButton ID="lb_logout" OnClick="lb_logout_Click" runat="server">logout</asp:LinkButton></li>
0
Comment
Question by:asp_net2
  • 6
  • 4
11 Comments
 
LVL 13

Expert Comment

by:Jesus Rodriguez
ID: 38322468
I'm not to savy on C# but must be something like that


EmployeeLoginInfo();

   
'Here check if the sessions variable are empty first
 if (Session["fname"] != null)  {
     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
 
LVL 15

Expert Comment

by:rajeeshmca
ID: 38324859
Hi,

try the following in the page load

if (Session["fname"] == null)  {
     lblFullNameSession.Text="Hello, Guest";
     lb_logout.visible=false;
  } else if(Session["fname"].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
 
LVL 4

Author Comment

by:asp_net2
ID: 38325347
@k-designers and rajeeshmc,

First of all thank you very much for replying and helping out. Late last night I was able to take k-designers code modify it and got the following below. But after seeing your post rajeeshmca I had to ask myself if I was handling this the wrong way. Either your way or my way work fine in C# after I cleaned up the code a little bit. So my question is which way is better see both example below and let me know which one is the better of the two. As you will both see below I'm actually loading in the Session values before I even check to see whether or not that value is !null. Not sure if this is good practice or not.

My Code:

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

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

Both of your code snippets:

        if (Session["empid"] == null)  
        {
            lblFullNameSession.Text="Hello, Guest";
            lb_logout.Visible = false;
        }
        else if (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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 13

Accepted Solution

by:
Jesus Rodriguez earned 2000 total points
ID: 38325432
You can simplify your code like this too, but second will check for more posibilities

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
 
LVL 4

Author Comment

by:asp_net2
ID: 38325501
@k-designers,

Which one would you use?
0
 
LVL 13

Expert Comment

by:Jesus Rodriguez
ID: 38325611
Second One. On that one you check iif is null or if is Empty. The only that I do on the last piece of code was join the two conditions in one line (I think that | works  like and or on VB)
0
 
LVL 4

Author Comment

by:asp_net2
ID: 38325686
Hi k-designers,

Ok, I will use your second one. But I ran into a bigger issue. When I logout it should kill my session(s) but when I navigate to another page it keeps the session value. How can I properly kill my session(s) across my entire application when I click on the logout button. Please see the code I'm using below for logging out. I have the same code on every page of my application.

    protected void lb_logout_Click(object sender, EventArgs e)
    {
        Session.Abandon();
        Response.Redirect("application/index.aspx");
    }
0
 
LVL 13

Expert Comment

by:Jesus Rodriguez
ID: 38326000
I think that you have the property Session.RemoveAll() that kill and erase every variables stored on Sessions.

you only has to do this code on the logout_click event
 protected void lb_logout_Click(object sender, EventArgs e)
    {
        Session.RemoveAll();
        Session.Abandon();
        Response.Redirect("application/index.aspx");
    }


Also you must check on every page something like this when the page load

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

to prevent that the guest enter to other pages
0
 
LVL 4

Author Comment

by:asp_net2
ID: 38326055
Hi k-designers,

Ok, first of all can you please post what you just posted on the link below. I created another post and if it works I would like to award you the points.

http://www.experts-exchange.com/Programming/Languages/.NET/ASP.NET/Q_27840081.html
0
 
LVL 4

Author Comment

by:asp_net2
ID: 38326176
Hi k-designers,

Also, I need to be able to allow users to access the Home, Information, and Contact pages without logging in. But if they login they I would like to display there login information with the ability to logout. But when they log out I don't want to see their session values.
0
 
LVL 4

Author Closing Comment

by:asp_net2
ID: 38327852
Thank you!
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
Whether it be Exchange Server Crash Issues, Dirty Shutdown Errors or Failed to mount error, Stellar Phoenix Mailbox Exchange Recovery has always got your back. With the help of its easy to understand user interface and 3 simple steps recovery proced…
As many of you are aware about Scanpst.exe utility which is owned by Microsoft itself to repair inaccessible or damaged PST files, but the question is do you really think Scanpst.exe is capable to repair all sorts of PST related corruption issues?
Suggested Courses

834 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question