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

Friday, April 04, 2008

Using CASE with ORDER BY in SQL Server

        Today I came to know that we can use CASE with ORDER BY clause.  Its a nice functionality which helps you to avoid UNIOUN when you have to display the records in some specific order and still you need to sort them.

     As shown below I have created an Employee table with ID (Primary key),Name, Address and Phone columns.

   1: SET ANSI_NULLS ON
   2: GO
   3: SET QUOTED_IDENTIFIER ON
   4: GO
   5: CREATE TABLE [dbo].[Employee](
   6:     [Id] [int] IDENTITY(1,1) NOT NULL,
   7:     [Name] [nvarchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
   8:     [Address] [nvarchar](100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
   9:     [Phone] [nvarchar](15) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
  10:  CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED 
  11: (
  12:     [Id] ASC
  13: )WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
  14: ) ON [PRIMARY]

Fig - (1) Employee  table.


         I have also inserted some temporary data as shown below,



   1: INSERT INTO Employee VALUES ('Chirag Darji','Ahmedabad','123456789')
   2: INSERT INTO Employee VALUES ('Dipak Patel','USA','123456789')
   3: INSERT INTO Employee VALUES ('Shailesh Patel','USA','123456789')
   4: INSERT INTO Employee VALUES ('Piyush Vadher','Gujarat','123456789')
   5: INSERT INTO Employee VALUES ('Mihir Panchal','Gujarat','123456789')
   6: INSERT INTO Employee VALUES ('Vishal Patel','Ahmedabad','123456789')

 Fig - (2)  Insert Statements


     Now consider that have to display the records of employee table order by Address however you want first it should display all the records with USA in address field then Ahmedabad then Gujarat and after that all. Here is the output that we want,



   1: 2    Dipak Patel          USA       123456789
   2: 3    Shailesh Patel       USA       123456789
   3: 6    Vishal Patel         Ahmedabad 123456789
   4: 1    Chirag Darji         Ahmedabad 123456789
   5: 4    Piyush Vadher        Gujarat   123456789
   6: 5    Mihir Panchal        Gujarat   123456789
   7: 7    Mayank Champaneri    Palitana  123456789
   8: 8    Manish Pansinita     Sanand    123456789
   9: 9    Manish Pansinita     Baroda    123456789

Fig - (3)  Result


      Below is the query that displays the result as shown in fig - (3),



   1: SELECT * FROM Employee ORDER BY
   2: CASE WHEN Address = 'USA' THEN 1
   3: WHEN Address = 'Ahmedabad' THEN 2
   4: WHEN Address = 'Gujarat' THEN 3
   5: ELSE 4
   6: END

Happy Programming !!!

Tuesday, April 01, 2008

ASP.NET Internals: Viewstate and Page Life Cycle

         During the free time today, I was looking for some articles on ASP.NET internals. I found an awesome article about page life cycle and viewstate. Author has explained a viewstate in very detail and simple manner. You can read the article here.

Happy Programming!!

Monday, March 17, 2008

IDENT_CURRENT, @@IDENTITY and SCOPE_IDENTITY()

         A very common question during the interview is to provide difference between IDENT_CURRENT, @@IDENTITY and SCOPE_IDENTITY().  All are used to retrieve the value of identity column after DML statement execution. All three functions return last-generated identity values. However, the scope and session on which last is defined in each of these functions differ:

  • IDENT_CURRENT returns the last identity value generated for a specific table in any session and any scope.
  • @@IDENTITY returns the last identity value generated for any table in the current session, across all scopes.
  • SCOPE_IDENTITY returns the last identity value generated for any table in the current session and the current scope.

The IDENT_CURRENT function returns NULL when the function is invoked on an empty table or on a table that has no identity column.
       I found a good article and an example which explains the difference very effectively. Here is the link for that.

Happy Programming !!!

Wednesday, March 12, 2008

CLR Stored Procedure in SQL Server 2005

       As we all know SQL Server 2005 has CLR integrated with it. This means one can write a code in manage application and execute it SQL Server. I read about this since Microsoft has launched SQL Server 2005, however I have never used it practically till last week.

Here is a complete article.

Friday, February 29, 2008

Service Unavailable error while connecting to team foundation server.

         You may receive "Service Unavailable" error while connecting to Team Foundation Server(TFS). I was getting this error from yesterday whenever I was trying to connect to TFS. Finally today I found the reason and solution. I had changed the password of Administrator user which I had used to configure TFS Application Pool. This has stopped the application pool as the account which is running the TFS Application Pool has old password. So one has to change the password in TFS Application pool. To change password in application pool, click Start - Run and type inetmgr. This will open IIS. Now select the TFS application pool.

           Right click on TFS Apppool and select properties. Select Identity tab. Here you have to enter a new password for this account and click ok. Restart the IIS and try to connect to TFS. This time you will not get the "Service Unavailable" error.

       You will get this same error if you have deleted the user which is used to configure TFS Application pool. Here is the good article from Microsoft. 

Happy Programming !!

Friday, February 15, 2008

The media set has 2 media families but only 1 are provided.

      You get this error while restoring the database backup file in SQL Server 2005. This is because when you took the backup your backup file is divided in more than one part and at the time of restoring the database you have not added all the parts.

       Lets do this practically so that you can have better idea. Take the backup of any database you have. To take the backup right click on database and select the task and click on backup. 

         Once you click on Backup you have to select the location for .back file on database. If there are two paths in path selection box as shown in image below, the backup file is generated in two parts and saved at two different locations.

        So in this case, we have two backup files generated for selected database. Now at the time of restoring if you are assigning only one file and try to restore the database, you will get "The media set has 2 media families but only 1 are provided." error.

        To solve this issue you have to add all the files (in our case two files) in file selection box. Once you select all the backup files and click on restore, the database will restore successfully.

For more detail check here.

Happy Programming !!

Friday, February 08, 2008

Query to find all the tables and columns in selected database.

         As a developer, it is really important for us to understand database design and underlying tables used in application. Sometime we do not have direct access to database server so that we can not open the server console and look in to the database.

         In this case we can take help of SysObjects, SysColumns, SysTypes tables of SQL Server 2005. These tables stores the information about each tables and columns and their data types. Using this tables you can write the query to find out all the tables and columns in selected database. Below is the query that gives you all the table and columns for those tables with data types and length.

 

   1: SELECT 
   2:     SysObjects.[Name] as TableName,
   3:     SysColumns.[Name] as ColumnName,
   4:     SysTypes.[Name] As DataType,
   5:     SysColumns.[Length] As Length
   6: FROM
   7:     SysObjects INNER JOIN SysColumns
   8:     ON SysObjects.[Id] = SysColumns.[Id]
   9:     INNER JOIN SysTypes 
  10:     ON SysTypes.[xtype] = SysColumns.[xtype]
  11: WHERE
  12:     SysObjects.[type] = 'U'
  13: ORDER BY 
  14:     SysObjects.[Name]

Fig - (1) Query to find all the tables and columns for those tables.


 


           "Type" columns of SysObjects table represent the different objects available in database (like Table,Trigger,Stored Procedures etc.). Below list explains the different values of "Type" columns.



   1: C = CHECK constraint 
   2: D = Default or DEFAULT constraint
   3: F = FOREIGN KEY constraint 
   4: FN = Scalar function
   5: IF = Inlined table-function
   6: K = PRIMARY KEY or UNIQUE constraint 
   7: L = Log
   8: P = Stored procedure
   9: R = Rule
  10: RF = Replication filter stored procedure
  11: S = System table 
  12: TF = Table function
  13: TR = Trigger
  14: U = User table
  15: V = View
  16: X = Extended stored procedure

Fig - (2) Explanation of different values of "Type" columns in SysObjects table.


 


          For more detail refer SysObjects and SysColumns.  and So in fig - (1) query uses [type] = 'U'. This means query displays al the user tables. You can change the condition in WHERE clause to get different objects. The query shown below displays all the triggers in selected database.


 



   1: SELECT 
   2:     b.[Name] as [Table Name],
   3:     a.[Name] as [Trigger Name],
   4:     a.[crdate] as [Created Date] 
   5: FROM 
   6:     SysObjects a 
   7:     INNER JOIN Sysobjects b
   8:     ON a.[parent_obj] = b.[id]
   9: WHERE 
  10:     a.[type] = 'TR'
  11: ORDER BY 
  12:     b.[Name]

Fig - (3) Query to display all the Triggers for selected database.


 


Happy Programming !!

Monday, January 28, 2008

Internet explorer was not able to open the Internet site. The requested site is either unavailable or can not be found.Please try again later.

       You may receive this error when you write a code that allows user to download a file instead of opening it in IE other browser. In my code I have to show Open/Save dialog for PDF file. I wrote the following code.

   1: Response.Clear();
   2: Response.Buffer = true;
   3: Response.ContentType = "application/pdf";
   4: Response.Cache.SetCacheability(HttpCacheability.NoCache);
   5: Response.AddHeader("content-disposition", "attachment;filename=test.pdf");
   6: Response.Charset = "";
   7: Response.BinaryWrite(bytContent);
   8: Response.End();

 


         When I ran the code I was getting error as "Internet explorer was not able to open the Internet site. The requested site is either unavailable or can not be found.Please try again later."


          To solve this error I just removed line 4 "SetCacheability" and everything works fine. After that I search on net to find the reason and I found really good article here.


          While surfing I found another approach to achieve this an I found it better that I used here. Rick Astral has shown that approach here.


 


Happy Programming !!