Showing posts with label I/O Operations. Show all posts
Showing posts with label I/O Operations. Show all posts

Thursday, 22 March 2012

What is Serialization and Why Serialization Process?

Serialization in .net?

Serialization is a process of converting the object form to an array of bytes of data. Using streams which can be moved form one place to another palce. As well as from physical form data to again form a object is called Deserialization.

Why Serialization process?

Serialization is used to save  the state of object. And transfer the data across the network required the object serialization.
The ISerializable interface allows you to make any class Serializable. Which is System.xml.Serialization namespace.

In .net we have 3 approaches to make serialization
1.Binary serialization 2. Soap serialization 3. Xmlserialization(custom serialization,shallow serialization)

 Xml Serialization

To make object save as a xml file we have to choose xml serialization process. System.xml and System.Xml.Serialization are namespaces.
Here we have the relavent classes to make serialization.

For Serialization and Deserialization for custom object
[Serializable()]
public class ObjectToSerialize : ISerializable  // Employee
{
// For Deserialization
ObjectToSerialize(SerializationInfo info, StreamingContext context, bool ConstructSchema);
// Serialization
public virtual void GetObjectData(SerializationInfo info, StreamingContext context);
}

Serialize() and deserialize() method belong to that particular type formatters. Like
Xmlserilizer------------------serialize and deserilizer methods
Binaryserlizer-----------------serializer and derrilser methods
Soap serializer-----------------serializer and deserlizer methods
But  these are derived from IFormatter for standardization.

Coming to xmlserialization
Type(DataSet….Employee…ect )should be Public  and members also should be public ----xmlserialization
Custom Object Serialization
[Serializable]
     public class Employee:ISerializable
    {

        private int EmpId;

        public int EmpId1
        {
            get { return EmpId; }
            set { EmpId = value; }
        }
        public string EmpName;

        //Default constructor
        public Employee()
        {
            EmpId = 0;
            EmpName = null;
        }

 public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue("EmpId10", this.EmpId);          
        }
    }
SerializationInfo info: This object holds a name-value pair for the properties to be serialized. You can decide which property   should be serialized and which not in the GetObjectData() function. All the properties that are added to this SerializationInfo parameter will be serialized. Here are the codes for the two functions. Add them to our Employee class.
static void Main()
        {
          Employee eobj = new Employee();
            eobj.EmpId1 = 1041;
          }
Xml Serialization


Serialization

String strxml=@"C:\EmployeeInfo.xml");

Type z = eobj.GetType();

XmlSerializer serializer = new XmlSerializer(z);
            Or
XmlSerializer serializer = new XmlSerializer(typeof(Employee));
TextWriter textWriter = new StreamWriter(strxml); // return type StramWriter
serializer.Serialize(textWriter, eobj);
textWriter.Close();------------serialization
DeSerialization

XmlSerializer serializer = new XmlSerializer(typeof(Employee));

TextReader textReader = new StreamReader(strxml);
object  eobs=serializer.Deserialize(textReader);
textReader.Close();

Employee eobjjj = new Employee();
eobjjj = (Employee)eobs;
int s = eobjjj.EmpId1;
Console.Write(s);
Whatever object properties we want to serialize those should be inside the
GetDataObject funcation why because Serialization of object starts from GetDataObject.

How to Use Streams,StreamWriter,StreamReader?

What  is   stream?
a stream is a general representation of bytes. We use a stream-based classes to read bytes of data from sources like files, memory or even network locations.

As per the source we have to choose the stream classes like FileStream,Memorystream,Networkstream….ect
Right now I am working with files means my source is File so choose FileStream.
Using File class I can read the data and write the data using Files.

FileStream is a stream based type which is derived from Stream abastract class.

File using stream based classes
Ex:
  FileStream  fss=File.Create("C:\\abcdd.txt");
            
   fss.WriteByte(98);
File Class has
public static StreamWriter CreateText(string path);
public static StreamReader OpenText(string path);
static void Main()
{
            string strpath=@"C:\\zolt.txt";
            StreamWriter w = File.CreateText(strpath);
            w.WriteLine("This is from");
            w.WriteLine("Chapter 6");
            w.WriteLine("Of C# Module");
            w.Write(w.NewLine);
            w.WriteLine("Thanks for your time");
            w.Close();
            Console.WriteLine("=========");
            StreamReader s = File.OpenText(strpath);
                string read = null;
                while ((read = s.ReadLine()) != null)
                {
                  Console.WriteLine(read);
                }
                s.Close();                       
            Console.Read();
  }
FileInfo Class
            FileInfo finfo = new FileInfo(@"C:\aa.txt");
            StreamWriter  w=finfo.AppendText();  // CreateText();
            w.WriteLine("This is from");
            w.WriteLine("Chapter 6");
            w.WriteLine("Of C# Module");
            w.Write(w.NewLine);
            w.WriteLine("Thanks for your time");
            w.Close();
CreateText() methods create every time override the File.

AppendText() method append the data to existing data. 
Working With StreamWriter and StreamReader classes?

StreamWriter and StreamReader are sealed Classes which derived from TextWriter and TextReader Classes.

