Type Attribute in WCF

Introduction

Understanding this article requires understanding some basics regarding WCF Services and various contracts available with the framework.

The MSDN says that a known type is an attribute class defined in the WCF Framework that allows you to specify the types that should be included for consideration during deserialization.

What the preceding statement means is that when communication happens between a WCF service and client by passing parameters and return values, both endpoints share all of the data contracts of the data to be transmitted.

Data Contracts MSDN Definition

A data contract is a formal agreement between a service and a client that abstractly describes the data to be exchanged. That is, to communicate, the client and the service do not need to share the same types, only the same data contracts. A data contract precisely defines, for each parameter or return type, what data is serialized (turned into XML) to be exchanged.

When data arrives at a receiving endpoint, the WCF runtime attempts to de-serialize the data. The type that is instantiated for deserialization is chosen by first inspecting the incoming message to determine the data contract to which the contents of the message conform.

A problem occurs when a service returns a derived type of the data contract instead of the base data contract.

Are you confused? Alright, let us create a scenario where two types of customers exist, one is a normal customer and the other is a classic customer of a customerOrder service.

Here we have a data contract of the customer that will be responsible for the transmission between the client and the service.

Now in one case when we need to return a derived class of a classic customer then WCF de-serialization does not recognize the derived data type and starts giving exceptions.

Sample WCF service

  1. namespace CustomerOrderService  
  2. {  
  3.     [ServiceContract]  
  4.     public interface IOrderService  
  5.     {  
  6.         [OperationContract]  
  7.         Customer GetCusomersDetails(int Id);  
  8.   
  9.         [OperationContract]  
  10.         void AddCustomers();  
  11.     }  
  12. }  
Data Contract (Base Class: Customer)
  1. namespace CustomerOrderService  
  2. {  
  3.   
  4.     [DataContract]  
  5.     public class Customer  
  6.     {  
  7.         [DataMember]  
  8.         public int ID { getset; }  
  9.         [DataMember]  
  10.         public string CustomerName { getset; }  
  11.         [DataMember]  
  12.         public string Location { getset; }  
  13.         [DataMember]  
  14.         public string MobileNo { getset; }  
  15.         public CustomerType customerType { getset; }  
  16.     }  
  17.   
  18.     [DataContract]  
  19.     public enum CustomerType  
  20.     {  
  21.         [EnumMember]  
  22.         ClaasicCustomers = 1,  
  23.         [EnumMember]  
  24.         NormalCustomers = 2  
  25.     }  
  26. }  
Derived Class:
  1. public class ClassicCustomers : Customer  
  2. {  
  3.     public float Discount { getset; }  
  4.     public int RewardPoints { getset; }  
  5.   
  6. }  
  7.   
  8. public class NormalCustomers : Customer  
  9. {  
  10.     public string newOffers { getset; }  
  11. }  
Service Code:
  1. namespace CustomerOrderService  
  2. {  
  3.   
  4.     public class OrderService : IOrderService  
  5.     {  
  6.         public Customer GetCusomersDetails(int ID)  
  7.         {  
  8.             Customer cust = Null;  
  9.             string Conn = ConfigurationManager.ConnectionStrings["customerConn"].ConnectionString;  
  10.   
  11.             using (SqlConnection myconn = new SqlConnection(Conn))  
  12.             {  
  13.                 SqlCommand cmd = new SqlCommand("sp_GetCustomers", myconn);  
  14.                 cmd.CommandType = CommandType.StoredProcedure;  
  15.                 SqlParameter param = new SqlParameter();  
  16.                 param.ParameterName = "@ID";  
  17.                 param.Value = ID;  
  18.                 cmd.Parameters.Add(param);  
  19.                 myconn.Open();  
  20.                 SqlDataReader reader = cmd.ExecuteReader();  
  21.   
  22.                 while (reader.Read())  
  23.                 {  
  24.                     cust = new ClassicCustomers()  
  25.   
  26.                     {  
  27.                         CustomerName = Convert.ToString(reader["CustomerName"]),  
  28.                         Location = reader["CustomerAddress"].ToString(),  
  29.                         MobileNo = reader["MobileNo"].ToString(),  
  30.                         RewardPoints = (int.Parse)(reader["RewardPoints"].ToString())  
  31.                     };  
  32.   
  33.                 }  
  34.             }  
  35.             return cust;  
  36.         }  
  37.   
  38.         public void AddCustomers(Customer cust)  
  39.         {  
  40.             throw new NotImplementedException();  
  41.         }  
  42.     }  
  43. }  
Explanation

In the above example we have a Customer Order service with Base class data contract Customer and two derived classes, normal customer and classic customer. So here our requirement is to get the customer details on the basis of the flag customer type and return derived type.

Here in the above example we are trying to return the Classic customer that is the derived type.

