Storing UserID and Username as global variable

2.8k views Asked by At

I am very new to ASP.NET so please take that into consideration in your response.

I have a method that creates a session cookie for my username and User ID that works when I put it into the code behind (See below)

protected void Page_Load(object sender, EventArgs e)
{
    if (Page.User.Identity.IsAuthenticated) // if the user is already logged in
    {
        MembershipUser currentUser = Membership.GetUser();

        Guid CurrentUserID = (Guid)currentUser.ProviderUserKey;
        string CurrentUsername = (string)currentUser.UserName;

        Session["CurrentUserID"] = CurrentUserID;
        Session["CurrentUserName"] = CurrentUsername;
    }
    else
    {
        Session["CurrentUserID"] = "";
        Session["CurrentUserName"] = "";
    }
}

I am trying to clean up my project and thought it would be wise to store any methods into a class file in my App_code directory so that I only had one instance of each.

I cannot just cut and paste the code above into the class file (below) as I receive multiple errors.

I would like to know what the best practice is for storing these as global variables?

My class file in my App_code folder

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;

/// <summary>
/// Generic utilities that can be accessed from any page
/// </summary>
public static class GlobalUtilities
{


    //Takes x characters from the right hand side. TO USE: MyString.TxtStrRight(8)
    public static string TxtStrRight(this string value, int length)
    {
        if (String.IsNullOrEmpty(value)) return string.Empty;

        return value.Length <= length ? value : value.Substring(value.Length - length);
    }

    //Takes x characters from the left hand side. TO USE: MyString.TxtStrLeft(40)
    public static string TxtStrLeft(this string value, int length)
    {
        if (String.IsNullOrEmpty(value)) return string.Empty;

        return value.Length <= length ? value : value.Substring(0, length) + "...";
    }

    //Get the difference between time and date of NOW and the database value. TO USE: GlobalUtilities.GetDiffDate(MyDate)
    public static string GetDiffDate(DateTime dt)
    {
        TimeSpan ts = dt - DateTime.Now;
        if (Math.Abs(ts.TotalHours) < 24 && Math.Abs(ts.TotalHours) >= 1)
        {
            return string.Format("{0:0} hrs ago", Math.Abs(ts.TotalHours));
        }
        else if (Math.Abs(ts.TotalHours) < 1)
        {
            return string.Format("{0:0} mins ago", Math.Abs(ts.TotalMinutes));
        }
        else
        {
            return dt.ToString("dd MMM yyyy");
        }
    }



}
1

There are 1 answers

5
Redit0 On BEST ANSWER

Page_Load is an event handler that handles the page.load event which occurs during the life cycle of an ASP .Net web request. While it is literally a method, it's not a method in the sense that your extension methods in the GlobalUtilities class are. If you try to take that method out of the context of something which fires the Page.Load event, it will not work.

If your goal is to abstract your code which sets the session variables out, so as to avoid duplication, you can create a different method to handle that explicitly.

It might look like this:

public static void SetSessionVariables(this MembershipUser currentUser) {
    Guid CurrentUserID = (Guid)currentUser.ProviderUserKey;
    string CurrentUsername = (string)currentUser.UserName;

    Session["CurrentUserID"] = CurrentUserID;
    Session["CurrentUserName"] = CurrentUsername;
}

And then your Page_Load handler would look like this:

protected void Page_Load(object sender, EventArgs e)
{
    if (Page.User.Identity.IsAuthenticated) { // if the user is already logged in
        MembershipUser currentUser = Membership.GetUser();

        currentUser.SetSessionVariables();
    }
    else
    {
        Session["CurrentUserID"] = "";
        Session["CurrentUserName"] = "";
    }
}

There will still be some stuff left behind. You can't move the initial if out of the event handler for the same reason you can't move the event handler itself; the Page object won't be available to you outside of this context.

As far as what the best way to store global data is, Session is a pretty good option. The only downside is that Session itself is a property of the HttpContext; so it won't be available outside of your presentation layer (web project) unless you pass the context around between methods, and that sucks.