Data Contract And Known Type In WCF

In this article, we will learn about what data contract and known type are in WCF. We will also see their usage and how to mention them. 
 
Let's start!
 

What is Contract in WCF

 
Contract provides the way to know about WCF service and communicate with it. There are four type of contracts available in WCF,
  1. Service Contract
  2. Operation Contract
  3. Data Contract
  4. Message Contract
But in this article, we do not see anything about those contracts except the Data contract.
 

What is Data Contract?

 
It is used to mention the custom or user defined data type into the WCF service. If you ask question such as, "Can’t we achieve it without mentioning the Data contract?" The answer will be "Yes, you can do it."  By default the Data Contract Serializer can do this work.
 
This time, again one question may arise; that is,  why we need to mention it? The Data Contract Serializer class serializes all data including private data. For that purpose we mention the DataContract attribute in it. There are two attributes used in the DataContract,
  1. DataContract Attribute
  2. DataMember Attribute
The DataContract attribute is used to mention the custom class as data contract and the DataMember attribute is used to mention the data member as a member of the data contract. We can use this for both the data member and properties of the class.
 
Let us see the steps to create the WCF service and capture it in a client application with data contract.
 
Step 1: Create one Service library named StudentServiceLib.
 
Step 2: For creating the DataContract create one class named Student and include the code like this,
  1. [DataContract]  
  2. public class Student  
  3. {  
  4.     [DataMember]  
  5.     public string Name  
  6.     {  
  7.         get;  
  8.         set;  
  9.     }  
  10.     [DataMember]  
  11.     public string Department  
  12.     {  
  13.         get;  
  14.         set;  
  15.     }  
  16.     [DataMember]  
  17.     public int Year;  
  18. }  
Note:
 
Here, I mention the DataMember attribute for both properties and public member of the class. It’s just for now, we can specify the DataMember attribute.
 
Step 3: WCF Service in the name StudentService and mention the code like this.
  1. [ServiceContract]  
  2. public interface IStudentService   
  3. {  
  4.     [OperationContract]  
  5.     Student GetStudent(string name);  
  6.   
  7.     [OperationContract]  
  8.     void SaveStudent(Student student);  
  9. }  
  10.   
  11. public class StudentService: IStudentService   
  12. {  
  13.     public Student GetStudent(string name)  
  14.     {  
  15.         switch (name)  
  16.         {  
  17.             case "sakthi":  
  18.                 return new Student  
  19.                 {  
  20.                     Name = "sakthi", Department = "MCA", Year = 3  
  21.                 };  
  22.             case "kumar":  
  23.                 return new Student  
  24.                 {  
  25.                     Name = "sakthi", Department = "BCA", Year = 3  
  26.                 };  
  27.             default:  
  28.                 return new Student  
  29.                 {  
  30.                     Name = name, Department = "BE", Year = 3  
  31.                 };  
  32.         }  
  33.     }  
  34.   
  35.     public void SaveStudent(Student student)  
  36.     {  
  37.   
  38.     }  
  39. }  
If you want to know how to create WCF service, please refer my following article, Host The Application With Multiple Endpoints In Self Hosting,
 
That’s all. Our service is ready to host and implement the following configuration and code to self host the application in a new console application named StudentService.
  1. <system.serviceModel>  
  2.     <services>  
  3.         <service name="StudentServiceLib.StudentService" behaviorConfiguration="mexBehaviour">  
  4.             <endpoint address="StudentService" binding="basicHttpBinding" contract="StudentServiceLib.IStudentService"></endpoint>  
  5.             <host>  
  6.                 <baseAddresses>  
  7.                     <add baseAddress="http://localhost:8085" />  
  8.                 </baseAddresses>  
  9.             </host>  
  10.         </service>  
  11.     </services>  
  12.     <behaviors>  
  13.         <serviceBehaviors>  
  14.             <behavior name="mexBehaviour">  
  15.                 <serviceMetadata httpGetEnabled="true" />  
  16.             </behavior>  
  17.         </serviceBehaviors>  
  18.     </behaviors>  
  19. </system.serviceModel>  
  20.   
  21. ServiceHost host = new ServiceHost(typeof(StudentServiceLib.StudentService)); Console.WriteLine("Try to start the service..."); host.Open(); Console.WriteLine("Service started successfully..."); Console.WriteLine("Press any key to stop the service."); Console.ReadKey();  
Build the solution and run the StudentServer.exe in the administrator mode. If it run successfully the console window will be like the following:
 
solution  
 
Add the service reference in the client application and implement the code like this to retrieve the student detail.
 
reference  
  1. StudentServiceClient client = new StudentServiceClient();  
  2. Student student = client.GetStudent("sakthi");  
  3. Console.WriteLine("****** Student Detail ******");  
  4. Console.WriteLine("****************************");  
  5. Console.WriteLine("Student Name : " + student.Name);  
  6. Console.WriteLine("Department : " + student.Department);  
  7. Console.WriteLine("Year : " + student.Year);  
  8. Console.ReadKey();  
If we run the application, the output will be like this,
 
