Sunday 6 November 2011

How to upgrade iPad 2 to iOS 5

I bought iPad 2 in end of October of the 2011 and happy to use it. When I bought it, it contained IOS operation system with version 4.3.5 (8L1).
To check your current OS version on iPad you can by clicking on Settings->General->About->Version:

iPad - check OS version


Apple released new OS version 2 weeks later - version 5, so I had to upgrade my iPad2 OS version by myself. I will describe my experience of upgrading IOS version 4.3.5 to version 5.0.
I missed some printscreens, but here is what I have.

Prerequirements:

1) Make sure your iPad has enough battery charge, because when you connect iPad to computer, it's battery is not charging. You will need battery to keep power for the synchronization and upgrading IOS for at least 30-40 minutes.

2) Download iTunes from following url and install it to your computer
http://www.apple.com/itunes/download/

Process:

2) Plug in iPad by USB cable to computer.

iPad2, connected to laptop by USB cable


iTunes will be run automatically with following message:

iTunes: prompt to download new IOS version 5


you can cancel it and you will be able to do it from main screen:

iTunes: iPad2 information


click on "Update" button.
If you have purchased items, you have to transfer it to local computer. You will be probably see following screen:

iTunes: alert about purchased items to be transferred to iTunes Library

Of if you click on "Sync" button at the right bottom corner of the iTunes window

iTunes: Sync button

you will probably see following dialog box:

iTunes: Need computer authorization to transfer purchased items


To authorize your computer to sync purchased items at Apple store you should do following:

iTunes: Authorize this computer


iTunes: computer authorization was successful

After you authorize your computer, click on "Sync" button again and you will see synchronization progress:

iTunes: transferring purchased items


After sync is done you will see message that device can be disconnect, but we don't want it:

iTunes: iPad sync is complete

4) start IOS update:

iTunes: start updating IOS

click "Update" button and you will see software update dialog box, which will describe what new features will be available in IOS 5:

iOS 5 Software update dialog box

You able to save text to file by clicking on "Save" button if you need it.
In anyway, click "Next" button and read "License Agreement" if you really enjoying it :-) and click on "Agree" button. iTunes will start download iPad software update.

iTunes: iPad Software Update


iTunes: Extracting software


iTuned: iPad2 - preparing to restore


iPad2: Connecting to iTunes

iPad2: Update in progress



iPad2: Select language


iPad2: Country select


iPad2: Enable Location Services
...

4) Restore settings





restoring apps...

....
Done.

Post upgrades steps:

Everything went smooth during upgrade, but .... as always there is something wrong.
I found that my 3G connection didn't work anymore. My 3G data plan service provider is Rogers.
I tried login to cellular data by using Rogers credentials and saw that my plan is still active:

iPad2: after upgrade to IOS5, Rogers Canada 3G didn't work, but dataplan was active.


but when I used Safari, I was getting message to buy new plan.
I tried different options, including network reset but it didn't help. I even tried visit support web site but it has an issue too.

I thought that it is temporary but on next morning I got the same problem.
I gave up and went to Apple store to get new SIM card from another service provider to avoid future problem, such as keep calling to Rogers support and keep spending my time.
My old data plan was almost exhausted, so I made that decision and selected Bell. I paid for new plan - it took me ~10 minutes and it started work:

iPad2: Cellular Data Plan has been activated with Bell Canada

Monday 19 September 2011

Framework 4.0 - How to configure WCF Service to use DataContractSerializer or XmlSerializer

Default serialization mechanism in WCF is DataContractSerializer. Main benefit of the DataContractSerializer is that it is faster. It is good if you use .NET clients, but in some cases it requires to use different serializer. If you need support both - XmlSerializer and DataContractSerializer, you have following options:

1) create new interface for every serialization method, which will bring new end-points
2) Inherit service class from the same interface as you use in with DataContractSerializer, but mark with [XmlSerializerFormat]
3) Keep one interface and one end-point, but create separate operations for that, like GetOrders (for the DataContractSerializer) and GetOrders2 (for the XmlSerializer)
I have already created article about XmlSerializer and DataContractSerializer and expected results in serialization/deserialization.

