Wednesday, 3 October 2012

What is DataContract?


Data Contract:
DataContract is used define a complex types. The Client and server communication is done through SOAP message communication but we can’t control the request and response between them.
Data Contract generates a soap request but this request is not be controlled by developer. This request
and response are simple XSD formats. So we can’t be control messages(request and response).
Advantages:
Data Contract uses DataContactSerializer.
Which serializes all types of members(public,private..ect) of Properties, Enums
.not static members
DataContract is faster then xmlserializer.
Demo:

namespace WcfServiceLibrary1
{
    // NOTE: If you change the interface name "IService1" here, you must also update the reference to "IService1" in App.config.
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        string GetData(int value);

        [OperationContract]
        CompositeType GetDataUsingDataContract(CompositeType composite);

        // TODO: Add your service operations here
    }

    // Use a data contract as illustrated in the sample below to add composite types to service operations
    [DataContract]
    public class CompositeType
    {
        bool boolValue = true;
        string stringValue = "Hello ";

        [DataMember]
        public bool BoolValue
        {
            get { return boolValue; }
            set { boolValue = value; }
        }

        [DataMember]
        public string StringValue
        {
            get { return stringValue; }
            set { stringValue = value; }
        }
    }
}
Response
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Header />
  <s:Body>
    <GetDataUsingDataContractResponse xmlns="http://tempuri.org/">
      <GetDataUsingDataContractResult xmlns:a="http://schemas.datacontract.org/2004/07/WcfServiceLibrary1" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
        <a:BoolValue>true</a:BoolValue>
        <a:StringValue>kasibbauSuffix</a:StringValue>
      </GetDataUsingDataContractResult>
    </GetDataUsingDataContractResponse>
  </s:Body>
</s:Envelope>
Data Exchange between Client and server done through simplified generalized XML SEHEMA DEFINICATION(.XSD) Format.
This is not compatable with old asp.net web service(.asmx) service to exchange data. So we prefer to use this case is Message Contract
Asp.net web service is----communication [ soap request 1.1 and soap 1.2]
And
Wcf ----------------------- communication [message contract]
For backward compatability.
as well DataContract has many properties like Name,Namespace,ProtectionLevel…ect.
When ever we add Service reference to client [using Add service Reference/web Reference] to client our complex types are create at client as .XSD Files.
Client and service exchange the data between them through based this Generated XSD. Like strongly typed data. So client and service SHARES complex types[datacontracts] as a xsd files.
<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:tns="http://tempuri.org/" elementFormDefault="qualified" targetNamespace="http://tempuri.org/" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:import namespace="http://schemas.datacontract.org/2004/07/WcfMessageContract" />
  <xs:element name="Employee">
    <xs:complexType>
      <xs:sequence>
        <xs:element minOccurs="0" name="EmpLocation" nillable="true" type="xs:string" />
        <xs:element minOccurs="0" name="EmpDept" type="xs:int" />
        <xs:element minOccurs="0" name="EmpUpload" type="xs:boolean" />
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>
DataContract Versions:
DataContract supports Versions this possible at client and service communication.
At service side any new members are add to xsd. Service will ignore them.
Through maintain versioning.[done through xsd through xsd validation].
DataContact Collections.
By default service returns multiple records as----an Array.
CollectionDataContract attribute to prepare –Custom Collections like .NET Collections.
[ServiceContract]
    public interface IService1
    {
        [OperationContract(Name="GetEmpNames")]
        MyCustomCollection<Emp> GetNames();
      
        [OperationContract]
        string Add(Emp eobj);
        [OperationContract(Name = "GetStuNames")]
        MyCustomCollection<Student> GetStudentNames();
       
      
    }
    [DataContract(Name = "Students")]
    public class Student
    {
        [DataMember(Name="RollNo")]
        public string RollNumber { get; set; }
        [DataMember(Name="studname")]
        public string Name { get; set; }
        [DataMember(Name="Hobbies")]
        public string Hobby { get; set; }
    }
    [DataContract(Name="Employee")]
    public class Emp
    {
        [DataMember(Name="Ename",Order=1)]
        public string EName { get; set; }
        [DataMember(Name = "Eloc",Order=2)]
        public string Eloc { get; set; }
        [DataMember(Name = "Edept",Order=3)]
        public int DeptId { get; set; }
        [DataMember(Name = "Euploadstatus",Order=4)]
        public bool Uploadstatus { get; set; }
   
    }
    [CollectionDataContract(Name = "MyCollectionof{0}")]
    public class MyCustomCollection<T> : IEnumerable<T>
    {
        private List<T> myList = new List<T>();
        public void Add(T c)
        {
            myList.Add(c);
        }
        IEnumerator<T> IEnumerable<T>.GetEnumerator()
        {
            return myList.GetEnumerator();
        }
        System.Collections.IEnumerator IEnumerable.GetEnumerator()
        {
            return myList.GetEnumerator();
        }
    }
