Sunday, June 23, 2013

SOAP Serialization in C#

SOAP Serialization

SOAP serialization uses SOAP encoding to produce compact serialization for uses such as web service.

Example

In this example we take an employee class. It has two attribute EmpId and EmpName.

using System;
using System.Runtime.Serialization;

namespace Example_Serialization
{
    [Serializable] 
    public class Employee : ISerializable
    {
        public int EmpId { get; set; }
        public string EmpName { get; set; }
        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue("EmpId", EmpId);
            info.AddValue("EmpName", EmpName);           
        }
        public Employee(SerializationInfo info, StreamingContext context)
        {
            EmpId = (int)info.GetValue("EmpId", typeof(int));
            EmpName = (string)info.GetValue("EmpName", typeof(string));
        }

        public Employee()
        {
        }
    }
}  
In the above class  [Serializable] attribute should be applied. Serializable attribute tell compiler that all public and private properties should be serialized. If we don't want to serialize some properties then simply apply [NonSerialized] attribute. Some times we need more customization, in that case we implements ISerializable interface. It override serializations process. It has a method  named GetObjectData which actually serialize the object. And for desrialization we use a constructor where we write our deserialization code.
Now we can serialize and deserialize our employee class. Below code snippet will explain how to serialize our employee class using SOAP serialization.

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Soap;


namespace Example_Serialization
{  
    class SOAPSerialization
    {      
        public void SerializeObj()
        {
            Console.WriteLine("SOAP Serialization starting");
            Employee emp = new Employee() { EmpId = 1, EmpName = "Hriday Ranjan Dutta" };
            Stream stream = File.Open("SOAPemployee.txt", FileMode.OpenOrCreate);
            SoapFormatter bformatter = new SoapFormatter();
            bformatter.Serialize(stream, emp);
            stream.Close();
            Console.WriteLine("SOAP Serialization done");
            Console.ReadLine();
        }
        public void DeserializeObj()
        {
            Console.WriteLine("SOAP Deserialization starting");
            Stream stream = File.Open("SOAPemployee.txt", FileMode.Open);
            SoapFormatter bformatter = new SoapFormatter();
            Employee emp = (Employee)bformatter.Deserialize(stream);
            stream.Close();
            Console.WriteLine("Employee ID : {0}, Employee Name : {1}",emp.EmpId.ToString(),emp.EmpName);
            Console.WriteLine("SOAP Deserialization done");
            Console.ReadLine();
        }

      
    }
}

Output Serialized file

<SOAP-ENV:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:clr="http://schemas.microsoft.com/soap/encoding/clr/1.0" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body>
<a1:Employee id="ref-1" xmlns:a1="http://schemas.microsoft.com/clr/nsassem/Example_Serialization/Example_Serialization%2C%20Version%3D1.0.0.0%2C%20Culture%3Dneutral%2C%20PublicKeyToken%3Dnull">
<_x003C_EmpId_x003E_k__BackingField>1</_x003C_EmpId_x003E_k__BackingField>
<_x003C_EmpName_x003E_k__BackingField id="ref-3">Hriday Ranjan Dutta</_x003C_EmpName_x003E_k__BackingField>
</a1:Employee>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
 

 

Saturday, June 22, 2013

Binary Serialization in C#

Binary Serialization

Binary serialization uses binary encoding to produce compact serialization for uses such as storage or socket-based network streams. It is also known as deep serialization. Because it serialize every thing of an object.

Example

In this example we take an employee class. It has two attribute EmpId and EmpName.


using System;
using System.Runtime.Serialization;

namespace Example_Serialization
{
    [Serializable] 
    public class Employee : ISerializable
    {
        public int EmpId { get; set; }
        public string EmpName { get; set; }
        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue("EmpId", EmpId);
            info.AddValue("EmpName", EmpName);           
        }
        public Employee(SerializationInfo info, StreamingContext context)
        {
            EmpId = (int)info.GetValue("EmpId", typeof(int));
            EmpName = (string)info.GetValue("EmpName", typeof(string));
        }

        public Employee()
        {
        }
    }
}  

In the above class  [Serializable] attribute should be applied. Serializable attribute tell compiler that all public and private properties should be serialized. If we don't want to serialize some properties then simply apply [NonSerialized] attribute. Some times we need more customization, in that case we implements ISerializable interface. It override serializations process. It has a method  named GetObjectData which actually serialize the object. And for desrialization we use a constructor where we write our deserialization code.

Now we can serialize and deserialize our employee class. Below code snippet will explain how to serialize our employee class using binary serialization.

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace Example_Serialization
{   
    class BinarySerialization
    {      
        public void SerializeObj()
        {
            Console.WriteLine("Binary Serialization starting");
            Employee emp = new Employee() { EmpId = 1, EmpName = "Hriday Ranjan Dutta" };
            Stream stream = File.Open("Binaryemployee.txt", FileMode.OpenOrCreate);
            BinaryFormatter bformatter = new BinaryFormatter();
            bformatter.Serialize(stream, emp);
            stream.Close();
            Console.WriteLine("Binary Serialization done");
            Console.ReadLine();
        }
        public void DeserializeObj()
        {
            Console.WriteLine("Binary Deserialization starting");
            Stream stream = File.Open("Binaryemployee.txt", FileMode.Open);
            BinaryFormatter bformatter = new BinaryFormatter();
            Employee emp = (Employee)bformatter.Deserialize(stream);
            stream.Close();
            Console.WriteLine("Employee ID : {0}, Employee Name : {1}",emp.EmpId.ToString(),emp.EmpName);
            Console.WriteLine("Binary Deserialization done");
            Console.ReadLine();
        }       
    }
}


Output Serialized file

 ÿÿÿÿ           LExample_Serialization, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null    Example_Serialization.Employee    <EmpId>k__BackingField <EmpName>k__BackingField    Hriday Ranjan Dutta

Friday, June 21, 2013

XML Serialization in C#

XML Serialization

XML Serialization serialize only public fields, properties of an object and parameters and return value of a method. That is why it is called Shallow Serialization.  XML serialization results in strongly typed classes with public properties and fields that are converted to XML. System.Xml.Serialization has all the classes and method need for XML serialization.
 

Example

The bellow example serialize a string array using XML Serialization and store it to a XML file. And again deserialize  from that xml file to a string array.



using System;
using System.IO;
using System.Xml.Serialization;
namespace Example_Serialization
{
    class Program
    {
        static void Main(string[] args)
        {

            Console.WriteLine("Serializing a string array and store it in country.xml");
            string[] country = new string[] { "India", "USA", "UK", "Australia" };
            XmlSerializer serialize = new XmlSerializer(typeof(string[]));
            StreamWriter writer = new StreamWriter("country.xml");
            serialize.Serialize(writer, country);
            writer.Close();

            Console.WriteLine("Deserializing a string array from country.xml");
            country = null;
            using (Stream streamload = new FileStream("Country.xml", FileMode.Open))
            {
                country = (string[])serialize.Deserialize(streamload);
                foreach (var str in country)
                {
                    Console.WriteLine("{0}", str);
                }
            }
            Console.ReadKey();
        }
    }
}
 

Serialization and Deserialization in C#

Serialization is a process of converting object into stream of bytes. And deserialization is a process of getting object back from serialization form.

According to MSDN "Serialization is the process of converting an object into a stream of bytes in order to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization."

The bellow figure shows how serialization works.


















Deserialization is just opposite of serialization. It is the mechanism to getting object back from stream of bytes. 



















There are three types of serialization mechanism available in C#.


  • XML Serialization
  • Binary Serialization
  • Soap Serialization


XML Serialization

XML Serialization serialize only public fields, properties of an object and parameters and return value of a method. That is why it is called Shallow Serialization.  XML serialization results in strongly typed classes with public properties and fields that are converted to XML. System.Xml.Serialization has all the classes and method need for XML serialization. more

Binary Serialization

Binary serialization uses binary encoding to produce compact serialization for uses such as storage or socket-based network streams. It is also known as deep serialization. Because it serialize every thing of an object. more

SOAP Serialization

SOAP serialization serialize an object into XML stream with SOAP standard. This serialization is used to transmit data over network. Most common area where SOAP serialization is used is web services. more



Download

You can download examples and source code from here.

Wednesday, June 19, 2013

How to send email using C#

C# provides many built in exiting features to make developer life easy. SmtpClient class is one of them. SmtpClient has every thing that we need to send email from our application.

Namespace : System.Net

The following program illustrate how to send email using SmtpClient from our Asp.Net application.

SmtpClient s = new SmtpClient();
s.Host = "smtp host"; // here enter smtp host, for google = smtp.gmail.com
s.Port = 25;
s.UseDefaultCredentials = false;
MailMessage m = new MailMessage();
m.To.Add("xxx@xxx.com"); // enter reciepent email address
m.From = new MailAddress("xxx@xxx.com"); // enter sender email address
m.Subject = "xxxx"; // mail subject
m.Body = "xxxxxxxxx"; // mail body
m.Priority = MailPriority.High;
s.Credentials = new NetworkCredential("userid", "password"); // for gmail user id is your email address, password is your gmail password.
//s.EnableSsl = true; // for gmail remove the comment
s.DeliveryMethod = SmtpDeliveryMethod.Network;
try
{
            s.Send(m);
            Response.Write("done")
}
catch (Exception ex)
{
            Response.Write(ex.Message.ToString());
}
 


Some times the above code gives an error "Require authenticaton" after giving all correct details. It means your smtp server require mail body level authentication. In such case use the following code



Namespace : System.Web.Mail

MailMessage Message = new MailMessage();
Message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
Message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", "xxx@xxx.xxx"); // user id (email)
Message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", "xxx"); // password
Message.To ="xxx@xxx.xxx";
Message.From ="xxx@xxx.xxx";
Message.Subject = "xxx";
Message.Body = "XXXXXXXXXXX";
try
{
            SmtpMail.SmtpServer = "xxx.xxx.xxx.xxx";
            SmtpMail.Send(Message);
}
catch (System.Web.HttpException ehttp)
{
            Response.Write(ehttp.Message.ToString());
}

Monday, June 17, 2013

Abstraction and Encapsulation

Definition

Encapsulation is the process of hiding irrelevant data from the user. Or in other word encapsulation is a process of hiding all the internal details of an object from the outside world.

Abstraction is just opposite of encapsulation. Abstraction is mechanism to show only relevant data to user. Hence it is a process of representation of only essential features of an object.



Learning

“Difference  between Abstraction vs Encapsulation” is a wrong question. Oops is not playing an IPL T20 match. It should be “What is Abstraction and Encapsulation ?” Simply Encapsulation is a process of hiding data into  object. In other words wrap data and information related to the class in one concrete box to prevent access from outside  world. It is somewhat like a capsule and that is why it is called encapsulation.

Abstraction is the process of encapsulation. Confused ? Ok, let me explain in simple word. Definition says “Abstraction is to show only relevant data to the user.” Means it is the process to show relevant data or alternatively hide the unwanted data. As the dictionary meaning of the word “abstraction”, abstraction abstract meaningful data and expose the same to user.

“A good encapsulation need good levels of abstraction.”

Oh.. I missed one thing. You geeks always confused with Abstraction and the keyword abstract. Both are different thing. Abstract, private, protected, internal, protected internal and public are the keywords and access modifier just to implement abstraction and encapsulation.
 

Example 

In the below class there are 5 members. Two are public and three are private. EmpID and EmpName are declared as public. These two member is exposed to outside of the Employee class. Hence it is called abstraction. On the other hand Salary,Bonus,Gratuity are declared as private , means it can only be accessable within the Employee class, or we can say these three are capsuled under Employee class. So it is called encapsulation.

Sunday, June 16, 2013

Clean up unmanned code in C#

Introduction


The code then execute in CLR (Common Language Runtine) is called managed code. 

And the code execute outside the scope of CLR is known as unmanaged code. The examples of unmanaged code is COM component, some database call etc.

CLR is responsible for cleanup managed code. But for clean up unmanaged code we need to do some thing extra. C# provide us an interface called IDisposable which need to be implemented in those class where we used our unmanaged code. IDisposable interface has only one method

public void Dispose();


Example


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Example_IDisposible
{
    class Program
    {
        static void Main(string[] args)
        {
            using (ABC abc = new ABC())
            {
                // your code
            }
        }
    }

    public class ABC : IDisposable
    {
        // ------- your unmanaged code ---------- //

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        public void Dispose(bool val)
        {
            if (val)
            {
                // Clean up managed code
            }
            //Clean up unmanaged code, large variable
        }
        ~ABC()
        {
            Dispose(true);
        }
    }
}