Framework 4.0 - XmlSerializer vs DataContractSerializer. Prepare class for serialization. Performance.

Very important aspect of that article is how to prepare class for the serialization.
In this article I will describe how to configure WCF service to use DataContractSerializer or XmlSerializer on service level or operation level and how to test it during development process by using WCF Test Client.

I will not be focused on extracting data from back-end systems and will use randomly generated data.


Visual Studio 2010 Solution Definition

First of all, I created simple WCF solution.
which contains

1) WCF Service project contains
 CustomerService.svc - returns CustomerProfile to client
 OrderManagementService.svc - returns Customer orders

2) Business Logic Library, which contains
 customer.cs  - customer profile class
 Order.cs - Order class
 Enums.cs - Order Status enumeration
 OrderTrackingInfo.cs - Order Tracking information class



Final solution will look like:




Configure WCF Service to use proper serializer

As I described above, there is option to configure serialization mechanism on interface level or at operation level.

Set Serialization at interface level

As sample I decided to use GetCustomer operation, which returns Customer object.
In serialization article I described how to prepare class for different serialization methods.
In Framework 4.0 you can use class as is - it will work in both methods.

Use DataContractSerializer at interface level

If you use visual studio, you don't actually, have to do anything. DataContractSerializer is a default serialization mechanism for the WCF.
I am just digging in it a little bit more.
If you decide to use DataContractSerializer, you have to mark interface ICustomerService with [ServiceContract].
Every operation, which will be available for call you have to mark with [OperationContract]. It is a standard routine to create wcf service nowadays.

    [ServiceContract]
    public interface ICustomerService
    {
        [OperationContract]
        PerformanceTest.WCF.Service.BLL.Customer GetCustomer(string customerId);
 
        [OperationContract]
        bool CustomerExists(string customerId);
    }

In this case, both - GetCustomer and CustomerExists will use DataContractSerializer.
In my case service endpoint is located at following url:
http://localhost/PerformanceTest.WCF.Service/CustomerService.svc

Testing

Set WCF service project as start-up project and "CustomerService.svc" as startup file and press F5 in VS 2010. It will run WCF Test Client. You should see window on next picture.
You can make operation call in test client. If you double mouse click on operation on left panel, it will open operation call parameters on right side.
On the right panel you can see request and response. To make call, you have to enter appropriate input values  and click "invoke", as shown at picture below:



In the result you will see formatted service call response. You can switch from formatted mode to XML mode.
XML mode allows you to see raw SOAP request and response from service as shown below.



Here is sample SOAP service request and response.
Request:

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Header>
    <Action s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">http://tempuri.org/ICustomerService/GetCustomer</Action>
  </s:Header>
  <s:Body>
    <GetCustomer xmlns="http://tempuri.org/">
      <customerId>100</customerId>
    </GetCustomer>
  </s:Body>
</s:Envelope>

Response:

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Header />
  <s:Body>
    <GetCustomerResponse xmlns="http://tempuri.org/">
      <GetCustomerResult xmlns:a="http://schemas.datacontract.org/2004/07/PerformanceTest.WCF.Service.BLL" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
        <a:CustomerId>100</a:CustomerId>
        <a:CustomerMemo i:nil="true" />
        <a:FirstName i:nil="true" />
        <a:LastName i:nil="true" />
      </GetCustomerResult>
    </GetCustomerResponse>
  </s:Body>
</s:Envelope>

Use XmlSerializer at interface level

If you decide to use XmlSerializer at interface level in the same project - you have 2 options:
1) Create new interface ICustomerService2, mark it with the same attributes as in 1), plus add additional attribute at interface level [XmlSerializerFormat]. You can also remove unused operations, like CustomerExists.
   
    [ServiceContract]
    [XmlSerializerFormat]
    public interface ICustomerService2
    {
        [OperationContract]
        PerformanceTest.WCF.Service.BLL.Customer GetCustomer(string customerId);
    }


