Search this blog

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

Search the blog

Loading

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

Explaining Generics using WPF Example

1. Go to file, select new project and you will see a window like this:




2. Now select WPF Application and give the project name as "ShoppingExample" and then click on OK.

3. Now double-click on Window1.xaml and it will open a designer window for you. Go ahead and drop controls on this window and make it look like this:


4. Once you are done, just check out the XAML CODE, if you are familiar with asp.net, you will be so happy to see this. Everything you do here has a feel of developing web application.

5. If you are unable to find the xaml view of window1 then dont worry, i will help you find it.





6.Right click on the project in the solution explorer, go to Add-->Add New Item-->Select a class in the window and name it as ShoppingCartItem.cs.

7. We are going to do a simple shopping example where in the store manager can keep track of all the prices of items in his store.

8. So we every Item has a name and a price.
Lets write a class for ShoppingCartItem which will have two attributes called Name and Price.

namespace ShoppingExample
{
public class ShoppingCartItem
{
public string ItemName;
public double Price;

public ShoppingCartItem(string _Name,double _Price)
{
ItemName = _Name;
Price = _Price;

}

public override string ToString()
{
return ItemName+" Price is " + Price.ToString() + " Rupees Only";
}
}
}

9. This class has one constructor which initializes two variables ItemName and Price.The other method has been used to override the ToString() function from base class for our custom use.

Once you are done with this, you are almost there.

10. Now we are going to create a generics List to store a list of ShoppingCartItems Objects like this:

public List ItemsList = new List();

10. ItemsList will store list of Items like Item1,Item2,Item3.....etc which will has a (Name1,Price1),(Name2,Price2),.....etc.

11.Now Double Click on Window1.xaml.cs and open the file. In that file write the below method:-

private void Window_Loaded(object sender, RoutedEventArgs e)
{

lbItems.ItemsSource = ItemsList;

//lbItems is the ListBox Control dropped in window1 designer

}

12. This suggests that everytime the particular window loads, listbox control will be binded to ItemsList which we created before.

13. Allright everything is set, incase you are still confused about what are really to acheive then let me explain it to you.
This screen allows the user to enter the item name and price .User clicks on Add to cart and the item he entered in textboxes gets saved in the listbox below.
So to do this, we need to add first create a ShoppingCartItem and then add it to the Generic List ItemsList.Since the listbox is binded to our ItemsList, we just need to refresh the listbox everytime and item is added. Below is complete code for Windows1.xaml.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections.Generic;

namespace ShoppingExample
{
///
/// Interaction logic for Window1.xaml
///

public partial class Window1 : Window
{
public List ItemsList = new List();
public Window1()
{
InitializeComponent();
}



private void btnAdd_Click(object sender, RoutedEventArgs e)
{
ShoppingCartItem I = new ShoppingCartItem(txtName.Text, Convert.ToDouble(txtPrice.Text));
ItemsList.Add(I);
lbItems.Items.Refresh();
txtName.Clear();
txtPrice.Clear();


}

private void Window_Loaded(object sender, RoutedEventArgs e)
{

lbItems.ItemsSource = ItemsList;

}
}
}


10.Run the application(Press F5)











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

Saturday, May 22, 2010

Generics V/S Non Generics

Why use Generics??
1.By using generics we can ensure appropriate use of types
2.Improves performance by reducing the need to cast.

Non Generic Classes

I will explain now how Non generic classes differ from Generic classes.

Let us now compare SortedList from Non generic classes and SortedList from Generic Class to understand how does generics actually ensure the appropriate use of types.Lets create a class called Company as follows:

public class Company
{
public SortedList EmpList = new SortedList();

public Company()
{
EmpList.Add("Sameer", 5000);
EmpList.Add("Sanjay", 2000);
EmpList.Add("Shraddha", 1000);



}


}

Am Creating a sorted list which stores "Names" and "Salary" as Key/Value Pair. So we add a few pairs into the sorted list. Lets create another class as follows:

class Program
{


static void Main(string[] args)
{

Company Acompany = new Company();

foreach (string salary in Acompany.EmpList.Values)
{
Console.WriteLine(salary);
/*If you check EmpList has "Salary" of type Int. Hence the above line will require to cast the Int Object to be converted to String Object.This code wont give you any error even if no explicit type casting is mentioned.This kind of conversion hits performance.And also in many cases you will get many errors while casting between different types*/

}
Console.ReadKey();




}
The Above class displays the salaries of employees using Non Generic Class.

USAGE OF GENERICS
Lets Create another class called CompanyGeneric, which uses a Generic Sorted List as follows:

public class CompanyGeneric
{
public SortedList BEmployeeList = new SortedList();

public CompanyGeneric()
{

BEmployeeList.Add("Sameer", 5000);
BEmployeeList.Add("Sanjay", 2000);
BEmployeeList.Add("Shraddha", 1000);

}

}

Now let me display the salaries of all the employees like i did with sorted list.

class Program
{


static void Main(string[] args)
{


CompanyGeneric BCompany = new CompanyGeneric();


foreach (string s in BCompany.BEmployeeList.Values)
{

Console.WriteLine(s);
/*Now when you try to execute this code, you will get an error saying "Cannot convert type int to string". This is how generics helps us in ensuring appropriate use of types and improving the system's performance by reducing the casting operation.If we didn't have an option of generics, our code will be more error prone and tedious.*/

}
Console.ReadKey();


You have to change the above code as follows to execute the program.

class Program
{


static void Main(string[] args)
{


CompanyGeneric BCompany = new CompanyGeneric();


foreach (int i in BCompany.BEmployeeList.Values)
{

Console.WriteLine(i);

}
Console.ReadKey();






}
}


I hope you understood the need of generics in development of an application.I know generics is a complex topic and it is very difficult to understand if you are especially a beginner.Try to run the above code and experience it yourself.Only then you will understand the exact usage of generics

If you have any questions
Mail me @ shaiksameer.cse@gmail.com.
I hope this has proven to be of some help to you.
Have Fun
Sameer Shaik

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