Thursday, July 5, 2012

c# - Storing Dictionary/Hastable in HttpCookie.Workaround for Serialization/Deserialization

I came across a situation where I had to store a Dictionary<string,string> in a HttpCookie.When I searched for achieving this the solution that I came across was to serialize the dictionary to a string to store it and then deserialize when needed.

The workaround is to prefix the Dictionary keys with a constant string that is not a part of any key in the HttpCookie and then use it retrieve the Dictionary keys.
The code is below//Store Dictionary in HttpCookieprivate void SetCookieValue(Dictionary<string,string> o_Dictionary)
{
        foreach (KeyValuePair<string, string> oKeyValuePair in o_Dictionary)                                                      
                oCookie.Values[oKeyValuePair.Key + "CONSTANT_STRING"] = oKeyValuePair.Value;
}

//Retrieve Dictionary Key/Values
private Dictionary<string, string> GetDictionaryCookieValue()
{
       Dictionary<string, string> oDictionary = new Dictionary<string, string>();           
       try
       {
             string[] saAllKeys = oCookie.Values.AllKeys;                  
 
              for (int iIndex = 0; iIndex < saAllKeys.Length; iIndex++) 

            {
                    if (saAllKeys[iIndex].Contains(" CONSTANT_STRING "))                               oDictionary.Add(saAllKeys[iIndex].Replace("CONSTANT_STRING",string.Empty), oCookie.Values.Get(saAllKeys[iIndex]));
            }              }
       catch { //Catch exception  }
       return oDictionary;
}


The same workaround can be used for a Hashtable as well.


No comments: