Archive for October 3rd, 2008
Serialization and de-Serialization in .NET
Serialization
While implementing a serialization mechanism in an object-oriented environment, we have to make a number of tradeoffs between ease of use and flexibility. The process can be automated to a large extent, provided you are given sufficient control over the process. For example, situations may arise where simple binary serialization is not sufficient, or there might be a specific reason to decide which fields in a class need to be serialized.
Objective:
To create the serialization program to add data to file in binaryformat and SOAPformat and then by using deserialization we retrieve data from the same file.
Steps to follow:
1. Declare Class hierarchy as [serializable]
2. Include namespace System.Runtime.Serialization.Formatters.Binary or System.Runtime.Serialization.Formatters.Soap
3. Create and intantiation of object.
4. Create and Intantiation of FileStream Object
5. Create and Instantiation of BinaryFormatter or SoapFormatter object
6. For Serialization: use method serialize of class BanaryFormatter/Soap Formatter
7. For DeSerialization: use method deserialize of class BanaryFormatter/Soap Formatter
Code For Person Class:
using System;
using System.Collections.Generic;
using System.Text;
namespace SerializationSample
{
// [Serializable] – To make class serializable
// Each and every base class must be declared as Serializable to make child class serializable.
[Serializable]
// Defination of base class Person
public class Person
{
private string _personName;
public string PersonName
{
get { return _personName; }
set { _personName = value; }
}
private int _age;
public int Age
{
get { return _age; }
set { _age = value; }
}
public Person(string name, int age)
{
_personName = name;
_age = age;
}
}
}
Code For Employee Class:
using System;
using System.Collections.Generic;
using System.Text;
namespace SerializationSample
{
// Full Hierarchi must be declared as [Serializable]
[Serializable]
// Defination of employee class begins .
// Base class is Person
public class employee:Person
{
private int _empid;
public int EmpId
{
get { return _empid; }
set { _empid = value; }
}
private decimal _basic;
public decimal Basic
{
get { return _basic; }
set { _basic = value; }
}
public employee(string _personName,int _age,int empid,decimal basic):base (_personName,_age)
{
_empid=empid;
_basic=basic;
}
}
}
// End of Defination of employee class
Code To Serialize and Deserialize Using Person and Employee Class:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
// namespace for Binary formatter
using System.Runtime.Serialization.Formatters.Binary;
// namespace for Soap formatter
using System.Runtime.Serialization.Formatters.Soap;
// Starting for windows application
namespace SerializationSample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
FileStream fstream=null;
//Binary formatter object declaration
BinaryFormatter binaryformat=null;
try
{
//Person p = new Person(“scott”, 25);
employee lk = new employee(“deependra”, 23, 77619, 20000);
//Instantiation of FileStream Object
fstream = new FileStream(“Person.txt”, FileMode.Create, FileAccess.Write);
// Instantiation of BinaryFormatter Object
binaryformat = new BinaryFormatter();
//Serialize method is called –
// arguments are <FileStream Object> and <ClassName which going to be serialized> .
// It stores object in file.
binaryformat.Serialize(fstream, lk);
MessageBox.Show(“Employee object in binary FORMAT “);
}
catch (Exception k)
{
MessageBox.Show(k.Message);
}
finally
{
fstream.Close();
}
}
private void button2_Click(object sender, EventArgs e)
{
BinaryFormatter binaryformat = null;
FileStream fstream = null;
try
{
fstream = new FileStream(“Person.txt”, FileMode.Open, FileAccess.Read);
binaryformat = new BinaryFormatter();
//Deserialization of employee object
//Input Parameters is FileStream object
//Return type is an object
employee lk = binaryformat.Deserialize(fstream) as employee;
// Showing the Data in Message Box Format
string message=string.Format(“Employee Name:{0}\nEmployee Age:{1} \nEmployee Id :{2}\nEmployee Basic:{3}”,lk.PersonName,lk.Age,lk.EmpId,lk.Basic);
MessageBox.Show(message);
}
catch(Exception ex)
{
MessageBox.Show(“ERROR:”,ex.Message);
}
finally
{
fstream.Close();
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
//DeSerialization using SoapFormatter
//Steps and Methods are same as Binary Formatter
private void button4_Click(object sender, EventArgs e)
{
SoapFormatter soapformat = null;
FileStream fstream = null;
try
{
fstream = new FileStream(“PersonSOAP.txt”, FileMode.Open, FileAccess.Read);
soapformat = new SoapFormatter();
Person p = soapformat.Deserialize(fstream) as Person;
string message = string.Format(“Person Name:{0}\nPerson Age:{1}”, p.PersonName, p.Age);
MessageBox.Show(message);
}
catch (Exception ex)
{
MessageBox.Show(“ERROR:”, ex.Message);
}
finally
{
fstream.Close();
}
}
//Serialization using SoapFormatter
//Steps and Methods are same as Binary Formatter
private void button3_Click(object sender, EventArgs e)
{
FileStream fstream = null;
SoapFormatter soapformat = null;
try
{
Person p = new Person(“scott”, 25);
fstream = new FileStream(“PersonSOAP.txt”, FileMode.Create, FileAccess.Write);
soapformat = new SoapFormatter();
soapformat.Serialize(fstream, p);
MessageBox.Show(“Person object in SOAP FORMAT”);
}
catch (Exception k)
{
MessageBox.Show(k.Message);
}
finally
{
fstream.Close();
}
}
}
}
Output:
Data shown here is store in Binary Format
ÿÿÿÿ JSerializationSample, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null SerializationSample.Person
_personName
_age
scott
Data shown here is store in SOAP Format
<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:Person id=”ref-1″ xmlns:a1=”http://schemas.microsoft.com/clr/nsassem/SerializationSample/SerializationSample%2C%20Version%3D1.0.0.0%2C%20Culture%3Dneutral%2C%20PublicKeyToken%3Dnull”>
<_personName id=”ref-3″>scott</_personName>
<_age>25</_age>
</a1:Person>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Add comment October 3, 2008
Remoting in .NET
Remoting:
Establishing communication between objects that run in different processes, whether on the same computer or on different computers.
.NET Remoting enables client applications to use objects in other processes on the same computer or on any other computer available on its network.
Communicating across processes is still a complex task, but much of it is now handled by the .NET Framework.
To use .NET remoting to build an application in which two components communicate directly across an application domain boundary, you need to build only the following:
- A remotable object.
- A host application domain to listen for requests for that object.
- A client application domain that makes requests for that object.
Remote Objects:
There are three types of objects that can be configured to serve as .NET remote objects.
They are: 1) Single Call Objects
2) Singleton Objects
3) Client Activated Objects (CAO)
Code:
RemoteComponet Library:
//remote component library
using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Data;
using System.Drawing;
namespace RemoteComponentLib
{
public class RemoteComponent:MarshalByRefObject //MarshalByRefObject ensures that the only reference of the object sent not the cpoy of the object
{
public string Greet(string name)
{
Debug(name);
return “Hello” + name + “from satyam”;
//Expected output is
//#3448748-user1 -at server side
//hello user from satyam -sent to client
}
//for tracing
private void Debug(string name)
{
Console.WriteLine(“#{0}-{1}”, this.GetHashCode(),name);
}
}
}
Remote Client Console type:
//remote client program console type
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Remoting; //provides classes and interfaces that allow developers to create and configure distributed applications.
using RemoteComponentLib; //connects to library
namespace RemoteClient
{
class Program
{
static void Main(string[] args)
{
RemotingConfiguration.RegisterWellKnownClientType(typeof(RemoteComponent),“tcp://localhost:9999/RemoteUri”);
RemoteComponent obj = new RemoteComponent();//the created obj refers as proxy
Console.WriteLine(“Enter a string”);
string str = Console.ReadLine();
Console.WriteLine(obj.Greet(str));
Console.ReadLine();
}
}
}
Remote Host:
//program for the RemoteHost
//remote client program console type
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Remoting; //provides classes and interfaces that allow developers to create and configure distributed applications.
using RemoteComponentLib; //connects to library
namespace RemoteClient
{
class Program
{
static void Main(string[] args)
{
RemotingConfiguration.RegisterWellKnownClientType(typeof(RemoteComponent),“tcp://localhost:9999/RemoteUri”);
RemoteComponent obj = new RemoteComponent();//the created obj refers as proxy
Console.WriteLine(“Enter a string”);
string str = Console.ReadLine();
Console.WriteLine(obj.Greet(str));
Console.ReadLine();
}
}
}
Remote Client windwos type:
//for Remote client in windows form
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.Remoting; //provides classes and interfaces that allow developers to create and configure distributed applications.
using RemoteComponentLib;//To create objets of type RemoteComponent that acts as proxy
namespace RemoteClib
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//RemoteComponent obj = null;
private void Form1_Load(object sender, EventArgs e)
{
//RemotingConfiguration.RegisterWellKnownClientType(typeof(RemoteComponent), “tcp://localhost:9999/ RemoteUri”);
//obj = new RemoteComponent();//proxy
}
private void button1_Click(object sender, EventArgs e)
{
//RemoteComponent:Provides various static methods for configuring the remoting infrastructure.
//RemotingConfiguration:Overloaded.Registers an object Type on the client end as a well-known type (single call or singleton).
//Registers an object Type on the client end as a well-known type that can be activated on the server,using the given parameters to initialize a new instance of the WellKnownClientTypeEntry class.
RemoteComponent obj = null;
RemotingConfiguration.RegisterWellKnownClientType(typeof(RemoteComponent), “tcp://localhost:9999/RemoteUri”);
obj = new RemoteComponent();//proxy
MessageBox.Show(obj.Greet(textBox1.Text));
Console.ReadLine();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
}
}
OutPut:
Different Windows for the following
1. Singleton –console Application
2. Singlecall –console Application
3. SingleCall –Windows Application
4. SingleTon –Windows Application
Aslo:the code can be modified to use over different machines using IP address
Add comment October 3, 2008
Interface
Interface:
An Interface is a reference type and it contains only abstract members. Interface’s members can be Events, Methods, Properties .But the interface contains only declaration for its members. Any implementation must be placed in class that realizes them. The interface can’t contain constants, data fields, constructors, destructors and static members. All the member declarations inside interface are implicitly public.
Interfaces in C# are provided as a replacement of multiple inheritance. Because C# does not support multiple inheritance, it was necessary to incorporate some other method so that the class can inherit the behavior of more than one class, avoiding the problem of name ambiguity that is found in C++. With name ambiguity, the object of a class does not know which method to call if the two base classes of that class object contain the same named method.
A very important point to be remembered about c# interfaces is, if some interface is inherited, the program must implement all its declared members. Otherwise the c# compiler throws an error
Objective:
To create an interface and implement it in different classes
Steps to follow;
· Create an interface iflight and define one method fly()
· Create three classes bird,aeroplane and superman and implement
the method fly() in these classes
· Create a main class and create an interface array of instances of the above three classes.
· Run a loop and call the fly() method of different objects
Code:
//this is an interface with a method called fly();
public interface IFlight
{
//definition of a method fly()
void Fly();
}
//implementing the interface in class bird
class Bird:IFlight
{
#region IFlight Members
//implementing the abstract method fly() of the interface
public void Fly()
{
Console.WriteLine(“Up Up High Sky”);
}
#endregion
}
//implementing the interface in class aeroplane
class Aeroplane:IFlight
{
#region IFlight Members
//implementing the abstract method fly() of the interface
public void Fly()
{
Console.WriteLine(“aeroplane is flying”);
}
#endregion
}
//implementing the interface in class superman
class SuperMan:IFlight
{
#region IFlight Members
//implementing the abstract method fly() of the interface
public void Fly()
{
Console.WriteLine(“Look that’s spiderman no its superman”);
}
#endregion
}
//Main class
class Program
{
static void Main(string[] args)
{
//creating an array of instances
IFlight[] flyobjects ={ new Bird(), new Aeroplane(),new SuperMan() };
//looping through the array
foreach (IFlight obj in flyobjects)
{
obj.Fly(); //calling the fly method
}
Console.ReadLine();
}
}
Output :
Up Up High Sky
Aeroplane is flying
Look that’s spiderman no its superman
2 comments October 3, 2008