In this case, both - GetCustomer and CustomerExists will use XmlSerializer.
The service endpoint url is:
http://localhost/PerformanceTest.WCF.Service/CustomerService2.svc

Testing

To test "CustomerService2.svc" service, which uses Xml serialization you should set it as start-up file and press F5 in VS 2010.
It will run the same WCF Test Client. You can see one difference: CustomerExists operation disappeared from list of available
operations because we excluded it from interface.
You will see the difference now when you will try make call:
You have to select request body in dropdown listbox, shown below


enter CustomerId value and click "Invoke"



you can see XML request and response by clicking at "XML" tab:


2) inherite class from the same interface, but mark with [XmlSerializerFormat]

    [XmlSerializerFormat]
    public class CustomerService3 : ICustomerService
    {


Testing

To test "CustomerService3.svc" service, which uses Xml serialization you should set it as start-up file and press F5 in VS 2010.
It will run the same WCF Test Client. You will se the same list of operations as in first case, because it is inherited from the same interface.



Set serialization at operation level:

In sections above I described CustomerProfile service. In this section I will use different service - OrderManagementService.
There is only one endpoint in this case, but serialization mechanism will be defined at operation level.
The service endpoint url is:
http://localhost/PerformanceTest.WCF.Service/OrderManagementService.svc

Default operation serialization is based on settings at interface level. If interface not marked with [XmlSerializerFormat], all operations will use DataContracSerializer and the other way around.
If you want override default serializer at operation level, you have to use [XmlSerializerFormat] or [DataContractFormat].

In the sample below, I created new GetOrders2 operation and marked it with [XmlSerializerFormat]. It will force WCF service to use XmlSerializer on GetOrders2 call.

    [ServiceContract]
    public interface IOrderManagementService
    {
        [OperationContract]
        List<PerformanceTest.WCF.Service.BLL.Order> GetOrders(string customerId);
 
        [OperationContract]
        [XmlSerializerFormat]
        List<PerformanceTest.WCF.Service.BLL.Order> GetOrders2(string customerId);
 
        [OperationContract]
        PerformanceTest.WCF.Service.BLL.Enums.OrderStatus GetOrderStatus(int orderId);
 
        [OperationContract]
        PerformanceTest.WCF.Service.BLL.Order GetOrderByOrderId(int orderId);
    }


Testing

To test "OrderManagementService.svc" service, you should set it as startup file and press F5.
In WCF Test Client you will see GetOrders and GetOrders2 operations. The testing will be pretty same as customer testing.
Testing GetOrders - DataContractSerializer:



Testing GetOrders2 - XmlSerializer:

Tuesday 30 August 2011

How women use kids as a weapon against husbands to get money.


I created this article to describe my current situation and give some tips to other men. I am divorcing my wife and she refuses me so see my son and uses him as weapon to get money. For last 10 years of living together, most of time she didn't work. Every time, I asked her what is she going to do, I never got answer. I was ok with it and was happy to support my family. Personally, I am fine if wife is staying home and does something to help husband to maintain family, but some women do not want work on purpose. I started look at this problem and found some information:


How women use kids as excuse.

I found very good article about some women, who don't want work and use kids as excuse:
http://shrink4men.wordpress.com/2009/01/15/excuses-your-wife-uses-for-not-working/
here is one part from it:

Some woman never wanted to support herself. She played at working as a plan B, trying this and that, until plan A (that would be you) gave her a way out. For some women having a child was a reason to stop working.
Her real goal has always been to have someone take care of her financial and material needs. Ironically, this is also the type of woman who complains bitterly about you working too much and not spending enough time with her or the kid(s).
Just to get you off her back, she may take a very part-time job answering phones, being a “designer,” or volunteer work, but she has no real career aspirations beyond being a dilettante.


Some comments from article above:
1) One guy is talking about his friend: Now they are divorced and he’s sending her $5000 a month (for child support, tax free to her of course) and she still complains. No matter what he does, she is unhappy, blames him for her miserable life and unfortunately, unloads all of her distress on the children. She is very manipulative and uses the kids to try to control him and indeed, throughout their marriage, that was the main issue: she was always trying to control him.

