Thursday, 4 October 2012

What is KnowType and ServiceKnowType in wcf?



Yes, In Object Oriented Programming base class/ abstract class holds the object of derived class. The samething is done in service oriented programming the client and service exchange data in the form of messages.
To explicitly specify  wcf environment maintain the same hirerchy in custom types also in wcf through wcf attribute is called KnowType.
Demo:
namespace WcfKnowTypes
{  
    [ServiceContract]
    public interface IService1
    {
        [OperationContract(Name="KnowTypeDemo")]
        Parent GetDept();
           
    }
    [DataContract(Name = "Father")]
    [KnownType(typeof(Child))]
    public class Parent
    {
        [DataMember]
        public string PName { get; set; }
   
    }
    [DataContract(Name="Childerns")]
    public class Child:Parent
    {
        [DataMember]
        public string CName { get; set; }

    }
     
}
 implementation

    public class Service1 : IService1
    {

        #region IService1 Members

        public Parent GetDept()
        {
            Child pobj = new Child();
            pobj.PName = "Parent Name";
            pobj.CName="Child Name";
            return pobj;
        }

        #endregion
    }
}


At client

using (Service1Client proxy = new Service1Client())
            {
             
                Father str =proxy.KnowTypeDemo();
                Childerns c = (Childerns)str;  // Convertation
                Console.Write(c.PName);
                Console.Write(c.CName);
                Console.Read();
               
            }

No comments:

Post a Comment