WCF Serialization Part 2: Day 7

In this article, we create an application, in this application we use a DataContractSerializer to serialize and deserialize data. We also see how we can use SvcUtil.exe

This is the Day 7 article. If you have not read the previous articles then please go through the following articles:
  1. Day 1 - WCF Introduction and Contracts
  2. Day 2 - WCF Fault Contracts
  3. Day 3 - WCF Message Exchange Patterns
  4. Day 4 - WCF DataContract
  5. Day 5 - WCF Difference between service application and service library
  6. Day 6 - WCF Serialization

Introduction

 
In this article, we create an application, in this application we use a DataContractSerializer to serialize and deserialize data. We also see how we can use SvcUtil.exe.
 

Step-by-step implementation of DataContractSerializer

 
File -> New -> Project
 
implementation-of-DataContractSerializer.jpg 
 
Select "WCF" from Installed Templates.
 
Select "WCF Service Library" and give a proper name, for example "AuthorSerializationLibrary".
 
Select-WCF-Service-Library.jpg 
 
Create one DataContract in the Interface i.e. IService1.cs using the following code:
  1. namespace AuthorServiceLibrary  
  2. {  
  3.     [ServiceContract]  
  4.     public interface IService1  
  5.     {  
  6.     }  
  7.     [DataContract]  
  8.     public class Author  
  9.     {  
  10.         [DataMember]  
  11.         public string FirstName;  
  12.         [DataMember]  
  13.         public string LastName;  
  14.         [DataMember]  
  15.         public DateTime StartDate;  
  16.         [DataMember]  
  17.         public string ArticleName;  
  18.     }  
  19. }  
I have not created an operation contract. So there is no code in the service class. 
  1. namespace AuthorServiceLibrary  
  2. {  
  3.     public class Service1 : IService1  
  4.     {  
  5.     }  
  6. }  
Now right-click on the Solution file and select Add >> New Project, as in:
 
Solution-file-and-select-Add-New-Project.jpg 
 
Select "Windows" from the Installed Templates.
 
Select "Console Application" and give it the name "AuthorSerialization", as in:
 
Select-Console-Application.jpg 
 
Add a reference for "AuthorServiceLibrary" into "AuthorSerialization".
 
Right-click on "References" in AuthorSerialization and select "Add Reference...", as in:
 
References-AuthorSerialization.jpg 
 
Select "AuthorServiceLibrary" from the Projects tab.
 
Press the "OK" button.
 
Select-AuthorServiceLibrary.jpg 
 
One more time right-click on references and select "Add Reference…", as in:
 
select-Add-Reference.jpg 
 
Select "System.Runtime.Serialization" from the .NET tab, as in:
 
Select-System.Runtime.Serialization.jpg 
 
Import the System.Runtime.Serialization namespace into the console application "AuthorSerialization"; see:
 
Import-System.Runtime.Serialization.jpg 
 
Create a static function to serialize data in the program.cs file of "AuthorSerialization" using:
  1. static void Serialize()  
  2. {  
  3.     Author author = new Author();  
  4.     author.FirstName = "Akshay";  
  5.     author.LastName = "Patel";  
  6.     author.StartDate = DateTime.Now;  
  7.     author.ArticleName = "WCF - Serialization - Day 6";  
  8.     using (FileStream fs = new FileStream("author.xml", FileMode.Create))  
  9.     {  
  10.         DataContractSerializer dcSerializer = new DataContractSerializer(typeof(Author));  
  11.         dcSerializer.WriteObject(fs, author);  
  12.     }  
  13. }  
In the preceding Serialize function we create an object of the Author class and assign some values to each field. We create a .xml file using a FileStream object. After that we serialize the class using DataContractSerializer and write into the .xml file.
 
Create one more function to deserialize the data under the preceding function; the code is:
  1. static void Deserialize()  
  2. {  
  3.     using (FileStream fs = new FileStream("author.xml", FileMode.Open))  
  4.     {  
  5.        DataContractSerializer dcSerializer = new DataContractSerializer(typeof(Author));  
  6.        Author author = dcSerializer.ReadObject(fs) as Author;  
  7.        Console.WriteLine("Name: {0}, Article: {1}", author.FirstName,author.ArticleName);  
  8.     }  
  9. }  
In the preceding code we open author.xml with the help of a FileStream object. We create an object of DataContractSerializer and read the file.
 
Add the following lines of code in the main function:
  1. static void Main(string[] args)  
  2. {  
  3.     if (args.Length > 0 && args[0].Equals("ds"))  
  4.         Deserialize();  
  5.     else  
  6.         Serialize();  
  7. }  
In the preceding code we check the length of args and args equal to ds, if it fulfills the condition then call the Deserialize function and if not then call the Serialize function. In other words, if you want to call the Deserialize function then pass "ds" as an argument.
 
Now build the console application "AuthorSerialization".
 
For that right-click on the AuthorSerialization project and select "Build".
 
console-application-AuthorSerialization.jpg 
 
Now you will see in the output window that "Build: 2 succeeded or up-to-date".
 
output-window.jpg 
 
Open a Visual Studio Command Prompt; see:
 
Visual-Studio-Command-Prompt.jpg 
 
Now navigate to the path where you created your AuthorSerialization application. Navigate to bin and in that go to debug.
 
Run the command dir, it will show all files and directories contained in the debug folder.
 
