0

I want to store my global data till its inserted into DB. so, i want to implement a customer class which can handle creating and storing session values. So, below is my code.

 public static class SessionHelper
 {
    private static int custCode;
    public static int PropertyCustCode
    {
        get
        {
            return custCode;
        }
        set
        {
            if   (!string.IsNullOrEmpty(HttpContext.Current.Session[propertyCode].ToString()))
            {
                custCode = value;
            }
            else
            {
                throw new Exception("Property Code Not Available");
            }
        }
    }

    public static void MakePropertyCodeSession(int custCode)
    {
        try
        {
            HttpContext.Current.Session[propertyCode] = custCode;
        }
        catch(Exception ex)
        {

        }
    }

I am Assigning Property Code from my webpage like below

SessionHelper.MakePropertyCodeSession(7777);

and after this i want to access session value like below

int propertyCode=SessionHelper.PropertyCustCode;

But, I am not able to access session values. Every time, I am getting as null value. Why? where is my mistake?

Arjun
  • 533
  • 2
  • 9
  • 23
  • 1
    Where are from _propertyCode_? – ale May 07 '14 at 05:57
  • I am assigning this property code from my web page by calling this MakePopertyCodeSession method while loading itself and henceforth i want to use this session value throughout my application by using its property(PropertyCustCode). Hope, its clear – Arjun May 07 '14 at 05:59
  • Try to add significant code snippet where you use your static Class – ale May 07 '14 at 06:07
  • I have updated my code snippet. Please see now. – Arjun May 07 '14 at 06:14
  • Maybe I need a coffee break but your project can compile? – ale May 07 '14 at 06:18
  • I struck with this problem and not able to proceed and my build is succeed and not able to proceed to next page since this is key session for next pages in my application – Arjun May 07 '14 at 06:22

1 Answers1

0
HttpContext.Current.Session[propertyCode].ToString()

Will give you problems if the HttpContext.Current.Session[propertyCode] is null. However is it very hard to see what want to do with you code, maybe you should try to rewrite it like:

 public static class SessionHelper
 {
  public static int PropertyCustCode
  {
    get
    {
        int result = 0;
        if (int.TryParse(HttpContext.Current.Session[propertyCode], out result){
            return result;
        }
        else
        {
            throw new Exception("HttpContext.Current.Session[propertyCode] is not a integer");
        } 
    }
    set
    {
          HttpContext.Current.Session[propertyCode] = value.ToString();
    }
}

Now you can just do:

SessionHelper.PropertyCustCode = 7777;
int custcode = SessionHelper.PropertyCustCode;
Peter
  • 27,590
  • 8
  • 64
  • 84