Search this blog

You can search for all the topics in our blog using our google custom search now.

Search the blog

Loading
Showing posts with label Topic Serialization. Show all posts
Showing posts with label Topic Serialization. Show all posts

Saturday, May 29, 2010

XML Serialization and Deserialization Simple example



Things you should remember:
1. Xml Serialization or De-Serialization needs a parameterless constructor, if you want to serialize an object.
2. Make the class Serializable using [Serializable] before class definition.
3. You need to add reference of  System.Xml.Serialization namespace.
4. Create Xml Serializer object like this:
    XmlSerializer xs = new XmlSerializer(typeof(Sometype));
    Note: Sometype means you have to declare some type like this XmlSerializer xs = new             XmlSerializer(typeof(String)) or XmlSerializer xs = new XmlSerializer(typeof(Object)) etc
5. You can serialize any object like this:
     xs.Serialize(fs1, Object);

Okay if you are new to serialization, i would suggest you check these examples first and then jump to this one:
http://mctsexam70-536tutorials.blogspot.com/2010/05/how-to-serialize-and-de-serialize.html
http://mctsexam70-536tutorials.blogspot.com/2010/05/how-to-serialize-and-de-serialize_24.html
http://mctsexam70-536tutorials.blogspot.com/2010/05/creating-serilizable-class-and-writing.html
http://mctsexam70-536tutorials.blogspot.com/2010/05/soap-serialization-example-using.html


Now am gonna believe that you have checked the previous posts to learn the basics of serialization, so am not gonna stress on details. First i will create a class called Item (Yes! Again, I know) and am going to define a parameterless function so that i can perform xml serialization and deserialization. Go ahead do it:

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

namespace ConsoleApplication1
{
   
        [Serializable]
        public class Item
        {
            public string name;
            public double price;
            public Item()
            {
                name = "Product_Name";
                price = 21;

            }

            public Item(string _name, double _price)
            {
                name = _name;
                price = _price;
            }

            public override string ToString()
            {
                return "The Item " + name + " would cost you " + price.ToString();
            }

        }
   
}

Now start serialization in your program.cs file which is created with your console application as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Serialization;

namespace XmlSerialization
{
    class Program
    {
        static void Main(string[] args)
        {
            Item Item1 = new Item("MCTS Tony Northrup Book", 55);
            Item Item2 = new Item("MCTS Braindumps Material", 159.99);
            Item Item3 = new Item("MCTS 70-528 Amit Kalani Book", 68.99);
            List ItemsList = new List();
            ItemsList.Add(Item1);
            ItemsList.Add(Item1);
            ItemsList.Add(Item1);
            FileStream fs = new FileStream(@"C:\Test.Sam", FileMode.Create);
            //You can write it to any file you want, if you see i have created a file of type.Sam, even you can make //a file with your name extension
            XmlSerializer xs = new XmlSerializer(typeof(List));
            xs.Serialize(fs, ItemsList);
            Console.WriteLine("Written items to the given file");

        }
    }
}
 

Free MCTS EXAM 70-536 training tutorials on this website, soon will be launching video tutorials for all the same topics 



Check out the video, if you still have any doubts on this:

Tuesday, May 25, 2010

Soap Serialization example using a serializable class

Just like in previous example:

http://mctsexam70-536tutorials.blogspot.com/2010/05/creating-serilizable-class-and-writing.html

Am going to create an Item Class, the code is as follows:

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

namespace SoapSerializationExample
{
    [Serializable]
    public class Item
    {
        public string name;
        public double price;
        public Item(string _name, double _price)
        {
            name = _name;
            price = _price;
        }

        public override string ToString()
        {
            return "The Item "+name+" would cost you " + price.ToString();
        }

    }
}
My project name is SoapSerializationExample, if you have given any other name to your console application project, then rename your namespace with your project name.

If you have checked the previous post, i dont think i need to explain much. Just go ahead and write the given code to implement the soap serialization:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Formatters.Soap;
using System.IO;