output  
 
Now, we finished the sample application to define the DataContract and run the application. Let us see what is Know type, its usage and how to define it.
 

What is Known Type

 
It is nothing but the client wans to know if the particular class is child class of a class. It will be declared by the KnownType attribute in the base class of this process, called known type.
 
Let us alter the above sample and implement the following code,
  1. [DataContract]  
  2. [KnownType(typeof(HostelStudent))]  
  3. public class Student  
  4. {  
  5.     [DataMember]  
  6.     public string Name   
  7.     {  
  8.         get;  
  9.         set;  
  10.     }  
  11.     [DataMember]  
  12.       
  13.     public string Department  
  14.     {  
  15.         get;  
  16.         set;  
  17.     }  
  18.     [DataMember]  
  19.     public int Year;  
  20.   
  21. }  
  22.   
  23.   
  24. [DataContract]  
  25. public class HostelStudent: Student  
  26. {  
  27.     [DataMember]  
  28.     public string RoomNumber  
  29.     {  
  30.         get;  
  31.         set;  
  32.     }  
  33. }  
  34.   
  35. public class StudentService: IStudentService   
  36. {  
  37.     public Student GetStudent(string name)   
  38.     {  
  39.         switch (name)   
  40.         {  
  41.             case "sakthi":  
  42.                 return new HostelStudent   
  43.                 {  
  44.                     Name = "sakthi", Department = "MCA", Year = 3, RoomNumber = "A124"  
  45.                 };  
  46.             case "kumar":  
  47.                 return new Student  
  48.                 {  
  49.                     Name = "sakthi", Department = "BCA", Year = 3  
  50.                 };  
  51.             default:  
  52.                 return new Student  
  53.                 {  
  54.                     Name = name, Department = "BE", Year = 3  
  55.                 };  
  56.         }  
  57.     }  
  58.   
  59.     public void SaveStudent(Student student)   
  60.     {  
  61.   
  62.     }  
  63. }  
Update the client service reference and change the client code like this,
  1. StudentServiceClient client = new StudentServiceClient();  
  2. HostelStudent student = (HostelStudent) client.GetStudent("sakthi");  
  3. if (student != null)  
  4. {  
  5.     Console.WriteLine("****** Student Detail ******");  
  6.     Console.WriteLine("****************************");  
  7.     Console.WriteLine("Student Name : " + student.Name);  
  8.     Console.WriteLine("Department : " + student.Department);  
  9.     Console.WriteLine("Year : " + student.Year);  
  10.     Console.WriteLine("Hostel Room Number : " + student.RoomNumber);  
  11. }  
Run the application and see the output in the console window.
 
output  
 
Suppose if you forget to mention the known type attribute in the base type, it will throw exception.
 
Ok, let us see what are the ways available to mention the known type in the WCF service. There are four ways available to mention the known type in WCF. 
  1. In the Base type using KnownType attribute,
    1. [DataContract]  
    2. [KnownType(typeof(HostelStudent))]  
    3. public class Student   
    4. {  
    5.     [DataMember]  
    6.     public string Name  
    7.     {  
    8.         get;  
    9.         set;  
    10.     }  
    11.     [DataMember]  
    12.     public string Department  
    13.     {  
    14.         get;  
    15.         set;  
    16.     }  
    17.     [DataMember]  
    18.     public int Year;  
    19.   
    20. }  
    21.   
    22.   
    23. [DataContract]  
    24. public class HostelStudent: Student  
    25. {  
    26.     [DataMember]  
    27.     public string RoomNumber  
    28.     {  
    29.         get;  
    30.         set;  
    31.     }  
    32. }  
  2. By mentioning the ServiceKnownType attribute in the service level. Here the Specified type is known type only to this service.
    1. [ServiceContract]  
    2. [ServiceKnownType(typeof(HostelStudent))]  
    3. public interface IStudentService  
    4. {  
    5.     [OperationContract]  
    6.     Student GetStudent(string name);  
    7.   
    8.     [OperationContract]  
    9.     void SaveStudent(Student student);  
    10. }  
  3. By mention the ServiceKnownType attribute in the operation level. Here the specified type is known type only to that operation.
    1. [OperationContract]  
    2. [ServiceKnownType(typeof(HostelStudent))]  
    3. Student GetStudent(string name);  
    If we try to access the Hostel student out of GetStudent operation, it will throw exception.

  4. Mention the following configuration in the web.config or app.config file.
    1. <system.runtime.serialization>  
    2.     <dataContractSerializer>  
    3.         <declaredTypes>  
    4.             <add type="StudentServiceLib.Student, StudentServiceLib, Version=1.0.0.0, PublicKeyToken=null">  
    5.                 <knownType type="StudentServiceLib.HostelStudent, StudentServiceLib, Version=1.0.0.0, PublicKeyToken=null"></knownType>  
    6.             </add>  
    7.         </declaredTypes>  
    8.     </dataContractSerializer>  
    9. </system.runtime.serialization>  
    It will be available to all services mentioned in the service host.
That’s all, please feel free to comment if you have any questions about it.