This is the Day 7 article. If you have not read the previous articles then please go through the following articles:
- Day 1 - WCF Introduction and Contracts
- Day 2 - WCF Fault Contracts
- Day 3 - WCF Message Exchange Patterns
- Day 4 - WCF DataContract
- Day 5 - WCF Difference between service application and service library
- 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
Select "WCF" from Installed Templates.
Select "WCF Service Library" and give a proper name, for example "AuthorSerializationLibrary".
Create one DataContract in the Interface i.e. IService1.cs using the following code:
- namespace AuthorServiceLibrary
- {
- [ServiceContract]
- public interface IService1
- {
- }
- [DataContract]
- public class Author
- {
- [DataMember]
- public string FirstName;
- [DataMember]
- public string LastName;
- [DataMember]
- public DateTime StartDate;
- [DataMember]
- public string ArticleName;
- }
- }
I have not created an operation contract. So there is no code in the service class.
- namespace AuthorServiceLibrary
- {
- public class Service1 : IService1
- {
- }
- }
Now right-click on the Solution file and select Add >> New Project, as in:
Select "Windows" from the Installed Templates.
Select "Console Application" and give it the name "AuthorSerialization", as in:
Add a reference for "AuthorServiceLibrary" into "AuthorSerialization".
Right-click on "References" in AuthorSerialization and select "Add Reference...", as in:
Select "AuthorServiceLibrary" from the Projects tab.
Press the "OK" button.
One more time right-click on references and select "Add Reference…", as in:
Select "System.Runtime.Serialization" from the .NET tab, as in:
Import the System.Runtime.Serialization namespace into the console application "AuthorSerialization"; see:
Create a static function to serialize data in the program.cs file of "AuthorSerialization" using:
- static void Serialize()
- {
- Author author = new Author();
- author.FirstName = "Akshay";
- author.LastName = "Patel";
- author.StartDate = DateTime.Now;
- author.ArticleName = "WCF - Serialization - Day 6";
- using (FileStream fs = new FileStream("author.xml", FileMode.Create))
- {
- DataContractSerializer dcSerializer = new DataContractSerializer(typeof(Author));
- dcSerializer.WriteObject(fs, author);
- }
- }
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:
- static void Deserialize()
- {
- using (FileStream fs = new FileStream("author.xml", FileMode.Open))
- {
- DataContractSerializer dcSerializer = new DataContractSerializer(typeof(Author));
- Author author = dcSerializer.ReadObject(fs) as Author;
- Console.WriteLine("Name: {0}, Article: {1}", author.FirstName,author.ArticleName);
- }
- }
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:
- static void Main(string[] args)
- {
- if (args.Length > 0 && args[0].Equals("ds"))
- Deserialize();
- else
- Serialize();
- }
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".
Now you will see in the output window that "Build: 2 succeeded or up-to-date".
Open a Visual Studio Command Prompt; see:
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.
Now open the author.xml file in Internet Explorer.
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.
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.
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.
Now open AuthorServiceLibrary.xsd in notepad.
Now with the same svcutil generate the .cs file. You can see in the command prompt.
Now open the AuthorServiceLibrary.cs file in Notepad.
This is our original code generated back by the tool.
-
-
-
-
-
-
-
-
-
- namespace AuthorServiceLibrary
- {
- using System.Runtime.Serialization;
- [System.Diagnostics.DebuggerStepThroughAttribute()]
- [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
- [System.Runtime.Serialization.DataContractAttribute(Name = "Author", Namespace = "http://schemas.datacontract.org/2004/07/AuthorServiceLibrary")]
- public partial class Author : object, System.Runtime.Serialization.IExtensibleDataObject
- {
- private System.Runtime.Serialization.ExtensionDataObject extensionDataField;
- private string ArticleNameField;
- private string FirstNameField;
- private string LastNameField;
- private System.DateTime StartDateField;
- public System.Runtime.Serialization.ExtensionDataObject ExtensionData
- {
- get
- {
- return this.extensionDataField;
- }
- set
- {
- this.extensionDataField = value;
- }
- }
- [System.Runtime.Serialization.DataMemberAttribute()]
- public string ArticleName
- {
- get
- {
- return this.ArticleNameField;
- }
- set
- {
- this.ArticleNameField = value;
- }
- }
- [System.Runtime.Serialization.DataMemberAttribute()]
- public string FirstName
- {
- get
- {
- return this.FirstNameField;
- }
- set
- {
- this.FirstNameField = value;
- }
- }
- [System.Runtime.Serialization.DataMemberAttribute()]
- public string LastName
- {
- get
- {
- return this.LastNameField;
- }
- set
- {
- this.LastNameField = value;
- }
- }
- [System.Runtime.Serialization.DataMemberAttribute()]
- public System.DateTime StartDate
- {
- get
- {
- return this.StartDateField;
- }
- set
- {
- this.StartDateField = value;
- }
- }
- }
- [System.Diagnostics.DebuggerStepThroughAttribute()]
- [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
- [System.Runtime.Serialization.DataContractAttribute(Name = "Service1", Namespace = "http://schemas.datacontract.org/2004/07/AuthorServiceLibrary")]
- public partial class Service1 : object, System.Runtime.Serialization.IExtensibleDataObject
- {
- private System.Runtime.Serialization.ExtensionDataObject extensionDataField;
- public System.Runtime.Serialization.ExtensionDataObject ExtensionData
- {
- get
- {
- return this.extensionDataField;
- }
- set
- {
- this.extensionDataField = value;
- }
- }
- }
- }