JMD
JMD

Reputation: 403

Using session to get/set object properties everytime

I tried searching for this but I'm not even sure how to phrase it for the search.

What I'm attempting to do is have a class that everytime I access it to change it, I'm really getting and setting the value from session.

Here's what I'm trying to do (what I have so far.):

public class example
{
   public int prop1 {get;set;}

   public static example Instance
   {
       return (example)(HttpContext.Current.Session["exampleClass"] ?? new example());
   }

}

public class main
{
   protected void Page_Load(object sender, EventArgs e)
   {
      example.Instance.prop1 = "aaa"; //stores value into session
      txtInput.Text = example.Instance.prop1; //retrieves value from session
   }
}

I hope that makes sense on what I am trying to do.

Any help would be appreciated, thank you.

Upvotes: 4

Views: 36114

Answers (5)

David East
David East

Reputation: 32624

If you're looking for a more object oriented way of doing session here is a good way of doing it below.

UserSession Class

[Serializable()]
public class UserSession
{

    private CurrentRecord _CurrentRecord;
    public CurrentRecord CurrentRecord
    {
        get
        {
            if ((_CurrentRecord == null))
            {
                _CurrentRecord = new CurrentRecord();
            }
            return _CurrentRecord;
        }
        set
        {
            if ((_CurrentRecord == null))
            {
                _CurrentRecord = new CurrentRecord();
            }
            _CurrentRecord = value;
        }
    }
}

Globals Class

public static class Globals
{
    public static UserSession TheUserSession
    {
        get
        {
            if ((HttpContext.Current.Session["UserSession"] == null))
            {
                HttpContext.Current.Session.Add("UserSession", new CurrentUserSession());
                return (CurrentUserSession)HttpContext.Current.Session["UserSession"];
            }
            else
            {
                return (CurrentUserSession)HttpContext.Current.Session["UserSession"];
            }
        }
        set { HttpContext.Current.Session["UserSession"] = value; }
    }
}

CurrentRecord class

[Serializable()]
public class CurrentRecord
{
    public int id { get; set; }
    public string name { get; set; }
}

Usage in code behind

    public void SetRecordId(int newId)
    {
        Globals.TheUserSession.CurrentRecord.id = newId;
    }

Upvotes: 1

James Johnson
James Johnson

Reputation: 46077

It looks like you're pretty close, but you don't have anything to actually store the object in session. Try something like this:

public static Example Instance
{
    get
    {
        //store the object in session if not already stored
        if (Session["example"] == null)
            Session["example"] = new Example();

        //return the object from session
        return (Example)Session["example"];
    }
}

This is basically just a web-friendly implementation of the Singleton Pattern.

Upvotes: 5

Adauto
Adauto

Reputation: 569

using System.Web;
using System.Web.SessionState;
using System.Collections.Generic;

public static class ExampleSession
{
    private static HttpSessionState session { get { return HttpContext.Current.Session; } }

    public static string UserName
    {
        get { return session["username"] as string; }
        set { session["username"] = value; }
    }

    public static List<string> ProductsSelected
    {
        get
        {             
            if (session["products_selected"] == null)
                session["products_selected"] = new List<string>();

            return (List<string>)session["products_selected"];        
        }
    }
}

and you can use it like so:

public class main
{
   protected void Page_Load(object sender, EventArgs e)
   {
      //stores value into session
      ExampleSession.UserName = "foo";
      ExampleSession.ProductsSelected.Add("bar"); 
      txtInput.Text = ExampleSession.UserName; //retrieves value from session
   }
}

Upvotes: 5

Kris Ivanov
Kris Ivanov

Reputation: 10598

public class example {
   public int prop1 { get; set; } 

   public static example Instance {
       var exampleObject = (example)(HttpContext.Current.Session["exampleClass"]
                                     ?? new example());

       HttpContext.Current.Session["exampleClass"] = exampleObject;

       return exampleObject; 
   } 

}

you can optimize it further if needed

Upvotes: 2

Chuck Conway
Chuck Conway

Reputation: 16435

This would be easy to do with generics.

Give this a try.

public class Session
{
    public User User
    {
        get { return Get<User>("User"); }
        set {Set<User>("User", value);}
    }

    /// <summary> Gets. </summary>
    /// <typeparam name="T"> Generic type parameter. </typeparam>
    /// <param name="key"> The key. </param>
    /// <returns> . </returns>
    private T Get<T>(string key)
    {
        object o = HttpContext.Current.Session[key];
        if(o is T)
        {
            return (T) o;
        }

        return default(T);
    }

    /// <summary> Sets. </summary>
    /// <typeparam name="T"> Generic type parameter. </typeparam>
    /// <param name="key">  The key. </param>
    /// <param name="item"> The item. </param>
    private void Set<T>(string key, T item)
    {
        HttpContext.Current.Session[key] = item;
    }
}

Upvotes: 7

Related Questions