namespace SoapSerializationExample
{
    class Program
    {
        Item ItemObj = new Item("Xbox", 325.00);
        static void Main(string[] args)
        {
            Item ItemObj = new Item("Xbox", 325.00);
            FileStream fs = new FileStream(@"C:\Test.Sam", FileMode.Open);
            SoapFormatter sf = new SoapFormatter();
            sf.Serialize(fs, ItemObj);
           
            fs.Close();
            StreamReader sr = new StreamReader(@"C:\Test.Sam");

            string TextEntered = "";
            string temp = "";
            if ((temp = sr.ReadLine()) != null)
            {
                TextEntered = temp + sr.ReadLine();

            }
            Console.WriteLine();
            Console.WriteLine("Reading the contents of the file ...Press any key");
            sr.Close();
            Console.ReadKey();
            Console.WriteLine();
            Console.WriteLine(TextEntered);
            FileStream fs2 = new FileStream(@"C:\Test.Sam", FileMode.Open);
            SoapFormatter bf2 = new SoapFormatter();
            Console.WriteLine();
            Console.WriteLine("Deselerializing the contents from the file...");
            Item ItemRetrieved = (Item)bf2.Deserialize(fs2);
            string s2 = ItemRetrieved.ToString();
            Console.WriteLine(s2);
            Console.WriteLine();
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
            fs2.Close();
        }
    }
}

I hope you understood this, if you haven't, let me know.
Sameer Shaik

Free MCTS EXAM training tutorials on this website, soon will be launching video tutorials for all the same topics

Creating a serilizable class and Writing it to a file

We have already seen how to serialize simple type objects like string, int etc etc, you must be wondering and asking yourself  "Okay and So what???". Imagine you have a requirement where you need to store the class objects to a file, how would you do that? Thats exactly when you use serialization to store the class objects and de-serilization to retrieve those stored class object.

Am going to create a new console application and to my project on right in the solution explorer, go ahead and add a new item-->Class-->name it as Item.Our class will have two attributes name and price. To make a class serializable you need to include this [serializable]. Our class will have a constructor and a ToString() method which overrides the ToString Method from Object Base Class.

What are you waiting for? go ahead and create a class like this

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

namespace serilizationexample
{
    [Serializable]
    public class Item
    {
        public string name;
        public double price;
        public Item(string _name, double _price)
        {
            name = _name;
            price = _price;
        }

        public override string ToString()
        {
            return "The Item "+name+" would cost you " + price.ToString();
        }

    }
}

Lets go ahead and write this class object to a file. Open program.cs from console application project, and create a filestream like this:
FileStream fs = new FileStream(@"C:\Test.Sam", FileMode.Create);
This tell us that fs opens a file called Test.Sam from given location.To serialize the object we need to create binary formatter as follows:
BinaryFormatter bf = new BinaryFormatter();

Now you need to create an object from Item class like this:
Item ItemObj = new Item("Xbox", 325.00);
Once you have object created, lets serialize it before we can write it to a file
bf.Serialize(fs, ItemObj);
Great!!! Now you have written the object to the given file, go ahead take a look at the file that you created.To do that go to your file location(in my case its C:\), open Test.Sam with notepad. Lets read the file from our program and display it on the console. Create a streamreader object "sr" and read from the file like this:

StreamReader sr = new StreamReader(@"C:\Test.Sam");
            string TextEntered = "";
            string temp = "";
            if ((temp = sr.ReadLine()) != null)
            {
                TextEntered  = temp + sr.ReadLine();
           
            }
Display the contents of the file on screen:
Console.WriteLine(TextEntered);


We are almost done now, go ahead and deserilialize the object from the file like this:
Item ItemRetrieved = (Item) bf2.Deserialize(fs2);
Now you have learned how to serialize and deserialize the class objects.