At the client end when the WCF Framework tries to de-serialize the data contract it does not have any knowledge of the derived type and it therefore throws exceptions.

start throwing exceptions

The WCF Framework introduced  solution for this problem called the KnownTypeAttribute class.

The KnownTypeAttribute class is recognized by the DataContractSerializer when serializing or deserializing a given type, in other words the known type helps to get a derived class deserialized at the client end.
  1. [KnownType(typeof(ClassicCustomers))]  
  2. [KnownType(typeof(NormalCustomers))]  
  3.   
  4. [DataContract]  
  5. public class Customer  
  6. {  
  7.     [DataMember]  
  8.     public int ID { getset; }  
  9.     [DataMember]  
  10.     public string CustomerName { getset; }  
  11.     [DataMember]  
  12.     public string Location { getset; }  
  13.     [DataMember]  
  14.     public string MobileNo { getset; }  
  15.     public CustomerType customerType { getset; }  
  16. }  
customer detail

The receding is the output from the client using the CustomerOrderService WCF service and the RewardPoints is the property of the derived data contract Classiccustomer meaning that after using the known type attribute the DataContactSerilizer engine of WCF starts recognizing the derived data contact and does allow it to pass to the client giving the desired results.

Ways to Use KnowTypeAttribute

The WCF Framework has provided the control on using the knowtypeattribute when creating the service. The known type attribute can be provided in on of two ways.

 

  • Code Level
    1. [KnownType(typeof(ClassicCustomers))]  
    This is the syntax we use with the data contract typeof(Derived Class).

    1. Known Type Attribute On Base type:

      Applying the known type attribute globally to a WCF service means that all the services and operation contracts will use this known type attribute to get de-serialized at the client.

      The following is the customer class and the known type is applied at the base level for two serviced classes:
      1. [KnownType(typeof(ClassicCustomers))]  
      2. [KnownType(typeof(NormalCustomers))]  
      3. [DataContract]  
      4. public class Customer  
      5. {  
      6.     [DataMember]  
      7.     public int ID { getset; }  
      8.     [DataMember]  
      9.     public string CustomerName { getset; }  
      10.     [DataMember]  
      11.     public string Location { getset; }  
      12.     [DataMember]  
      13.     public string MobileNo { getset; }  
      14.     public CustomerType customerType { getset; }  
      15. }  
    2. Known Type attribute to Service Contact:

      Here control will go to the service level, meaning that applying the known type attribute at the Service level will ensure all the operation contacts will use the known type attribute.
      1. namespace CustomerOrderService  
      2. {  
      3.     [KnownType(typeof(ClassicCustomers))]  
      4.     [KnownType(typeof(NormalCustomers))]  
      5.     [ServiceContract]  
      6.   
      7.     public interface IOrderService  
      8.     {  
      9.         [OperationContract]  
      10.         Customer GetCusomersDetails(int Id);  
      11.   
      12.         [OperationContract]  
      13.         void AddCustomers(Customer cust);  
      14.     }  
      15. }  
    3. Known Type Attribute to Operation contact:

      Here we have more granular control on the known type that will be at the operation contact level, meaning that within the service we can specify one operation with a known type and another operation without it.

      So one operation contract will use the Known type for de-serialization at the client and another may break if we use a derived type with that.
      1. namespace CustomerOrderService  
      2. {    
      3.     [ServiceContract]  
      4.     public interface IOrderService  
      5.     {  
      6.         [KnownType(typeof(ClassicCustomers))]  
      7.         [KnownType(typeof(NormalCustomers))]   
      8.         [OperationContract]  
      9.         Customer GetCusomersDetails(int Id);  
      10.   
      11.         [OperationContract]  
      12.         void AddCustomers(Customer cust);  
      13.     }      
      14. }  
  • Configuration Level

    In the configuration file we can apply the known type that will be the global way of applying a known type, meaning that all the service and operation contracts will in scope of that known type attribute.

    In the configuration file of the WCF service we can apply the known type attribute globally.
    1. <system.runtime.serialization>  
    2.     <dataContractSerializer>  
    3.       <declaredTypes>  
    4.         <add type="CustomerOrderService.Customer , OrderService , Version=1.0.0.0 , Culture=Neutral , PublicKeyToken=null">  
    5.           <knownType type="CustomerOrderService.ClassicCustomers , OrderService , Version=1.0.0.0 , Culture=Neutral , PublicKeyToken=null"/>  
    6.           <knownType type="CustomerOrderService.NormalCustomers , OrderService , Version=1.0.0.0 , Culture=Neutral , PublicKeyToken=null"/>   
    7.         </add>      
    8.       </declaredTypes>  
    9.     </dataContractSerializer>  
    10.   </system.runtime.serialization>  

Conclusion

The Known Type attribute is the solution to the deserialization problem of when a derived type is being used in the service.

Happy Coding and keep learning and sharing.

References

Data Contract Known Types.