TextReader and TextWriter for Text data.
like
XmlTextReader,xmltextWriter.
StreamWriter:
             string strpath = @"C:\\zolt.txt";

StreamWriter w = new StreamWriter(strpath);
            w.WriteLine("This is from");
            w.WriteLine("Chapter 6 kasibabu");
            w.WriteLine("Of C# Module");
            w.Write(w.NewLine);
            w.WriteLine("Thanks for your time");
            w.Close();
            Console.WriteLine("+++++++++++");
 StreamReader:
                StreamReader sr = new StreamReader(strpath);          
                String line;
                // Read line by line
                while ((line = sr.ReadLine()) != null)
                {
                    Console.WriteLine(line);
                }
Another way is

StreamWriter and  TextWriter
            string strpath = @"C:\\zolt.txt";
            TextWriter writeFile = new StreamWriter(strpath);
            writeFile.Write("dalksfjdflaksj");
            writeFile.Write(10);
            writeFile.Write("daflsfkasibabu");
            writeFile.Flush();
StreamReader and TextReader
            string line1 = null;
            System.IO.TextReader readFile = new StreamReader("C:\\dfgsdf.txt");
            line1 = readFile.ReadToEnd();
            Console.WriteLine(line1);           
            readFile.Close();
            readFile = null;         

Streamwriter  and StreamReder can take any stream as a parameter to write and read.
StreamWriter accepts stream as paramter

public StreamWriter(Stream stream);
public StreamReader(Stream stream); 

Ex:
       FileStream  fs=File.Create("C:\\naveen.txt");
            StreamWriter sw = new StreamWriter(fs);
            sw.Write("i ");
            sw.Write("kasi");
            sw.Write("babu");
            sw.WriteLine("");
            sw.Write("addresss:");
            sw.Flush();
            sw.Close();
StreamReader  accepts stream as paramter

            FileStream fs1 = File.Open(strpath, FileMode.Open);
            StreamReader sr = new StreamReader(fs1);
            string str = sr.ReadToEnd();
            Console.WriteLine(str);
            sr.Close();

When we serialize and deserialize any object then we are then these are very useful…

Wednesday, 21 March 2012

How to use Files,Directories,Streams?

Yes, we need to know how to use these classes, and what the relationship between them.for all classes related to Input and Output classes defined in namespace is called using System.IO;
using System.IO


Directory,File,FileSystemInfo,FileInfo,DirectroyInfo,Stream,
FileStream, ...ect.

What is the Difference between Directory and DirectoryInfo Classes?
Yes,Both DirectoryInfo and Directory has same methods and properties.
How to choose which is best one.? Both are good types. We have choose as per our need of  the development requirement
Ex: 
But when I go for Static class(Directory) or  Instatnce class(DirectoryInfo).
Static Class : To perform simple operations like Directory/file is existed or not, creating..ect.
How to use DirectoryInfo type?
          DirectoryInfo dirinfo = new DirectoryInfo(@"E:mani");
            dirinfo.Create();           
            DirectoryInfo[] dirstr = dirinfo.GetDirectories();
            foreach (DirectoryInfo item in dirstr)
            {
                Console.Write(item);
                Console.Write("\n");
            }
Same example we can perform implement using Static Class Directory
  string strpath = @"E:\mani";
  Directory.CreateDirectory(strpath);  // equal to dirinfo.Create()
    string[] strdirectires = Directory.GetDirectories(strpath);
     foreach (string item in strdirectires)
     {
       Console.Write(item);
       Console.WriteLine("\n");
    }
But how to use them is for simple operations like directory is exist or not I want to know then choose static class---Directory class. Why because I don’t require now any information about that directoy.
Ex:
            string strdir=@"E:\a";
            if (Directory.Exists(strdir))
            {
                Console.WriteLine("yes directory is existed");
            }
            else
            {
                Console.WriteLine("no directory is no existed");                       
            }
           Instead of unneccsseryly creating object like below
            DirectoryInfo dirinfo = new DirectoryInfo(@"E:\a");
            if (dirinfo.Exists)
            {
                Console.WriteLine("yes existed sub directories");
            }
            else
            {
                Console.WriteLine("no directory is existed");          
            }

But some titmes I need to know about that particular directory then go for DirectoryInfo.
a diriectory contains b,c,d directories so output is yes directory is existed
But now I want know b or c or d subdirectory conatains any subdirectories.
Then go for DirectoryInfo type.
Static class –Directory require more parameters then DirectoryInfo type.
Like
Directory.MoveTo(source,destination);
Come to DirectoryInfo requries one parameter that is Destination only
Why because we are working with instance of directoryInfo which is already instanated with the some path
Ex:
DirectoryInfo dirinfo = new DirectoryInfo(@"E:\a");
Means dirinfo has source it self. So we requrie only destination so one parameter is enough.
Note: what are the things we can do with the Directory static class. All are possible with DirectoryInfo also. But unnecessarly creating object is not good.
The same things what we discuss applicable to File and FileInfo types.
Why because they are derived from FileSystemInfo abstract class.