WCF Serialization Part 2: Day 7

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:

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:

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:
 

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".

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.
 

//------------------------------------------------------------------------------

// <auto-generated>

//     This code was generated by a tool.

//     Runtime Version:4.0.30319.17020

//

//     Changes to this file may cause incorrect behavior and will be lost if

//     the code is regenerated.

// </auto-generated>

//------------------------------------------------------------------------------

 

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;

            }

        }

    }

}

 

 

Up Next
    Ebook Download
    View all
    Learn
    View all