2) I don’t think it’s the man’s responsibility to support another, educated adult who is capable of working. I think it is the couple’s responsibility to support each other and any children they create.

Here is another article, which describes women, who use kid as a weapon (such women have complex):
http://www.shrink4men.com/2011/05/17/does-your-wife-or-ex-wife-have-a-golden-uterus-complex-15-characteristics-of-the-golden-uterus/
some statements from that article above:

Once you have sex with a such woman, she owns you for life. She believes that if she gave birth to your children, you are “connected for life.” She should always come first (even if you’ve both remarried) and YOU OWE HER until death you do part.
This also applies to the children. She wields guilt over their children with staggering virtuosity. “I am your mother. I carried you for 9 months. No one will ever love you like I do. No one will ever break our bond. No one will ever come between us. I CARRIED you in my WOMB for NINE months. YOU can NEVER do that for me.” (I heard many times statement from my wife: "I had being sitting for 2 years with our kid. It is your turn now.")

Such woman uses motherhood as an excuse. “Becoming a ‘mother’ is the her excuse for EVERYTHING. She can’t work because ‘mothers don’t work.’ My husband HAS to give her all of his money because she’s the mother of his ONLY child. She lost all identity as a woman and used becoming a mother as her free ride in life”.
Even after their children are in school full-time, she still uses the kids and being a mother as an excuse not to work outside the home and often not to work inside the home. “You have no idea how stressful it is being a mom.” Um, the kids are in school all day. What do you do with your time? “You always minimize all the hard work I do. YOU HAVE NO IDEA.”
Um, the breakfast dishes are still in the sink when I get home from work in the evening. The laundry is piled up and the kids haven’t done their homework. What did you do all day? “HOW DARE YOU DISRESPECT ME. I’m THE MOTHER OF YOUR CHILDREN!”



What can you do if the mother of your children has such complex?

There’s nothing you can do to change her. Nothing. She’s highly unlikely to see the light and morph into a reasonable human being and good mother. Your goal, as with all high-conflict abusive types, should be containment. You accomplish containment through establishing iron-clad boundaries. Learn to say no and then practice deafening your ears to the caterwauling.
Don’t let her use your children as an extortion mechanism. Don’t allow the children to view you as a human ATM machine. In other words, don’t reward your children’s bad behavior with money, gifts, trips and other goodies, otherwise, they will view you the same way that their mother does. I know many fathers are desperate for time with their children and use toys and expensive entertainment as bait. Trust me, this is not the relationship you want with your children. It’s a quick path to time with them, but it’s an unhealthy and impermanent one.
Decide exactly how much bad behavior you’re willing to tolerate from your ex and what offenses you want to pursue in court. Forget about co-parenting with a such woman; it’s next to impossible. You will be less frustrated if you try to parallel parent. A such woman will undermine you at nearly every turn. Expect it and plan for it.

About my current personal situation

I am a good parent, who always cared about family but one day this happened: 1st April - Fools' day or how my wife sent me to jail

I menationed at the beginning of this article that I am divorcing with my wife and she is refusing me to see my son. I mean she is not letting even communicate with him at all - no phone calls, no pictures. I have full right to be with my son and my son has full right to be with me. I love my son and he loves me. It is very hard for me - adult, but what about kid? The law is working the way, so you have to hire lawyer in such situations. What I am doing now, is trying to get family court order to see my son. Government shouldn't close its eyes on such problems. It is abnormal when kid leave in the same city with parents and cannot see both or one of them. Both parents should participate in kids' life even after divorce. I very hope that will get court order to see son.

I simply want my son spend time with me and I want make his live brighter.
It is almost end of August and school time is on the horizon, so he needs to be ready for that.
It means that clothes and school accessories should be bought for him. Hockey season is coming too (my son plays hockey - Vaughan hockey league) and it is a time to make registration for hockey league and by equipment. But how?? He grew up and I don't even know his size..... I don't even know will my wife bring him for hockey games or not.

Every year my son has dental examination. I called to dental office and explained them situation that I can bring deposit for services and asked them to call to my wife about it, so she can bring him and doctor could check his teeth. My wife simply refused appointment.????? I don't even know what to do.

