user4221591
user4221591

Reputation: 2180

check the value of session variable created at another cs file in Base Page

I've created Session Variables as Objects from the tutorial http://www.c-sharpcorner.com/uploadfile/9505ae/session-variables-as-objects/

I have given the values of the session from login page LoginUser.aspx . I am trying to check if the session values are empty or not in Base Page. When I login from the login page and redirects to another page, the session values are checked in base page. The session values in Base page are always NULL. I can not retrieve the session values set from LoginUser.aspx in Base page class.

public class C_UserSession
    {
        #region Variables
        private const string mySessionName = "_MyUserInfo_";    //Our session name
        private string username;
        private string role;
        private string name;
        #endregion

        #region constructor
        public C_UserSession()
        {

        }
        #endregion
        #region Public Methods
        public string UserName
        {
            get { return this.username; }
            set { this.username = value; Save(); }
        }
        public string Role
        {
            get { return this.role; }
            set { this.role = value; Save(); }
        }
        public string Name
        {
            get { return this.name; }
            set { this.name = value; Save(); }
        }
        #endregion
        #region Private Methods
        private void CheckExisting()
        {
            if (HttpContext.Current.Session[mySessionName] == null)
            {
                //Save this instance to the session
                HttpContext.Current.Session[mySessionName] = this;
                UserName = string.Empty;
                Role = string.Empty;
                Name = string.Empty;
            }
            else
            {
                //Initialize our object based on existing session
                C_UserSession oInfo = (C_UserSession)HttpContext.Current.Session[mySessionName];
                this.UserName = oInfo.UserName;
                this.Name = oInfo.Name;
                this.Role = oInfo.Role;
                oInfo = null;
            }
        }
        private void Save()
        {
            //Save our object to the session
            HttpContext.Current.Session[mySessionName] = this;
        }
        #endregion
    }

login page code behind logic

public partial class LoginUser : System.Web.UI.Page
    {
        C_UserSession usersession;
        protected void Page_Load(object sender, EventArgs e)
        {
                Session.Clear();
                Session.Abandon();
                usersession = new C_UserSession();

        }

        protected void btnSignIn_Click(object sender, EventArgs e)
        {

                DataTable dt = new DataTable();
                dt = new C_User().Get_LoginUser(inputUserName.Value, inputPwd.Value);
                if (dt == null || dt.Rows.Count == 0)
                {
                    Response.Redirect("LoginUser.aspx", false);
                    return;
                }
                DataRow dr = dt.Rows[0];
                usersession.UserName = dr["USERNAME"].ToString();
                usersession.Name = dr["NAME"].ToString();
                usersession.Role = dr["ROLE"].ToString();

                Int16 userRole = Convert.ToInt16(usersession.Role);
                Dictionary<int, string> _redirects = new Dictionary<int, string>
                {
                    { 1, "product.aspx"}, {2, "shift.aspx" }
                };

                Response.Redirect(_redirects[userRole], false);

        }
    }

base page code behind

public class BasePage : System.Web.UI.Page
    {
        C_UserSession usersession;
        public BasePage() {
            usersession = new C_UserSession();
        }

        protected override void OnInit(EventArgs e)
        {
            try
            {
                if ( string.IsNullOrEmpty(usersession.UserName) || string.IsNullOrEmpty(usersession.Role))
                {
                    Response.Redirect("LoginUser.aspx");
                    Context.ApplicationInstance.CompleteRequest();
                }
            }
            catch (Exception ex)
            {

                throw;
            }
        }
    }

product page inherits Base Page

public partial class product : BasePage 
{
    // code blocks  
}

When I open my product.aspx page, it redirects me to LoginUser.aspx because session values are null. But after providing valid username and password also, I can not go the respective pages. I can not check the session values from Base Page. I can not understand what is the correct approach to do this. Please help. Thank You!!!

Upvotes: 0

Views: 432

Answers (2)

CodingYoshi
CodingYoshi

Reputation: 27039

Here is the issue. In your BasePage you have this code:

public class BasePage : System.Web.UI.Page
{
    C_UserSession usersession;
    public BasePage()
    {
        usersession = new C_UserSession();
    }

    protected override void OnInit(EventArgs e)
    {
        try
        {
            if (string.IsNullOrEmpty(usersession.UserName) || string.IsNullOrEmpty(usersession.Role))
            {
            }
        }
    }
}

But off course usersession.Userame will be empty because you just created it in the constructor.

What you should be doing is checking the session to see if it is there and if not, then do a redirect:

public class BasePage : System.Web.UI.Page
{
    C_UserSession usersession;
    public BasePage()
    {
        usersession = (C_UserSession)HttpContext.Current.Session[mySessionName];
    }

    protected override void OnInit(EventArgs e)
    {
        try
        {
            if (usersession == null)
            {
                Response.Redirect("LoginUser.aspx");
                Context.ApplicationInstance.CompleteRequest();
            }
        }
    }
}

Now you may have other issues in your code but that is the answer to your question.


Please do yourself a favor: If you are coding in C# then follow the C# coding conventions. Stop using names like C_UserSession and call it something without the underscore such. Do not call your class product but call it Product (Pascal Notation) or better yet call it ProductPage. Take some time and study your code and clean it up.

Upvotes: 2

Mark Fitzpatrick
Mark Fitzpatrick

Reputation: 1624

I don't think you are ever initializing your user object. You have a CheckExisting() private method on your class which appears to re-hydrate the class from session if it's there, but this is never called. If you don't call this within your class then it won't fill those properties and they will always be the default.

Upvotes: 0

Related Questions