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

Wednesday, May 14, 2008

Internet Explorer contains Dipak Bhattarai in title

      Recently I found many pcs affected by this. You can see Dipak Bhattarai in title of every Internet explorer window. The simples solution I found to remove this is change the registry value. I am not sure that this has also added some malicious entry some where and maybe stilling or sniffing the data. However to remove name from title , Go to Start - Run - type regedit. Now go to HEY_CURRENT_USER - SOFTWARE - MICROSOFT - INTERNET EXPLORER - MAIN

       Go to Window_Title key and change the value field to "Microsoft Internet Explorer".

Happy Programming !!!

Friday, May 09, 2008

Generate Image from text using C# OR Convert Text in to Image using C#

     Today I learn a new thing, how to generate and image form given text or how to convert text in to image? Dotnet framework provides System.Drawing and System.Drawing.Graphics class which helps us to generate image from text or convert text into image. Below is the code,

   1: private Bitmap CreateBitmapImage(string sImageText)
   2: {
   3:     Bitmap objBmpImage = new Bitmap(1, 1);
   4:  
   5:     int intWidth = 0;
   6:     int intHeight = 0;
   7:  
   8:     // Create the Font object for the image text drawing.
   9:     Font objFont = new Font("Arial", 20, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel);
  10:  
  11:     // Create a graphics object to measure the text's width and height.
  12:     Graphics objGraphics = Graphics.FromImage(objBmpImage);
  13:     
  14:     // This is where the bitmap size is determined.
  15:     intWidth = (int)objGraphics.MeasureString(sImageText, objFont).Width;
  16:     intHeight = (int)objGraphics.MeasureString(sImageText, objFont).Height;
  17:  
  18:     // Create the bmpImage again with the correct size for the text and font.
  19:     objBmpImage = new Bitmap(objBmpImage, new Size(intWidth, intHeight));
  20:  
  21:     // Add the colors to the new bitmap.
  22:     objGraphics = Graphics.FromImage(objBmpImage);
  23:  
  24:     // Set Background color
  25:     objGraphics.Clear(Color.White);
  26:     objGraphics.SmoothingMode = SmoothingMode.AntiAlias;
  27:     objGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;
  28:     objGraphics.DrawString(sImageText, objFont, new SolidBrush(Color.FromArgb(102, 102, 102)), 0, 0);
  29:     objGraphics.Flush();
  30:  
  31:     return (objBmpImage);
  32: }

Fig (1) - generate image from text or convert text into image 


Happy Programming!!! 

Tuesday, May 06, 2008

Missing templates in Visual Studio installed templates

     

         Today, when I start visual studio and click on Add new Item I found that WebForm option is missing from visual studio templates. Thanks to Eric Hammersley who gave the perfect solution. To add missing templates you need to run following command on visual studio command prompt.

     Close all instance of Visual Studio. Open visual studio command prompt and type,

                devenv /installvstemplates

       Press Enter. Let the process be complete and now open visual studio. You will get all missing templates under Visual Studio installed templates. 

Happy Programming !!

Monday, May 05, 2008

How to Serialize Object in Dot Net

What is Serialization?

     Serialization is the process of storing the state of an object to the stream of bytes. Using serialization one can store the object in to memory stream or file system in such a way that the original object can be retrieve from persistent medium using DeSerialization.

     One can make the class serialize by adding [Serializable] attribute at the top of class and the dot net framework automatically serialize object of that class when ever required. For example you can store only serializable data in ViewState. So if you have a class which has [Serializable] attribute, the dot net framework automatically serialize it and store it in ViewState. You  do not have to write any code for serialization.

      In this article I used a Person class (shown in Fig - (1)) which has few fields with different datatypes. We will Serialize and Deserialize the object of Person class using CustomSerialization class (shown in Fig (2)).

   1: /// <summary>
   2: /// Summary description for Person
   3: /// </summary>
   4: [Serializable]
   5: public class Person
   6: {
   7:     private string mstrName;
   8:     private string mstrCity;
   9:     [NonSerialized]
  10:     private string mstrPhone;
  11:     private int mintPinCode;
  12:     
  13:  
  14:     public int PinCode
  15:     {
  16:         get { return mintPinCode; }
  17:         set { mintPinCode = value; }
  18:     }
  19:     
  20:     public string Phone
  21:     {
  22:         get { return mstrPhone; }
  23:         set { mstrPhone = value; }
  24:     }
  25:     
  26:     public string City
  27:     {
  28:         get { return mstrCity; }
  29:         set { mstrCity = value; }
  30:     }
  31:     
  32:     public string Name
  33:     {
  34:         get { return mstrName; }
  35:         set { mstrName = value; }
  36:     }
  37:     
  38:     
  39: }

