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,
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,
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,
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,
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 !!!