Interesting fact about people around me: Everybody is interested in what is going on in my criminal and divorce cases - it is no more than entertainment for them. Everybody is giving advices, which would never do it by himself being in my situation. Everybody sorry for what is going with my son and me, but trying not be involved in it. People, who could talk to my wife is not aware of it anymore. Looks like it is expected and it is normal for the society. People are talking about friendly environment and good society at TV and newspapers, people even care about poor kids in Africa. What about our own kids? Why do you think that it is normal to isolate kid from his father just because wife wants money or she is angry at husband?

I had many discussions people around me and was shocked that some of them think like "Many people do such thing as your wife to have power on husbands. Why don't you give her money and she will give you son? You are the man!!!".  What I understood that money it is the main reason why she is not giving my son to me. Actually, there is another reason - she is angry at me regarding my articles (I made comment below about it), but I think it is her cover (some kind of protection from people's bad opinion about her). I even asked "what if I don't have money? What if became poor? What if my son simply wants see me and I want see him? What about kid's soul? Why do you measure everything in money only?..." - I didn't get answer.

Looks like nowadays people think about money only. There is nothing saint anymore.
I don't have problems to support my son financially and happy to do it, but my wife should start think about live on her own. My wife is playing role of a poor mom now, who doesn't have money even to feed our son. She simply uses him to make public opinion against me. She knows that if my son would be with see me one a week, he would be happy and I would supply him with what he needs, but she is keep doing that bad thing because she needs money but not food. She doesn't even think about kid.

My wife knows that my son will be happy with me and cannot accept it. She told my friends that normal people should support their families - I totally agree on that, but can only tell that there is no our family anymore - she ruined it. There is only my son and me - it is my family now. I would do anything to make his life easier, but will never support her as before. I am send child support via my lawyer on monthly basis and putting money to my son's personal bank account. I asked many times my wife before to sell the house, put all money to son's account and I would support my wife for a while. I understand that life is a challenge and if we couldn't live together, let’s give everything to kid and start new life. She didn't accept my offer - she wanted to have money in her pocket. She already hired lawyer and those money will be paid off from the house sell. It means that son will get nothing.

The problem is that my wife is not working or may be working but it is not enough for her life style and expects me to supply her money desire. I feel that even if I start give her money, in half a year she will tell me that it is not enough and will do the same thing as now - do not let me see my son. I have read many forums and articles - people are confirming that in many cases women do exactly the same thing as I described. I talked with my wife, before our family got into the problem, about here unemployment, so I asked her to start look for job and be independent in financial aspect. I told her many times that If you don't work in Canada, even if we split property by 50/50, it will be zero in less one year (It has only 50k in downpayment). My point was: "You should be independent and be able maintain yourself and son if you want live separated, especially with kid" - She sent me to jail instead of it.


What advices you can hear from people around you?

1) Make her bad in front of law because she is using your kid against you.
2) Give everything (money) to her and forget her.
3) Be strong - everything will be fine (common advice - very generic. It is the same as somebody is cutting your hand and telling you - relax, everything will be fine).
4) You guys hate each other and there is only one solution is to change yourself - start respect her and give her money.

I can only say that almost none of these advices above work for me.

1) I don't want make anything bad for her because it will affect kid. I simply want participate in my kid's life.
2) I don't want support person, who fck.d me up.
3) I am trying to be strong, but my hurt is broken. As for fine days, by statistic it takes up to 3 years to forget about it for adults, but can affect whole kid's life.
4) I will never respect person, who betrayed me. I read many articles about how after divorce husbands start play actor's role, looks like they have been changed their feelings to her ex-wife.
There is only one reason for that - see their kids. As for me, I don't want to have fake feelings.

P.S.

As for articles about my personal situation: I heard many advices to remove everything what I wrote, related to my wife - it makes our relations even worse. First of all, I am writing about my life - facts and my thought. Second: there is no relations with my wife anymore. I am not going live forever. May be it is the only one chance to say something. I heard recently one guy who talked with his wife, who didn't give him to see his daughter for 8 months - I heard only fck...s. Women, please, do not do mistakes, you should understand that kids need to see their fathers who can care about them, so kids will fill life support.

