Wednesday, October 31, 2012

Introduction to JavaScript Object Notation (JSON) in JavaScript and .NET


JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming LanguageStandard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.
JSON is built on two structures:
  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
These are universal data structures. Virtually all modern programming languages support them in one form or another. It makes sense that a data format that is interchangeable with programming languages also be based on these structures.
In JSON, they take on these forms:
An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma).

An array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).

value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.

string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. A character is represented as a single character string. A string is very much like a C or Java string.

number is very much like a C or Java number, except that the octal and hexadecimal formats are not used.

Whitespace can be inserted between any pair of tokens. Excepting a few encoding details, that completely describes the language.

Introduction to JavaScript Object Notation (JSON) in JavaScript and .NET


JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming LanguageStandard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.
JSON is built on two structures:
  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
These are universal data structures. Virtually all modern programming languages support them in one form or another. It makes sense that a data format that is interchangeable with programming languages also be based on these structures.
In JSON, they take on these forms:
An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma).

An array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).

value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.

string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. A character is represented as a single character string. A string is very much like a C or Java string.

number is very much like a C or Java number, except that the octal and hexadecimal formats are not used.

Whitespace can be inserted between any pair of tokens. Excepting a few encoding details, that completely describes the language.

Monday, October 29, 2012

Authenticate .NET Web Service with Custom SOAP Header in Sql Server

Authenticate .NET Web Service with Custom SOAP Header in Sql Server 

First step open Web Services 

Basically all the client needs to do is create an authentication object, fill out the username and password, then pass them to the web service object. The web service code is also pretty simple, the .NET framework lets you create custom SOAP headers by deriving from the SoapHeader class, so we wanted to add a username and password:


and create Authenticate Program .create and UserMaster Table 

Create Table UserMaster(UserId int identity ket(1,1),UserName varchar(20),UserPwd varchar(50))

then after we can create a web services in asp.net add + web services 


using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Data;
using System.Data.SqlClient;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
// [System.Web.Script.Services.ScriptService]
public class Service : System.Web.Services.WebService
{
    public MyHeader consumer;
    public SqlConnection con = null;
    public SqlCommand cmd = null;
    
    public Service () 
    {

        con = new SqlConnection("server=10.21.157.35;database=elekha;uid=elekha;pwd=iamdoingaccounts;");

    }