This is how your program.cs file should look like:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace serilizationexample
{

    class Program
    {
       
        static void Main(string[] args)
        {
         

            FileStream fs = new FileStream(@"C:\Test.Sam", FileMode.Create);
            BinaryFormatter bf = new BinaryFormatter();
            Item ItemObj = new Item("Xbox", 325.00);
            bf.Serialize(fs, ItemObj);
            fs.Close();
            Console.WriteLine("Successfully wrote Obj to file press any key to Read the text from the file");
           
           

           
          
           
           
            StreamReader sr = new StreamReader(@"C:\Test.Sam");
            string TextEntered = "";
            string temp = "";
            if ((temp = sr.ReadLine()) != null)
            {
                TextEntered  = temp + sr.ReadLine();
           
            }
            Console.WriteLine();
            Console.WriteLine("Reading the contents of the file ...Press any key");
            sr.Close();
            Console.ReadKey();
            Console.WriteLine();
            Console.WriteLine(TextEntered);
            FileStream fs2 = new FileStream(@"C:\Test.Sam", FileMode.Open);
            BinaryFormatter bf2 = new BinaryFormatter();
            Console.WriteLine();
            Console.WriteLine("Deselerializing the contents from the file...");
           Item ItemRetrieved = (Item) bf2.Deserialize(fs2);
           string s2 = ItemRetrieved.ToString();
            Console.WriteLine(s2);
            Console.WriteLine();
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
            fs2.Close();
           
           


           


        }
    }
}

If you need any help since you are totally new to all of this, then contact me and i will try to help you out.

Free MCTS EXAM training tutorials on this website, soon will be launching video tutorials for all the same topics

Monday, May 24, 2010

How to serialize and de-serialize simple objects part 2

Refining the previous example to include reading from a file, displaying to the console, serializing and de-serializing the objects. This program must showcase the usage of streamreader,streamwriter,binaryformatter,filestream etc

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace serilizationexample
{

class Program
{

static void Main(string[] args)
{
Console.WriteLine("Please enter the text to write to the file");
string s1 = Console.ReadLine();

FileStream fs = new FileStream(@"C:\Test.Sam", FileMode.Create);
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, s1);
fs.Close();
Console.WriteLine("Successfully wrote text to file press any key to Read the text from the file");
// Console.ReadKey();
Console.Clear();

FileStream fs2 = new FileStream(@"C:\Test.Sam", FileMode.Open);
BinaryFormatter bf2 = new BinaryFormatter();
string s2 = (string)bf2.Deserialize(fs2);
fs2.Close();
StreamReader sr = new StreamReader(@"C:\Test.Sam");
string TextEntered = "";
string temp = "";
if ((temp = sr.ReadLine()) != null)
{
TextEntered = temp + sr.ReadLine();

}
Console.WriteLine("Reading the contents of the file ...Press any key");
Console.ReadKey();
Console.WriteLine(TextEntered);
Console.WriteLine("Deselerializing the contents from the file...");
Console.WriteLine(s2);
Console.ReadKey();
sr.Close();






}
}
}

Incase you find anything confusing, contact me

Free MCTS EXAM training tutorials on this website, soon will be launching video tutorials for all the same topics

Sunday, May 23, 2010

How to serialize and de-serialize simple objects Part 1

1. Serialization is the process of converting objects into linear sequence of bytes that can be stored or transferred.

2. You got to include all these namespaces to use serialization, they are:-

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

3. System.IO namespace for working with all available streams and serialization,de-serialization is basically done by BinaryFormatter Objects which is available in System.Runtime.Serialization.Formatters.Binary;


4.



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace serilizationexample
{

class Program
{


static void Main(string[] args)
{
Console.WriteLine("Please enter the text to write to the file");
string s1 = Console.ReadLine();
FileStream fs = new FileStream(@"C:\Test.Sam", FileMode.Create);
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, s1);
fs.Close();
Console.WriteLine("Successfully wrote text to file press any key to Read the text from the file");
Console.ReadKey();
Console.Clear();

FileStream fs2 = new FileStream(@"C:\Test.Sam", FileMode.Open);
BinaryFormatter bf2 = new BinaryFormatter();
string s2 = (string)bf2.Deserialize(fs2);

fs2.Close();
Console.WriteLine("Below is the text written to the file");
Console.WriteLine(s2);
Console.ReadKey();





}
}
}

Free MCTS EXAM training tutorials on this website, soon will be launching video tutorials for all the same topics