Tuesday 23 August 2011

Framework 4.0 - XmlSerializer vs DataContractSerializer. Prepare class for serialization. Performance.

Serialization is the process of persisting data structure or object state. You can persist object state to file, database, memory, ..... XML is the common format to transfer data between systems.
You can find in internet many articles about different serializers. I will review 2 common: XmlSerializer and DataContractSerializer. DataContractSerializer was proposed by Microsoft as new faster way to persists objects - It used in WCF. Based on tasks you have to be ready to use one or another, or both. Before use these serializers you should understand how class will be persisted.
For some security reasons, you will probably need hide some class properties before send class to client, such as financial data. In this article I will describe how to do it and will review persistence to file only.

Prepare class for serialization.

If you use Framework 4.0, you don't have to make any special preparations for serialization, but if you want have control on serialization, you should mark class and it's properties with special attributes.
Here is a sample, which prove that you don't have to do anything, but result will be different in every serialization method. Here is sample with Xml Serializer:
Let's say you want serialize following class:

    public class Order
    {
        public string sId = "test";
        public string CustomerId { getset; }
        public string OrderId { getset; }
        public int TrackingId { getset; }
        public System.DateTime DateCreated { getset; }
        public Enums.OrderStatus Status { getset; }
    }

class initialization:

            //try create object and serialize it
            Order order = new Order();
            order.CustomerId = "1902";
            order.Status = OrderStatus.Completed;
            order.DateCreated = System.DateTime.UtcNow;
            order.TrackingId = 100;

1) Use XmlSerializer

following code you can use to serialize class to external file:

System.Xml.Serialization.XmlSerializer sr0 = new System.Xml.Serialization.XmlSerializer(order.GetType());
using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(@"c:\order_100.xml"))
{
    sr0.Serialize(writer, order);
    writer.Close();
}

a) class without serialization attributes and save it to file. All public properties and variables will be serialized by default.
code above will generate following xml:

<?xml version="1.0" encoding="utf-8"?>
<Order xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <sId>test</sId>
  <CustomerId>1902</CustomerId>
  <TrackingId>100</TrackingId>
  <DateCreated>2011-08-23T01:44:29.6794597Z</DateCreated>
  <Status>Completed</Status>
</Order>


b) if you use XmlSerializer and want control on serialization you should mark class as [Serializable].
If you want exclude some properties from serialization, you should mark them with [System.Xml.Serialization.XmlIgnore].
If you want property as an xml attribute instead of xml element during serialization, you can use [System.Xml.Serialization.XmlAttribute(....)]

    [Serializable]
    public class Order
    {
        public string sId = "test";
        public string CustomerId { getset; }
        [System.Xml.Serialization.XmlElement(IsNullable = true)]
        public string OrderId { getset; }
        [System.Xml.Serialization.XmlIgnore]
        public int TrackingId { getset; }
        [System.Xml.Serialization.XmlAttribute("OrderDate")]
        public System.DateTime DateCreated { getset; }
        [System.Xml.Serialization.XmlElement("OrderStatus")]
        public Enums.OrderStatus Status { getset; }
    }

In the result you will get following xml:

<?xml version="1.0" encoding="utf-8"?>
<Order xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" OrderDate="2011-08-23T16:10:14.3406181Z">
  <sId>test</sId>
  <CustomerId>1902</CustomerId>
  <OrderStatus>Completed</OrderStatus>
</Order>

As you can see, TrackingId was excluded from the xml, DateCrated became as an attribute with name OrderDate, Status was renamed to OrderStatus, OrderId doesn't have assigned value but xml node appears in xml.

2) use DataContractSerializer

You can use following code to serialize class:

System.Runtime.Serialization.DataContractSerializer sr1 = new System.Runtime.Serialization.DataContractSerializer(order.GetType());
using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(@"c:\order_100_dc.xml"))
{
    sr1.WriteObject(writer, order);
    writer.Close();
}