    [WebMethod]
    [SoapHeader("consumer", Required = true)]
    public string GetBalance() 
    {
        if (checkConsumer())
            return consumer.UserName + " had 9999999999999 credit";
        else
            return "Error in authentication";
    }
    private bool checkConsumer()
    {
        try
        {
            // In this method you can check the username and password 
            // with your database or something
            // You could also encrypt the password for more security
            
                con.Open();
            

            cmd = new SqlCommand("select * from UserMaster where UserName='"+consumer.UserName+"' and UserPwd='"+consumer.Password+"'", con);
            SqlDataReader rd = cmd.ExecuteReader();
            if (consumer != null)
            {
                if (rd.Read())
                {
                    return true;
                    
                }
                else return false;
            }
            else { return false; }
            con.Close();
            //if (consumer != null)
            //{
            //    if (consumer.UserName == "virendra" && consumer.Password == "1234")
            //        return true;
            //    else
            //        return false;
            //}
            //else
            //    return false;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    public class MyHeader : SoapHeader
    {
        public string UserName;
        public string Password;
    }
}
==========================================================
I should also mention that when I say SOAP headers, I actually mean the soap:Header element in a SOAP request, it has nothing to do with the HTTP headers sent with the request. The SOAP request looks something like:
then we can call the Web services in front end 

or .aspx Page


<asp:Panel ID="Panel1" runat="server" BackColor="#CCFFCC" Height="200px" 
        Width="300px">
        <br />
        <br />
        User_Name ::
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <br />
        <br />
        Password&nbsp; ::&nbsp;&nbsp;
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
        <br />
        <br />
        <br />
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <asp:Button ID="Button1" runat="server" BackColor="#99CCFF" 
            onclick="Button1_Click" Text="Button" />
    </asp:Panel>

We just get reference to the service and the SOAP header, assign the SOAP header properties, attach it with the SOAP message and then make our call to the web method.
then code behind page Or aspx.cs Page


protected void Button1_Click(object sender, EventArgs e)
    {
        MyWebServices.Service ws = new MyWebServices.Service();
        MyWebServices.MyHeader sh = new MyWebServices.MyHeader();
        sh.UserName = TextBox1.Text.ToString();
        sh.Password = TextBox2.Text.ToString();
        ws.MyHeaderValue = sh;
        Response.Write("<script>alert('"+ws.GetBalance()+"')</script>");
    }



=====================================


Thursday, October 25, 2012

Key codes of keydown and keyup events


keydown/keyup event.keyCode                    
Opera   MSIE  Firefox  Safari  Chrome    Key pressed
_________________________________________________________

  8       8       8       8       8      Backspace
  9       9       9       9       9      Tab
 13      13      13      13      13      Enter
 16      16      16      16      16      Shift
 17      17      17      17      17      Ctrl
 18      18      18      18      18      Alt
 19      19      19      19      19      Pause, Break
 20      20      20      20      20      CapsLock
 27      27      27      27      27      Esc
 32      32      32      32      32      Space
 33      33      33      33      33      Page Up
 34      34      34      34      34      Page Down
 35      35      35      35      35      End
 36      36      36      36      36      Home
 37      37      37      37      37      Left arrow
 38      38      38      38      38      Up arrow
 39      39      39      39      39      Right arrow
 40      40      40      40      40      Down arrow
         44      44      44      44      PrntScrn (see below)
 45      45      45      45      45      Insert
 46      46      46      46      46      Delete
 48-57   48-57   48-57   48-57   48-57   0 to 9
 65-90   65-90   65-90   65-90   65-90   A to Z  
112-123 112-123 112-123 112-123 112-123  F1 to F12 
144     144     144     144     144      NumLock
145     145     145     145     145      ScrollLock

188     188     188     188     188      , <
190     190     190     190     190      . >
191     191     191     191     191      / ?
192     192     192     192     192      ` ~
219     219     219     219     219      [ { (see below)
220     220     220     220     220      \ |
221     221     221     221     221      ] }
222     222     222     222     222      ' "
In most browsers, pressing the PrntScrn key fires keyup events only. 
Caution! Key code 219 also corresponds to the Win Key (Start) in Opera.
The following key codes differ across browsers:
      keydown/keyup event.keyCode                    
Opera   MSIE  Firefox  Safari  Chrome    Key pressed
_________________________________________________________ 

 59     186      59     186     186      ; :             
 61     187     107     187     187      = +             
109     189     109     189     189      - _             
219      91      91      91      91      WIN Key (Start) 
  0      93      93      93      93      WIN Menu        


Opera    All Others (NumLock On/Off)     Key pressed
_________________________________________________________

48/45       96/45                        Numpad 0 Ins    
49/35       97/35                        Numpad 1 End    
50/40       98/40                        Numpad 2 Down   
51/34       99/34                        Numpad 3 Pg Down
52/37      100/37                        Numpad 4 Left   
53/12      101/12                        Numpad 5        
54/39      102/39                        Numpad 6 Right  
55/36      103/36                        Numpad 7 Home   
56/38      104/38                        Numpad 8 Up     
57/33      105/33                        Numpad 9 Pg Up  
42/42      106/106                       Numpad *        
43/43      107/107                       Numpad +        
45/45      109/109   (45 is also Ins)    Numpad -        
78/46      110/46    (78 is also N)      Numpad . Del    
47/47      111/111                       Numpad / 

Regular expressions to validate file extension before file upload in javascript using asp.net

Validate file extension before file upload in javascript using asp.net by Regular expressions 

this article ,I will explain how to cheak or validate file in file upload control using javascript and regular expression to cheak file extension before file upload using Javascript in ASP.NET.


Here I have some of regular expressions to validate file upload. 

Regular expression to validate file formats for .mp3 or .MP3 or .mpeg or .MPEG or m3u or M3U

Re= /^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.mp3|.MP3|.mpeg|.MPEG|.m3u|.M3U)$/;

Regular expression to validate file formats for .doc or .docx

Re= /^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.doc|.docx|.DOC|.DOCX)$/;

Regular expression to validate file formats for .txt or .TXT

Re= /^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.txt|.TXT)$/;

Regular expression to validate file formats for .jpeg or .JPEG or .gif or .GIF or .png or .PNG

Re= /^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.jpeg|.JPEG|.gif|.GIF| .png|.PNG)$/;


Save/Upload files in folder and download files from folder in asp.net

Save / Upload files in folder and download files from folder in asp.net

In this article I will explain how to save/upload files in folder and download files from folder system when click on link in gridview using asp.net.

Generally we have different ways to save files like directly in our database or our project folder. If we save files in our database it will occupy more space so it will create problem for us after host website because host providers will provide limited space for us we can solve this problem by saving files in our project folder.

first we create table in sql Server.sql file

create table FileName(FileId int identity(1,1),FileName varchar(35),FilePath varchar(50))

then after we design Gridview .aspx Page


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="File_Upload_and_Downloan.aspx.cs" Inherits="File_Upload_and_Downloan" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Save and Download Files from file system</title>
    <style type="text/css">
.modalBackground
{
background-color: Gray;
filter: alpha(opacity=80);
opacity: 0.8;
z-index: 10000;
}

.GridviewDiv {font-size: 100%; font-family: 'Lucida Grande', 'Lucida Sans Unicode', Verdana, Arial, Helevetica, sans-serif; color: #303933;}
Table.Gridview{border:solid 1px #df5015;}
.Gridview th{color:#FFFFFF;border-right-color:#abb079;border-bottom-color:#abb079;padding:0.5em 0.5em 0.5em 0.5em;text-align:center}
.Gridview td{border-bottom-color:#f0f2da;border-right-color:#f0f2da;padding:0.5em 0.5em 0.5em 0.5em;}
.Gridview tr{color: Black; background-color: White; text-align:left}
:link,:visited { color: #DF4F13; text-decoration:none }

</style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
<asp:FileUpload ID="fileUpload1" runat="server" /><br />
<asp:Button ID="btnUpload" runat="server" Text="Upload" onclick="btnUpload_Click" />
</div>
<div>
<asp:GridView ID="gvDetails" CssClass="Gridview" runat="server" AutoGenerateColumns="false" DataKeyNames="FilePath">
<HeaderStyle BackColor="#df5015" />
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" />
<asp:BoundField DataField="FileName" HeaderText="FileName" />
<asp:TemplateField HeaderText="FilePath">
<ItemTemplate>
<asp:LinkButton ID="lnkDownload" runat="server" Text="Download" OnClick="lnkDownload_Click"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
    </form>
</body>
</html>

last in we create code behind .aspx.cs Page 

using System;
using System.Collections;
using System.Configuration;
using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Web.UI.WebControls;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class File_Upload_and_Downloan : System.Web.UI.Page
{
    SqlConnection con;
    public File_Upload_and_Downloan()
    {
        con = new SqlConnection("server=10.21.157.35;database=elekha;uid=elekha;pwd=iamdoingaccounts;");
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {
         BindGridviewData();
        }
    }
    // Bind Gridview Data
    private void BindGridviewData()
    {
        con.Open();
        SqlCommand cmd = new SqlCommand("select * from FilesTable", con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        con.Close();
        gvDetails.DataSource = ds;
        gvDetails.DataBind();
    }
    // Save files to Folder and files path in database
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        string filename = Path.GetFileName(fileUpload1.PostedFile.FileName);
        fileUpload1.SaveAs("C:\\temp\\" + filename);
        con.Open();
        SqlCommand cmd = new SqlCommand("insert into FilesTable(FileName,FilePath) values(@Name,@Path)", con);
        cmd.Parameters.AddWithValue("@Name", filename);
        cmd.Parameters.AddWithValue("@Path", "C:\\temp\\" + filename);
        cmd.ExecuteNonQuery();
        con.Close();
        BindGridviewData();
    }
    // This button click event is used to download files from gridview
    protected void lnkDownload_Click(object sender, EventArgs e)
    {
        LinkButton lnkbtn = sender as LinkButton;
        GridViewRow gvrow = lnkbtn.NamingContainer as GridViewRow;
        string filePath = gvDetails.DataKeys[gvrow.RowIndex].Value.ToString();
        Response.ContentType = "image/jpg";
        Response.AddHeader("Content-Disposition", "attachment;filename=\"" + filePath + "\"");
        Response.TransmitFile(filePath);
        Response.End();
    }
}


thank

Tuesday, October 23, 2012

Error Handling in SQL Server 2005 Stored Procedure using Try Catch Block


Error Handling in SQL Server 2005 Stored Procedure using Try Catch Block


I am fascinated by the easy and safer way SQL Server 2005 provides for error handling. Traditionally we used @@ERROR for this purpose, along the BEGIN TRANSACTION, COMMIT TRANSACTION, ROLLBACK TRANSACTION blocks. Below is one example.
Traditional Error Handling in SQL Server 2000/2005
ALTER PROCEDURE dbo.DeleteFromMyTable
AS
/* SET NOCOUNT ON */
BEGIN TRANSACTION
DELETE FROM myTable1 WHERE myColumn='myColumnValue'--delete transaction1
IF @@ERROR>0 --some error occured
BEGIN
ROLLBACK TRANSACTION 
RETURN
END
ELSE --no error has occured till now, move ahead (do some more transactions)
BEGIN
BEGIN TRANSACTION
DELETE FROM myTable2 WHERE myColumn='myColumnValue'--delete transaction2
IF @@ERROR>0 --some error occured at this point
BEGIN
ROLLBACK TRANSACTION 
--this rollbacks previous delete action also
RETURN
END
ELSE 
--both the delete transactions successful !
BEGIN
--so commit the transactions
COMMIT TRANSACTION
RETURN
END
END
All these stuffs work (perfectly!). But oh! SQL Server 2005! There exists more easy and interesting way. If you are an asp.net programmer or the one who works with front end, there is exactly like what a developer faces with error handling. Guess what? You are right, it is Try..Catch block. Yes Try..Catch block has been introduced in SQL Server 2005, and it provides better way to performing transactions like above in SQL Server database.
Latest Error Handling in SQL Server 2005
ALTER PROCEDURE dbo.DeleteFromMyTable
AS
/* SET NOCOUNT ON */
BEGIN TRY
BEGIN TRANSACTION
DELETE FROM myTable1 WHERE myColumn='myColumnValue'--delete transaction1
DELETE FROM myTable2 WHERE myColumn='myColumnValue'--delete transaction2
COMMIT TRANSACTION
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0 --some error has occurred
ROLLBACK TRAN --so rollback all transactions
--you raise error or fill output variable here
--for front end reference in your asp.net webpage
END CATCH 
See how easy and better way? I found this Try..Catch has made sql programming like front end programming. Happy Programming!

Monday, October 22, 2012

Introducing Serialization in C#.NET

Introducing Serialization in .NET

he serialization is process of convert an object type into stream of bytes.
There are several types

1) Binary serialization
2) SOAP serialization
3) XML serialization
4) Custom serialization


Serialization is the process of converting an object into a stream of bytes. Deserialization is the opposite process of creating an object from a stream of bytes. Serialization/Deserialization is mostly used to transport objects (e.g. during remoting), or to persist objects (e.g. to a file or database).Serialization can be defined as the process of storing the state of an object to a storage medium. During this process, the public and private fields of the object and the name of the class, including the assembly containing the class, are converted to a stream of bytes, which is then written to a data stream. When the object is subsequently deserialized, an exact clone of the original object is created.

 Binary serialization preserves type fidelity, which is useful for preserving the state of an object between different invocations of an application. For example, you can share an object between different applications by serializing it to the clipboard. You can serialize an object to a stream, disk, memory, over the network, and so forth. Remoting uses serialization to pass objects "by value" from one computer or application domain to another. 

XML serialization serializes only public properties and fields and does not preserve type fidelity. This is useful when you want to provide or consume data without restricting the application that uses the data. Because XML is an open standard, it is an attractive choice for sharing data across the Web. SOAP is an open standard, which makes it an attractive choice. There are two separate mechanisms provided by the .NET class library - XmlSerializer and SoapFormatter/BinaryFormatter. Microsoft uses XmlSerializer for Web Services, and uses SoapFormatter/BinaryFormatter for remoting. Both are available for use in your own code.




Serialization is the process of saving the state of an object in a persistent storage media by converting the object to a linear stream of bytes.  The object can be persisted to a file, a database or even in the memory.  The reverse process of serialization is known as de-serialization and enables us to re-construct the object from the previously serialized instance of the same in the persistent or non-persistent storage media.
Serialization in .NET is provided by the System.Runtime.Serialization namespace.  This namespace contains an interface called IFormatter which in turn contains the methods Serialize and De-serialize that can be used to save and load data to and from a stream.  In order to implement serialization in .NET, we basically require a stream and a formatter.  While the stream acts as a container for the serialized object(s), the formatter is used to serialize these objects onto the stream.
The basic advantage of serialization is the ability of an object to be serialized into a persistent or a non-persistent storage media and then reconstructing the same object if required at a later point of time by de-serializing the object.  Remoting and Web Services depend heavily on Serialization and De-serialization.  Refer to the figure below.
The following are the basic advantages of serialization:
·         Facilitate the transportation of an object through a network
·         Create a clone of an object
The primary disadvantage of serialization can be attributed to the resource overhead (both the CPU and the IO devices) that is involved in serializing and de-serializing the data and the latency issues that are involved for transmitting the data over the network.  Further, serialization is quite slow.  Moreover, XML serialization is insecure, consumes a lot of space on the disk and it works on public members and public classes and not on the private or internal classes.  Therefore, it compels the developer to allow the class to be accessed to the outside world.


The Serializable Attribute


In order for a class to be serializable, it must have the attribute SerializableAttribute set and all its members must also be serializable, except if they are ignored with the attribute NonSerializedAttribute.  However, the private and public members of a class are always serialized by default.  The SerializationAttribute is only used for the binary serialization.  The code snippet below shows the usage of SerializableAttribute.
Listing1:
[Serializable]
public class Employee
{
   public int empCode;
   public string empName;
}
Note the Serializable attribute that is specified at the beginning of the class in the code listing above.  The SerializableAttribute is useful for situations where the object has to be transported to other application domains.  It needs to be applied even irrespective of whether the class implements the ISerializable interface.  If this attribute is not set in that case, then when we try to serialize an object the CLR throws a SerializationException.
Types of Serialization


Serialization can be of the following types:
·         Binary Serialization
·         SOAP Serialization
·         XML Serialization
·         Custom Serialization
All these types of serialization are explained in details in the sections that follow.
Binary Serialization
Binary serialization is a mechanism which writes the data to the output stream such that it can be used to re-construct the object automatically.  The term binary in its name implies that the necessary information that is required to create an exact binary copy of the object is saved onto the storage media.  A notable difference between Binary serialization and XML serialization is that Binary serialization preserves instance identity while XML serialization does not.  In other words, in Binary serialization the entire object state is saved while in XML serialization only some of the object data is saved.  Binary serialization can handle graphs with multiple references to the same object; XML serialization will turn each reference into a reference to a unique object.  The following code listing shows how we can implement binary serialization.
Listing 2:
public void BinarySerialize(string filename, Employee emp)
{
  FileStream fileStreamObject;
  try
  {
    fileStreamObject = new FileStream(filename, FileMode.Create);
    BinaryFormatter binaryFormatter = new BinaryFormatter();
    binaryFormatter.Serialize(fileStreamObject, emp);
  }
  finally
  {
    fileStreamObject.Close();
  }
}
The following code listing shows how we can implement binary de-serialization.
Listing 3:
public static object BinaryDeserialize(string filename)
{
  FileStream fileStreamObject;
 
  try
  {
    fileStreamObject = new FileStream(filename, FileMode.Open);
    BinaryFormatter binaryFormatter = new BinaryFormatter();
    return (binaryFormatter.Deserialize(fileStreamObject));
  }
  finally
  {
    fileStreamObject.Close();
  }
}
Advantages and Disadvantages of Binary Serialization


One of the major advantages of using Binary Serialization in the managed environment is that the object can be de-serialized from the same data you serialized it to.  Besides, the other advantage of Binary Serialization is enhanced performance as it is faster and even more powerful in the sense that it provides support for complex objects, read only properties and even circular references.  However, the downside to this is that it is not easily portable to another platform.
SOAP Serialization


The SOAP protocol is ideal for communicating between applications that use heterogeneous architectures.  In order to use SOAP serialization in .NET we have to add a reference to System.Runtime.Serialization.Formatters.Soap in the application.  The basic advantage of SOAP serialization is portability.  The SoapFormatter serializes objects into SOAP messages or parses SOAP messages and extracts serialized objects from the message.  The following code listing shows how we can implement serialization using the SOAP protocol.
Listing 4:
public void SOAPSerialize(string filename,Employee employeeObject)
{
  FileStream fileStreamObject = new FileStream(filename, FileMode.Create);
  SoapFormatter soapFormatter = new SoapFormatter();
  soapFormatter.Serialize(fileStreamObject, employeeObject);
  fileStreamObject.Close();
}
The following code listing shows how we can implement de-serialization using the SOAP protocol.
Listing 5:
public static object SOAPDeserialize(string filename)
{
  FileStream fileStreamObject = new FileStream(filename, FileMode.Open);
  SoapFormatter soapFormatter = new SoapFormatter();
  object obj = (object)soapFormatter.Deserialize(fileStreamObject);
  fileStreamObject.Close();
  return obj;
}
XML Serialization


According to MSDN, "XML serialization converts (serializes) the public fields and properties of an object or the parameters and returns values of methods, into an XML stream that conforms to a specific XML Schema definition language (XSD) document. XML serialization results in strongly typed classes with public properties and fields that are converted to a serial format (in this case, XML) for storage or transport. Because XML is an open standard, the XML stream can be processed by any application, as needed, regardless of platform."  Implementing XML Serialization in .Net is quite simple.  The basic class that we need to use is the XmlSerializer for both serialization and de-serialization.  The Web Services use the SOAP protocol for communication and the return types and the parameters are all serialized using the XmlSerializer class.  XML Serialization is however, much slower compared to Binary serialization.  We can set a property as an XML attribute as shown in the code listing below.
Listing 6:
[XmlAttribute("empName")]
public string EmpName
{
  get
  {
    return empName;
  }
  set
  {
    empName = value;
  }
}
The following code listing shows how we can implement XML serialization.
Listing 7:
public void XMLSerialize(Employee emp, String filename)
{
  XmlSerializer serializer = null;
  FileStream stream = null;
  try
  {
    serializer = new XmlSerializer(typeof(Employee));
    stream = new FileStream(filename, FileMode.Create, FileAccess.Write);
    serializer.Serialize(stream, emp);
  }
  finally
  {
    if (stream != null)
      stream.Close();
  }
}
The following code listing shows how we can implement XML de-serialization.
Listing 8:
public static Employee XMLDeserialize(String filename)
{
  XmlSerializer serializer = null;
  FileStream stream = null;
  Employee emp = new Employee();
  try
  {
    serializer = new XmlSerializer(typeof(Employee));
    stream = new FileStream(filename, FileMode.Open);
    emp = (Employee)serializer.Deserialize(stream);
  }
  finally
  {
    if (stream != null)
      stream.Close();
  }
  return emp;
}
Advantages of XML Serialization


The advantages of XML Serialization are as follows:
·         XML based
·         Support for cross platforms
·         Easily readable and editable
Working with Formatters


A formatter is used to determine the serialization format for objects.  In other words, it is used to control the serialization of an object to and from a stream.  They are the objects that are used to encode and serialize data into an appropriate format before they are transmitted over the network.  They expose an interface called the IFormatter interface.  IFormatter's significant methods are Serialize and De-serialize which perform the actual serialization and de-serialization. There are two formatter classes provided within .NET, the BinaryFormatter and the SoapFormatter.  Both these classes extend the IFormatter interface.
The Binary Formatter
The Binary formatter provides support for serialization using binary encoding.  The BinaryFormater class is responsible for binary serialization and is used commonly in .NET's Remoting technology.  This class is not appropriate when the data is supposed to be transmitted through a firewall.
The SOAP Formatter
The SOAP formatter provides formatting that can be used to serialize objects using the SOAP protocol.  It is used to create a Soap envelop and it uses an object graph to generate the result.  It is responsible for serializing objects into SOAP messages or parsing the SOAP messages and extracting these serialized objects from the SOAP messages.  SOAP formatters in .NET are widely used by the Web Services.
Custom Serialization


In some cases, the default serialization techniques provided by .NET may not be sufficient in real life.  This is when we require implementing custom serialization.  It is possible to implement custom serialization in .NET by implementing the ISerializable interface.  This interface allows an object to take control of its own serialization and de-serialization process.  It gives us a great deal of flexibility in the way we can save and restore objects.  The ISerializable interface consists of a single method, GetObjectData, which accepts two parameters.
The SerializationInfo class serves as the container for all the data we want to serialize.  The AddValue method is called to add the objects we want to serialize to this container.  The implementing class needs to have the GetObjectData method and a special constructor which is used by the common language runtime during the process of de-serialization.  The following code listing shows how we can implement Custom Serialization.
Listing 9:
public class Employee: ISerializable
{
  private int empCode;
  private string empName;
  protected Employee(SerializationInfo serializationInfo, StreamingContext
    streamingContext)
  {
    this.empCode = serializationInfo.GetInt32("empCode");
    this.empName = serializationInfo.GetString("empName");
  }
  public void ISerializable.GetObjectData(SerializationInfo serializationInfo,
    StreamingContext streamingContext)
  {
    serializationInfo.AddValue("empCode"this.empCode);
    serializationInfo.AddValue("empName"this.empName);
  }
}
The following listing shows how we can implement Custom Serialization on a Custom Collection class that extends the CollectionBase class of the System.Collections namespace.
Listing 10
[Serializable]
public class EmployeeCollection: System.Collections.CollectionBase,
  ISerializable
{
  private int empCode;
 
  public EmployeeCollection()
  {
    empCode = 1;
  }
 
  protected EmployeeCollection(SerializationInfo info, StreamingContext context)
    : base(info, context)
  {
    empCode = info.GetInt32("empCode");
  }
 
  public virtual void GetObjectData(SerializationInfo info, StreamingContext
    context)
  {
    base.GetObjectData(info, context);
    info.AddValue("empCode", empCode);
  }
}
Points to remember


This section deals with some of the points that we have already covered in this article and some others that we have not, but are still very important and relate to the serialization and de-serialization concepts of .NET.
When you apply the Serializable custom attribute to a type, all instance fields of the class (public, private, protected, etc.) are serialized automatically.
XmlSerializer does not use the ISerializable interface; rather, it uses the IXmlSerializable interface.  The XmlSerializer class can only serialize the public properties of the class, whereas the BinaryFormatter class can serialize private fields using the ISerializable interface.
The Serializable attribute is a must for making a class serializable irrespective of whether we have implemented the ISerializable interface in this class.  When we serialize a class, the objects of the references to other classes that are contained in this class are also serialized if they are marked as serializable.  All members are serialized, including public, private or protected members. Furthermore, even circular references are supported by binary serialization.  Note that read only properties are not serialized except the collection class objects.  However, the read only properties can be serialized using binary serialization.
If we do not require serializing a particular property of a class when using an XmlSerializer, we have to mark the property with the custom attribute XmlIgnoreAttribute.  When using a SoapFormatter we have to use the SoapIgnoreAttribute instead.  The XmlSerializer generates an in-memory assembly optimized for each type since the initial invocation to a Web Service always takes so much time.  To combat this, we can use the sgen.exe tool to pre-generate the serialization assembly.
References

Conclusion


Serialization is the process of storing an object, including all of its members, to a persistent or a non-persistent storage media by converting the object into a linear stream of data.  De-serialization is the process of restoring an object's values from the said stream.  The advantage of serialization is to save the state of an object in order to have the ability to recreate the same object at a later point of time if and when it is required.  The .NET Framework provides a strong support for serialization of objects.  The .NET Framework provides a unified standard for serializing and de-serializing objects for building distributed heterogeneous systems.  This article has explored Serialization and De-serialization and the various types of Serialization concepts with code examples wherever necessary.  It has discussed what Custom Serialization is and how to implement it.  However, I would recommend not using serialization unless it is absolutely necessary due to the drawbacks that I have already explained in this article.  I hope that the readers will find this article quite useful and post their comments and suggestions on this article. Happy reading!