Here T is // Employee or Student as per our request

Implementation
   public class Service1 : IService1
    {
      
        MyCustomCollection<Emp> lstStudent = new MyCustomCollection<Emp>();
        SqlConnection con = new SqlConnection("uid=sa;pwd=zolt123$;database=wcfdb");
        SqlCommand cmd;
        DataSet ds;
        public MyCustomCollection<Emp> GetNames()
        {
            MyCustomCollection<Emp> e1 = new MyCustomCollection<Emp>();
          
Emp eobj1 = new Emp { EName = "nani",Eloc="vba", DeptId = 4,Uploadstatus = true };
Emp eobj2 = new Emp { EName = "rajshkar", Eloc = "vba", DeptId = 4, Uploadstatus = true };
            e1.Add(eobj1);
            e1.Add(eobj2);
            return e1;
          
        }
        public string Add(Emp e)
        {
          
            SqlCommand cmd = new SqlCommand("InsertEmp", con);
            cmd.CommandType = CommandType.StoredProcedure;
            SqlParameter sp1 = new SqlParameter("@ename", SqlDbType.VarChar);
            sp1.Value = e.EName;
            cmd.Parameters.Add(sp1);
            SqlParameter sp2 = new SqlParameter("@eloc", SqlDbType.VarChar);
            sp2.Value = e.Eloc;
            cmd.Parameters.Add(sp2);
            SqlParameter sp3 = new SqlParameter("@dept", SqlDbType.Int);
            sp3.Value = e.DeptId;
            cmd.Parameters.Add(sp3);
            SqlParameter sp4 = new SqlParameter("@upload", SqlDbType.Bit);
            sp4.Value = e.Uploadstatus;
            cmd.Parameters.Add(sp4);
            con.Open();
            int i=cmd.ExecuteNonQuery();
            if (i != null || i == 0)
            {

                return "Inserted Succefully" + i.ToString();
           
            }
            else
            {
                return "Record is not Inserted ";
            }
            con.Close();
 
       
        }

        #region IService1 Members


        MyCustomCollection<Student> IService1.GetStudentNames()
        {
            MyCustomCollection<Student> e1 = new MyCustomCollection<Student>();

            Student stud1 = new Student { Name = "student1", RollNumber = "104", Hobby = "cricket" };
            Student stud2 = new Student { Name = "student2", RollNumber = "105", Hobby = "Chess" };
            e1.Add(stud1);
            e1.Add(stud2);
            return e1;
        }

        #endregion
    }


At Client
class Program
    {
        static void Main(string[] args)
        {
            ServiceReference1.Service1Client proxy = new Service1Client();
            Employee eobj1 = new Employee { Ename = "first", Eloc = "bangalore", Edept = 1, Euploadstatus = true };
            proxy.Add(eobj1);


            MyCollectionofStudents students = proxy.GetStuNames();  //MyCollectionof{0}--Employee,student
            Console.WriteLine(" Students Collection  :MyCollectionofStudents  ");
            foreach (Students item in students)
            {
                Console.WriteLine(item.Hobbies);
               
            }

            Console.WriteLine();
            MyCollectionofEmployee employees = proxy.GetEmpNames();
            Console.WriteLine(" Employee Collection : MyCollectionofEmployee ");
            foreach (Employee item in employees)
            {
                Console.WriteLine(item.Ename);
            }
           
          
            Console.Read();
      
          
        
        }
}





No comments:

Post a Comment