a) class is not marked with any serialization attributes
The result will be:

<?xml version="1.0" encoding="utf-8"?>
<Order xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/PerformanceTest.Serialization.BLL">
  <CustomerId>1902</CustomerId>
  <DateCreated>2011-08-23T04:16:08.4371221Z</DateCreated>
  <OrderId i:nil="true" />
  <Status>Completed</Status>
  <TrackingId>100</TrackingId>
  <sId>test</sId>
</Order>

As you can see, it is pretty same result, but xmlns contains project workspace. There is one more difference - public variable at the end of the xml.

b) use the same class as in 1b):

<?xml version="1.0" encoding="utf-8"?>
<Order xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/PerformanceTest.Serialization.BLL">
  <_x003C_CustomerId_x003E_k__BackingField>1902</_x003C_CustomerId_x003E_k__BackingField>
  <_x003C_DateCreated_x003E_k__BackingField>2011-08-23T04:21:49.8596503Z</_x003C_DateCreated_x003E_k__BackingField>
  <_x003C_OrderId_x003E_k__BackingField i:nil="true" />
  <_x003C_Status_x003E_k__BackingField>Completed</_x003C_Status_x003E_k__BackingField>
  <_x003C_TrackingId_x003E_k__BackingField>100</_x003C_TrackingId_x003E_k__BackingField>
  <sId>test</sId>
</Order>

Instead of clean xml element names you can see _x003C_, _x003E etc. This is DataContractSerializer pattern. you still can see that public variable sId is visible as it was.

c) To have full control on class serialization with DataContractSerializer, you should mark class with [DataContract] and every property, which will be serialized with [DataMember]. If you mark class with [DataContract] only, none of properties will be serialized.
for example, if you want serialize sId, CustomerId and OrderId, you have to mark class as follows:

    [DataContract]
    public class Order
    {
        [DataMember]
        public string sId = "test";
        [DataMember]
        public string CustomerId { getset; }
        [DataMember]
        public string OrderId { getset; }
        public int TrackingId { getset; }
        public System.DateTime DateCreated { getset; }
        public Enums.OrderStatus Status { getset; }
    }

In the result you will get following XML:

<?xml version="1.0" encoding="utf-8"?>
<Order xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/PerformanceTest.Serialization.BLL">
  <CustomerId>1902</CustomerId>
  <OrderId i:nil="true" />
  <sId>test</sId>
</Order>
DataContract attribute has overloads, where you can specify namespace.

d) can be class marked both with [Serializable] and [DataContract]?. The answer is yes:
It is used when you have heterogeneous systems with different clients. Some clients can use XmlSerializer and some DataContractSerializer.

    [DataContract(Namespace = "http://Supplier1.org/OMS/Order")]
    [Serializable]
    [System.Xml.Serialization.XmlRoot(Namespace = "http://Supplier1.org/OMS/Order")]
    public class Order
    {
        [DataMember]
        public string sId = "test";
        [DataMember]
        public string CustomerId { getset; }
        [DataMember]
        [System.Xml.Serialization.XmlElement(IsNullable = true)]
        public string OrderId { getset; }
        [System.Xml.Serialization.XmlIgnore]
        public int TrackingId { getset; }
        [System.Xml.Serialization.XmlAttribute("OrderDate")]
        public System.DateTime DateCreated { getset; }
        [System.Xml.Serialization.XmlElement("OrderStatus")]
        public Enums.OrderStatus Status { getset; }
    }



Attributes will be applied based on what serialization method do you use. XmlDataContractSerializer will first look at [DataContract] attribute. If there is no such it will check if [Serializable] is specified and check for [System.Xml.Serialization.....] attributes. If there is no any attributes - default behaviour will be applied. I will describe it later, but it plays very important role when you have many back-end systems with the same class. For example, you have different product supplies and every product supplier has its own order management system. The problem is that every system uses object with the same name - order. To separate it somehow, you should use different namespaces.

Here is a sample how you can do it for DataContractSerializer (OMS - order management system):