Fig - (1) Person class which we will use for serialization.


   One can add [NonSerialized] attribute for the field that one do not wants to serialize. You can see that we have used [NonSerialized] attribute to mstrPhone field.


   Below is CustomSerialization class which includes the method for Serialization and DeSerialization. We need to import System.Runtime.Serialization and System.Runtime.Serialization.Formatters.Binary namespace.



   1: using System;
   2: using System.Data;
   3: using System.Configuration;
   4: using System.Web;
   5: using System.Web.Security;
   6: using System.Web.UI;
   7: using System.Web.UI.WebControls;
   8: using System.Web.UI.WebControls.WebParts;
   9: using System.Web.UI.HtmlControls;
  10: using System.IO;
  11: using System.Runtime.Serialization;
  12: using System.Runtime.Serialization.Formatters.Binary;
  13:  
  14:  
  15: /// <summary>
  16: /// Summary description for CustomSerialization
  17: /// </summary>
  18: public class CustomSerialization
  19: {
  20:     /// <summary>
  21:     /// Serialize Data
  22:     /// </summary>
  23:     /// <param name="objData">Data to be Serialized</param>
  24:     /// <returns>MemoryStream</returns>
  25:     public static MemoryStream SerializData(Object objData)
  26:     {
  27:         MemoryStream msMemoryStream = new MemoryStream();         
  28:  
  29:         IFormatter objIFormatter = new BinaryFormatter();
  30:         objIFormatter.Serialize(msMemoryStream, objData);
  31:         msMemoryStream.Position = 0;
  32:  
  33:         return msMemoryStream;
  34:     }
  35:  
  36:     /// <summary>
  37:     /// Deserialize Data
  38:     /// </summary>
  39:     /// <param name="msData">Memory Stream containing serialized data</param>
  40:     /// <returns>Object</returns>
  41:     public static object DeSerializData(MemoryStream msData)
  42:     {
  43:         IFormatter objIFormatter = new BinaryFormatter();
  44:         return objIFormatter.Deserialize(msData);
  45:     }
  46: }

Fig - (2) Custom Serialization class to serialize and deserialize the data.


   Code shows a part of web page code behind which shows code for serialization.



   1: public Person objPerson
   2:    {
   3:        get 
   4:        {
   5:            if (ViewState["objPerson"] == null)
   6:                ViewState["objPerson"] = new Person();
   7:            return (Person)ViewState["objPerson"]; 
   8:        }
   9:        set 
  10:        { 
  11:            ViewState["objPerson"] = value; 
  12:        }
  13:    }
  14:  
  15:    public MemoryStream msStreamData
  16:    {
  17:        get
  18:        {
  19:            if (ViewState["msStreamData"] == null)
  20:                ViewState["msStreamData"] = new MemoryStream();
  21:            return (MemoryStream)ViewState["msStreamData"];
  22:        }
  23:        set
  24:        {
  25:            ViewState["msStreamData"] = value;
  26:        }
  27:    }
  28:    
  29:  
  30:    protected void Page_Load(object sender, EventArgs e)
  31:    {
  32:        if (!Page.IsPostBack)
  33:        {           
  34:            objPerson.Name = "Chirag";
  35:            objPerson.City = "Ahmedabad";
  36:            objPerson.Phone = "1234";
  37:            objPerson.PinCode = 3456;            
  38:        }
  39:    }
  40:  
  41:    protected void btnSerializeData_Click(object sender, EventArgs e)
  42:    {
  43:        msStreamData = CustomSerialization.SerializData(objPerson);
  44:    }
  45:  
  46:    protected void btnDeSerializeData_Click(object sender, EventArgs e)
  47:    {
  48:        Person objData = (Person)CustomSerialization.DeSerializData(msStreamData);
  49:    }

Fig - (3) Web Page code behind class


     One thing to note here is, the constructor of Person class will not called when the object is deserialize. 


Happy Programming !!!