Saturday, March 16, 2013

Store data locally with HTML5 Web Storage

Now new version of HTML5 having number of new API one of the is Storage API, which allow you to store data of use locally. Here in following post I am going to describe Storage API.

Cookies vs. Storage
In previous version of HTML allows to store data locally with the help of Cookies but the
  •  issue with the cookies is its not allow to big object and which can be easily done. Storage allows 5M (most browsers) or 10M (IE) of memory at disposal. 
  • Another problem is cookies get sent to server with each HTTP request which in term increases traffic.
Storage
Now lets start using the store in application
if(typeof(Storage)!=="undefined")
{
  alert("storage is supported and you can store data in it"); 
}
else
{
 alert("Get new version of browser or use browser which support storage");
}
So here in above as you can see, first line of code check weather browser supports/have Storage object. It's good to check because most of the older browser is not supporting and as its new feature its mostly supported in new browsers.

After doing check for Storage support decide either you want to store data for given session only or want to store data which available even after session is over and when user come back.
So there are two type of object which is explained below
  • sessionStorage is used to store within the browser tab or window session. so it allows to store data in a single web page session.
  • localStorage is used to kept even between browser sessions. so it allows to access data after the browser is closed and reopened again, and also instantly between tabs and windows.
Note : Storage data created by one browser is not avaible in other browser. for example created in IE is not available in FireFox.

Following is the way you can use the localStorage and sessionStorage in your application.
//sessionStorage 
//set and get object 
sessionStorage.setItem('myKey', 'myValue');
var myVar = sessionStorage.getItem('myKey');
//another way to set and get 
sessionStorage.myKey = 'myValue';
var myVar = sessionStorage.myKey;

//remove item
sessionStorage.removeItem('myKey');

//clear storage 
sessionStorage.clear();
//localStorage 
//set and get object 
localStorage.setItem('myKey', 'myValue');
var myVar = localStorage.getItem('myKey');
//another way to set and get 
localStorage.myKey = 'myValue';
var myVar = localStorage.myKey;

//remove item
localStorage.removeItem('myKey');

//clear storage 
localStorage.clear();
as in the above code both of the object support same set of methods to store and retrieve data.
  • setItem - allows to set value. 
  • getItem - allows to get value.
  • removeItem - allows to remove object from storage. Note: if it used like removeItem(), it removes all stored object , so be careful when removing -to remove specific object use removeItem("myKey"). 
  • clear - clear storage i.e. clear all stored data.
and as you can see storage store data in key value pair.

Conclusion
Web Storage simplify the storing of object in client and also have advantage over cookies, but its always good to not store sensitive information in the client side storage as storage is not provide that much security.

Thanks for reading and do post comment if you like it or something is missing or wrong.

Thursday, March 14, 2013

Object to XML using LINQ or XmlSerializer

In Following post I am going show you how easily you can convert you object in the XML string, because sometime there is need of pass object and XML from one function to another and also convert XML string back to object. But As title suggest here I just going to discuss the conversion of object to XML string.

Following two way to achieve this task of converting Object to XML.

Before we start Below is class structure which object need to be convert in XML string.
public class Product
    {
        public string Name { get; set; }
        public int Code { get; set; }
        public List<productType> types {get; set;}
    }

    public class productType
    {
        public string type {get; set;}
    }
As you can see in structure Product is class and it's having list of producttype in it.

Way 1 : Linq To XML
 List<productType> typ = new List<productType>();
            typ.Add((new productType() { type="Type1"}));
            typ.Add((new productType() { type = "Type2" }));
            typ.Add((new productType() { type = "Type3" }));

            Product[] products = { new Product { Name = "apple", Code = 9,types=typ }, 
                       new Product { Name = "orange", Code = 4,types=typ   }, 
                       new Product { Name = "apple", Code = 9 ,types=typ}, 
                       new Product { Name = "lemon", Code = 9,types=typ } };
Above code is creating array of product which contains the object of product. Over all its initializing the product array object.Now to convert this in the XML using Linq following is code
            XElement _customers = new XElement("Products",
                       from c in products
                       orderby c.Code 
                        select new XElement("product",
                            new XElement("Code", c.Code),
                            new XElement("Name", c.Name),
                            new XElement("Types", (from x in c.types
                                                  orderby x.type//descending 
                            select new XElement("Type",x.type)) 
                        ))
                  );

            Console.WriteLine(_customers.ToString());
As you see in above code its converting the each property of object in XMLElement by using method of Linq To XML which is XElement. You can modify structure as per you needs here is more on Linq to XML

Output



Way 2 : Make use of XmlSerializer
You can easily convert the object in XML string by using Serializer as shown below. This process called as object serialization.
            XmlSerializer xser = new XmlSerializer(products.GetType());
            xser.Serialize(Console.Out, products);
            Console.ReadLine();
As you see there just two line of code need to conversion. There is no need to write more amount of the code like Linq To XML, But if you want to control structure of the generated XML you need to decorate your class with XmlAttributes. Read more about this XmlSerializer

Output



Comparison between both the ways
  • Big difference between both is way XML string is generated. That you can easily figure out form the Output of both the way.
  • XmlSerializer provide more control on XML than than the Lin To XML.
  • As stated with Linq to Xml you need to write down more amount of code to structure the XML string which is very easy with XmlSerializer. But if you dont want the default structure generated by XmlSerializer you need to use XmlAttributes for each property. with attribute class will be

 public class Product
    {
        [XmlElement("Product Name")]
        public string Name { get; set; }
        [XmlElement("Code")]
        public int Code { get; set; }
        [XmlElement("Types")]
        public List types {get; set;}
    }
But you can easily do this in Linq to XML.
  •  When you dont want to include some property in XML string. you just need to skip that property like this.
XElement _customers = new XElement("Products",
                       from c in products
                       orderby c.Code //descending 
                        select new XElement("product",
                            //new XElement("Code", c.Code),
                            new XElement("Name", c.Name),
                            new XElement("Types", (from x in c.types
                                                  orderby x.type//descending 
                            select new XElement("Type",x.type)) 
                        ))
                  );
in linq to xml you just need to remove it here i just commented Code so there is no element for Code.






For XmlSerializer you need to put attribute called [Obsolete] on top of property.
        public string Name { get; set; }
        [Obsolete]
        public int Code { get; set; }
        public List types {get; set;}

  • Another Difference is Linq TO XML is faster than XmlSerializer which you can easy see by running the code its because XmlSerializer is Serializing object which might be using reflection and other metadata information about the object.
Conclusion
You can use one of the way as per your need. But if you just want to generate XML than its better to go for Linq to XML and if there is serialization/ de-serialization required than go for XmlSerializer .

Provide comments if you find more difference and there is thing change require in above. Thanks for reading.