[DataContract(Namespace = "http://Supplier1.org/OMS/Order")]
[DataContract(Namespace = "http://Supplier2.org/OMS/Order")]

The same result you can achieve for XmlSerializer by using XmlRoot attribute:

[System.Xml.Serialization.XmlRoot(Namespace = "http://Supplier1.org/OMS/Order")]
[System.Xml.Serialization.XmlRoot(Namespace = "http://Supplier2.org/OMS/Order")]


Deserialization

There is nothing special in this section:
1) Deserialization object from file by using XmlSerializer

Order order = null;
System.Xml.Serialization.XmlSerializer sr2 = new System.Xml.Serialization.XmlSerializer(typeof(Order));
using (System.Xml.XmlReader reader = System.Xml.XmlReader.Create(@"c:\order_100.xml"))
{
    order = (Order)sr2.Deserialize(reader);
}
2) Deserialization object from file by using DataContractSerializer

Order order = null;
System.Runtime.Serialization.DataContractSerializer sr3 = new System.Runtime.Serialization.DataContractSerializer(typeof(Order));
using (System.Xml.XmlReader reader = System.Xml.XmlReader.Create(@"c:\order_100_dc.xml"))
{
    order = (Order)sr3.ReadObject(reader);
}

3) Actually there is one special thing:
If your object was serialized by old framework with special characters your xml could look like this:

<?xml version="1.0" encoding="utf-8"?>
<Order xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <CustomerId>&#xB;</CustomerId>
  <OrderId>0</OrderId>
  <DateCreated>2011-08-11T16:48:44.9546066Z</DateCreated>
  <Status>Completed</Status>
</Order>

xml contains special symbol "0xb", which is not acceptable by XML standard. In ideal world it should be encoded as "&amp;#xB;".

No matter what method do you use you will get something like this:
"There was an error deserializing the object of type ........ ' ', hexadecimal value 0x0B, is an invalid character. Line 1, position ...."



There is a solution from Microsoft - use serializer settings XmlWriterSettings with option CheckCharacters during deserialization. Some people write xml parsers, before pass it to deserialization function.

Performance

I created simple application to make 5000 serializations to local file for both serializes.
Here is result:



Not bad for DataContractSerializer!

How to improve XmlSerializer performance?

There is one method to do it - you have to make serialization dlls by using sgen tool.
Otherwise runtime will use temporary folder to build it. If you have multithread application, it will do it again again and again, which will involve disk IO. I prefer update VS project, which contains classes to be serialized, so every time you make build it will generate such dlls. To do it you have to right mouse click on project and select "Unload project" in popup menu



right mouse click and select "Edit <project name>"



I simply edit project definition with this text an the end of file, right before </Project>:

  <Target Name="GenerateSerializationAssembliesForAllTypes" DependsOnTargets="AssignTargetPaths;Compile;ResolveKeySource" Inputs="$(MSBuildAllProjects);@(IntermediateAssembly)" Outputs="$(OutputPath)$(_SGenDllName)">
    <SGen BuildAssemblyName="$(TargetFileName)" BuildAssemblyPath="$(OutDir)" References="@(ReferencePath)" ShouldGenerateSerializer="true" UseProxyTypes="false" KeyContainer="$(KeyContainerName)" KeyFile="$(KeyOriginatorFile)" DelaySign="$(DelaySign)" ToolPath="$(SGenToolPath)">
      <Output TaskParameter="SerializationAssembly" ItemName="SerializationAssembly" />
    </SGen>
  </Target>
  <Target Name="BeforeBuild">
  </Target>
  <Target Name="AfterBuild" DependsOnTargets="GenerateSerializationAssembliesForAllTypes">
  </Target>

After you saved file, right mouse click on project and select "Reload project"



Rebuild project and open output folder.
If you class library project name is "PerformanceTest.Serialization.BLL" you will see
PerformanceTest.Serialization.BLL.dll and extra one dll, generated by sgen:
PerformanceTest.Serialization.BLL.XmlSerializers.dll (this dll will be used by xmlSerializer to serialize and deserialize objects). By generating that dll you will prevent process to use temp folder to build it during runtime.