Run AuthorSerialization.exe.
 
Once you have executed it successfully, run the dir command.
 
You will see that an author.xml file has been created.
 
author.xml-file.jpg 
 
Now open the author.xml file in Internet Explorer.
 
open-author.xml-file.jpg 
 
Here in author.xml "Author" is a root element because we declared a DataContract with this name. In this element you can see ArticleName, FirstName, LastName, StartDate and their values which we have supplied. The very important thing you can observe is that all elements in the author element is in alphabetical order. In my previous article (WCF DataContract - Day 4) we have seen the order attribute of DataContract. Here we are not setting the order attribute so by default the DataContract is generated in alphabetical order.
 
default-DataContract.jpg 
 
Previously we ran AuthorSerialization.exe without a parameter i.e. we do a serialization process; now the deserialize method is called. For that run AuthorSerialization.exe with the "ds" parameter.
 
run-AuthorSerialization.exe.jpg 
 
Now generate a XSD of our DataContract with the help of svcutil.exe.

Run the following command: svcutil /dconly AuthorServiceLibrary.dll
 
In the above command "dconly" means DataContract only.
 
Once you run this command, it will generate a .xsd file.
 
generate-.xsd file.jpg 
 
Now open AuthorServiceLibrary.xsd in notepad.
 
open-AuthorServiceLibrary.xsd.jpg
 
notepad-AuthorServiceLibrary.xsd.jpg 
 
Now with the same svcutil generate the .cs file. You can see in the command prompt.
 
svcutil-generate.jpg 
 
Now open the AuthorServiceLibrary.cs file in Notepad.
 
AuthorServiceLibrary.cs.jpg 
 
This is our original code generated back by the tool.
  1. //---------------------------------------------------------  
  2. // <auto-generated>  
  3. //     This code was generated by a tool.  
  4. //     Runtime Version:4.0.30319.17020  
  5. //  
  6. //     Changes to this file may cause incorrect behavior and will be lost if  
  7. //     the code is regenerated.  
  8. // </auto-generated>  
  9. //---------------------------------------------------------  
  10. namespace AuthorServiceLibrary  
  11. {  
  12.     using System.Runtime.Serialization;  
  13.     [System.Diagnostics.DebuggerStepThroughAttribute()]  
  14.     [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization""4.0.0.0")]  
  15.     [System.Runtime.Serialization.DataContractAttribute(Name = "Author", Namespace = "http://schemas.datacontract.org/2004/07/AuthorServiceLibrary")]  
  16.     public partial class Author : object, System.Runtime.Serialization.IExtensibleDataObject  
  17.     {  
  18.         private System.Runtime.Serialization.ExtensionDataObject extensionDataField;  
  19.         private string ArticleNameField;  
  20.         private string FirstNameField;  
  21.         private string LastNameField;  
  22.         private System.DateTime StartDateField;  
  23.         public System.Runtime.Serialization.ExtensionDataObject ExtensionData  
  24.         {  
  25.             get  
  26.             {  
  27.                 return this.extensionDataField;  
  28.             }  
  29.             set  
  30.             {  
  31.                 this.extensionDataField = value;  
  32.             }  
  33.         }  
  34.         [System.Runtime.Serialization.DataMemberAttribute()]  
  35.         public string ArticleName  
  36.         {  
  37.             get  
  38.             {  
  39.                 return this.ArticleNameField;  
  40.             }  
  41.             set  
  42.             {  
  43.                 this.ArticleNameField = value;  
  44.             }  
  45.         }  
  46.         [System.Runtime.Serialization.DataMemberAttribute()]  
  47.         public string FirstName  
  48.         {  
  49.             get  
  50.             {  
  51.                 return this.FirstNameField;  
  52.             }  
  53.             set  
  54.             {  
  55.                 this.FirstNameField = value;  
  56.             }  
  57.         }  
  58.         [System.Runtime.Serialization.DataMemberAttribute()]  
  59.         public string LastName  
  60.         {  
  61.             get  
  62.             {  
  63.                 return this.LastNameField;  
  64.             }  
  65.             set  
  66.             {  
  67.                 this.LastNameField = value;  
  68.             }  
  69.         }  
  70.         [System.Runtime.Serialization.DataMemberAttribute()]  
  71.         public System.DateTime StartDate  
  72.         {  
  73.             get  
  74.             {  
  75.                 return this.StartDateField;  
  76.             }  
  77.             set  
  78.             {  
  79.                 this.StartDateField = value;  
  80.             }  
  81.         }  
  82.     }  
  83.     [System.Diagnostics.DebuggerStepThroughAttribute()]  
  84.     [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization""4.0.0.0")]  
  85.     [System.Runtime.Serialization.DataContractAttribute(Name = "Service1", Namespace = "http://schemas.datacontract.org/2004/07/AuthorServiceLibrary")]  
  86.     public partial class Service1 : object, System.Runtime.Serialization.IExtensibleDataObject  
  87.     {  
  88.         private System.Runtime.Serialization.ExtensionDataObject extensionDataField;  
  89.         public System.Runtime.Serialization.ExtensionDataObject ExtensionData  
  90.         {  
  91.             get  
  92.             {  
  93.                 return this.extensionDataField;  
  94.             }  
  95.             set  
  96.             {  
  97.                 this.extensionDataField = value;  
  98.             }  
  99.         }  
  100.     }  
  101. }