Wednesday, June 25, 2008

Access Cache object of one application from another application OR share Cache object between Applications

       Recently while reading some forum I found an interesting question Can we share the cache object between two different applications ? More specifically can we access cache data of one application from another application ? I thought its a good topic to study and share.

       The answer is yes you can share the cache data between two application or you can access cache data of one application in another. There may be plenty of options to achieve this. The way I found and like is to serialize the cache data and transfer it between two applications.

       In the example which I will show here, I have created a two applications. First application has two pages Default.aspx and SerializeCacheData.aspx. The second application has only one page GetSerializedCacheData.aspx. The logic is, we will add the data in Cache on Default.aspx. SerializeCacheData.aspx page receives the name of the cache object we want to share between two applications. GetSerializedCacheData.aspx call the SerializeCacheData.aspx page and passes the name of the cache data that it wants from first application in querystring.

      On Default.aspx page I am creating an object of Person class (I have created a class in App_Code folder and will store the object of that class in cache) and string it is Cache. To store the object in Cache that object must be serializable. So I have marked my Person class as [Serializale]. Below is the Person class,

   1: using System;
   2: using System.Data;
   3: using System.Configuration;
   4: using System.Linq;
   5: using System.Web;
   6: using System.Web.Security;
   7: using System.Web.UI;
   8: using System.Web.UI.HtmlControls;
   9: using System.Web.UI.WebControls;
  10: using System.Web.UI.WebControls.WebParts;
  11: using System.Xml.Linq;
  12:  
  13: /// <summary>
  14: /// Summary description for Person
  15: /// </summary>
  16: [Serializable]
  17: public class Person
  18: {
  19:     public Person()
  20:     {
  21:         //
  22:         // TODO: Add constructor logic here
  23:         //
  24:         Name = "Chirag";
  25:         Address = "Ahmedabad";
  26:         Id = 1;
  27:         strPrivateData = "chirag";
  28:     }
  29:  
  30:     public string Name { get; set;}
  31:     public string Address { get; set; }
  32:     public int Id { get; set; }
  33:  
  34:     private string strPrivateData;
  35:  
  36: }

Fig - (1) Person class, we are going to store its object in Cache


       On Default.aspx page we will store the object of person class in cache as shown below,



   1: using System;
   2: using System.Configuration;
   3: using System.Data;
   4: using System.Linq;
   5: using System.Web;
   6: using System.Web.Security;
   7: using System.Web.UI;
   8: using System.Web.UI.HtmlControls;
   9: using System.Web.UI.WebControls;
  10: using System.Web.UI.WebControls.WebParts;
  11: using System.Xml.Linq;
  12:  
  13: public partial class _Default : System.Web.UI.Page 
  14: {
  15:     protected void Page_Load(object sender, EventArgs e)
  16:     {
  17:         if (!Page.IsPostBack)
  18:         {
  19:             Person objPerson = new Person { Name = "Dipak", Address = "USA", Id = 2 };
  20:             Cache.Insert("TestData", objPerson);
  21:         }
  22:     }
  23: }

Fig - (2) Storing data in Cache.


        On SerializeCacheData.aspx page we will serialize the cache data in byte array.  We will get the name of cache data in querystring.  As you can see in code below we will get the querystring parameter "data" on this page. We will retrieve the values from cache using querystring parameter and serialize it in Memory Stream. There is no need to store value in ViewState however I have specifically stored in ViewState as I need to do some operations on postback which I have not covered in this article. Look at the code below,



   1: using System;
   2: using System.Collections;
   3: using System.Configuration;
   4: using System.Data;
   5: using System.Linq;
   6: using System.Web;
   7: using System.Web.Security;
   8: using System.Web.UI;
   9: using System.Web.UI.HtmlControls;
  10: using System.Web.UI.WebControls;
  11: using System.Web.UI.WebControls.WebParts;
  12: using System.Xml.Linq;
  13: using System.Runtime.Serialization;
  14: using System.Runtime.Serialization.Formatters.Binary;
  15: using System.IO;
  16:  
  17: public partial class SerializeCacheData : System.Web.UI.Page
  18: {
  19:     public MemoryStream objMemoryStream
  20:     {
  21:         get
  22:         {
  23:             if (ViewState["objMemoryStream"] == null)
  24:                 ViewState["objMemoryStream"] = new MemoryStream();
  25:             return (MemoryStream)ViewState["objMemoryStream"];
  26:         }
  27:  
  28:         set
  29:         {
  30:             ViewState["objMemoryStream"] = value;
  31:         }
  32:     }
  33:     
  34:  
  35:     protected void Page_Load(object sender, EventArgs e)
  36:     {
  37:         if (!Page.IsPostBack)
  38:         {
  39:             string strValueToSerialize = string.Empty;
  40:  
  41:             // Get the name of Cache data from querystring
  42:             if (Request.QueryString["data"] != null)
  43:                 strValueToSerialize = Request.QueryString["data"].ToString();
  44:  
  45:             if (strValueToSerialize != string.Empty)
  46:             {
  47:                 // Serialize the data in Memory Stream
  48:                 IFormatter objIFormatter = new BinaryFormatter();
  49:                 objIFormatter.Serialize(objMemoryStream, Cache[strValueToSerialize]);
  50:                 objMemoryStream.Position = 0;
  51:  
  52:                 // Generate the byte array from Memory Stream
  53:                 byte[] objByte = new byte[objMemoryStream.Length];
  54:                 objMemoryStream.Read(objByte, 0, Convert.ToInt32(objMemoryStream.Length));
  55:                 Response.BinaryWrite(objByte);
  56:                 objMemoryStream.Position = 0;
  57:                 Response.End();
  58:             }
  59:             
  60:         }
  61:         
  62:     }
  63: }

Fig - (3) SerializeCacheData.aspx.cs


      Now in second application from GetSerializedCacheData.aspx page we will call SerializCacheData.aspx page and retrieves the value. Look at the code below,



   1: using System;
   2: using System.Collections;
   3: using System.Configuration;
   4: using System.Data;
   5: using System.Linq;
   6: using System.Web;
   7: using System.Web.Security;
   8: using System.Web.UI;
   9: using System.Web.UI.HtmlControls;
  10: using System.Web.UI.WebControls;
  11: using System.Web.UI.WebControls.WebParts;
  12: using System.Xml.Linq;
  13: using System.Net;
  14: using System.IO;
  15: using System.Runtime.Serialization;
  16: using System.Runtime.Serialization.Formatters.Binary;
  17:  
  18: public partial class GetSerilizedCacheData : System.Web.UI.Page
  19: {
  20:     protected void Page_Load(object sender, EventArgs e)
  21:     {
  22:         if (!Page.IsPostBack)
  23:         {
  24:             // Generate WebRequest to SerializeCacheData.aspx page
  25:             WebRequest objWebRequest = WebRequest.Create("http://localhost:1083/SerializationEx/SerializeCacheData.aspx?data=TestData");
  26:             WebResponse objWebResponse = objWebRequest.GetResponse();
  27:             Stream objStream = objWebResponse.GetResponseStream();
  28:  
  29:             // Deserialize the value
  30:             IFormatter objIFormatter = new BinaryFormatter();
  31:             Person objPerson = (Person)objIFormatter.Deserialize(objStream);
  32:             Response.Write(objPerson.Name);
  33:             
  34:         }
  35:     }
  36: }

Fig - (4) GetSerializedCacheData.aspx.cs


     As shown in above code, we are retrieving the Person class object in second application and writing the Name value in response. You must have to have Person class in both application. In real time you can pass anything which can be serialized like DataTable, DataSet or any custom object.


Happy Programming !!!