Sunday 8 September 2013

WCF Basic - Part 1

          Windows communication Foundation (WCF) is a framework for building a service oriented loosely coupled application.You can send the messages to one endpoint to another endpoint. WCF consists of all functional of web service and also additional many more things. It is designed for Distributed computing, broad interoperability and  for service orientation.


Contract :  Which specifies the what are the operations can be perform by end user.

To create a WCF service 

1. Create a Interface and specifies a Service Contract as attribute.
2. Mention the methods inside the Interface and specifies the Operation contract as attribute 
3. Derive the Interface in the service class and implement the method this is the good practice
4. Specifies the input parameter for the method as Message Contract.
5. If DataContract parameter is uses and Messgae contract parameter is uses then Message contract is overrides the Data Contract parameter

Message Contract:
  Message Contract is to specify in which format that the soap message is organised while sending and receiving the data. MessageBodyMember is used to specify the parameters of DataContract So many properties are there for MessageBodyMember

         Name : Which is used to specify the external name for client to access.
         ProtectionLevel : three types None, Sign, EncryptAndSign
        Order : Specify the order of the parameter


[MessageContract]
    public class Offer
    {
        [MessageHeader]
        public DateTime JoinedDate { set; get; }
       
        [MessageBodyMember]
        public bool IsPermenant { set; get; }

        [MessageBodyMember]
        public bool IsExperience { set; get; }

        [MessageBodyMember(Name="OfferLetter",Order=2,ProtectionLevel=System.Net.Security.ProtectionLevel.None)]
        public OfferLetter offer { set; get; }

    }


Service Contract :
     Service Contract is like WebService and operation contract is like webMethod notation.

Data Contract:
  Data Contract is used to specify the data and DataMember is a indication of Property,Order property specify in the parameter of DataMember in the same order it is serialized. Name is property in DataMember class is used as Alias name in client side.
     
     [DataMember(Order = 1, Name = "Exception")]


EndPoint
   EndPoint is the notation at which place we can access the service through which binding.


<endpoint address="http://localhost:14849/EmployeeService.svc"
                binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IOffice"
                contract="ServiceReference1.IOffice" name="BasicHttpBinding_IOffice" />


Address
  Address of the service URL. That indicates where the end point can be found.

Binding
  Binding indicates that how we can communicate with the end point


<bindings>
            <basicHttpBinding>
                <binding name="BasicHttpBinding_IOffice" closeTimeout="00:01:00"
                    openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                    allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
                    maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
                    messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
                    useDefaultWebProxy="true">
                    <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                        maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                    <security mode="None">
                        <transport clientCredentialType="None" proxyCredentialType="None"
                            realm="" />
                        <message clientCredentialType="UserName" algorithmSuite="Default" />
                    </security>
                </binding>
            </basicHttpBinding>
        </bindings>

        
   Behavior
  You can use the end point behavior to customize the local behavior of Service end point.

FaultException:
  Specify the Fault Exception instead of throw general exception from the application. Specifies the Fault Contract attribute after the operation contract declaration in interface and there typeof Fault is pass as parameter to the constructor.
        [OperationContract]
        [FaultContract(typeof(EmployeeException))]

        Employee GetEmployee(Employee empid);


Create a WCF Service :
1. Launch a Visual Studio 2010
2. Create a new project.
3. Select WCF Service Application.


Interface : Service Contract 
[ServiceContract]
    public interface IOffice
    {
        [OperationContract]
        Offer Joined();

        [OperationContract(Name = "EmployeeExists")]
        bool EmpExists(Employee emp);

        [OperationContract]
        [FaultContract(typeof(EmployeeException))]
        Employee GetEmployee(Employee empid);

    }


Message Contract 
Name property specifies a alias name , order property specifies the order of the property, protection level specifies the type of encryption.

[MessageContract]
    public class Offer
    {
        [MessageHeader]
        public DateTime JoinedDate { set; get; }

        [MessageBodyMember]
        public bool IsPermenant { set; get; }

        [MessageBodyMember]
        public bool IsExperience { set; get; }

        [MessageBodyMember(Name = "OfferLetter", Order = 2, ProtectionLevel = System.Net.Security.ProtectionLevel.None)]
        public OfferLetter offer { set; get; }

    }


Data Contract 

[DataContract]
    public class OfferLetter
    {
        [DataMember]
        public string Message { set; get; }

        [DataMember]
        public int SalaryPackage { set; get; }
    }

********************************************************************************
Service Code: In this service we have three methods, 1. Joined()  2. EmpExists() 3. GetEmployee()
********************************************************************************

[DataContract]
    public class OfferLetter
    {
        [DataMember]
        public string Message { set; get; }

        [DataMember]
        public int SalaryPackage { set; get; }
    }

    [MessageContract]
    public class Offer
    {
        [MessageHeader]
        public DateTime JoinedDate { set; get; }

        [MessageBodyMember]
        public bool IsPermenant { set; get; }

        [MessageBodyMember]
        public bool IsExperience { set; get; }

        [MessageBodyMember(Name = "OfferLetter", Order = 2, ProtectionLevel = System.Net.Security.ProtectionLevel.None)]
        public OfferLetter offer { set; get; }

    }

    [ServiceContract]
    public interface IOffice
    {
        [OperationContract]
        Offer Joined();

        [OperationContract(Name = "EmployeeExists")]
        bool EmpExists(Employee emp);

        [OperationContract]
        [FaultContract(typeof(EmployeeException))]
        Employee GetEmployee(Employee empid);

    }

    [DataContract]
    public class EmployeeException
    {
        [DataMember]
        public int Id { set; get; }

        [DataMember(Order = 1, Name = "Exception")]
        public string ExceptionMessage
        { set; get; }
    }

    [DataContract]
    public class Employee
    {
        [DataMember(IsRequired = true)]
        public string Id { set; get; }

        [DataMember(IsRequired=true, EmitDefaultValue = true)]
        public String Name { set; get; }

        [DataMember(Name = "Mobile No", Order = 2)]
        public string PhoneNo { set; get; }

    }

  
    public class EmployeeService : IOffice
    {
        EmployeeCollection coll = new EmployeeCollection();

        public Offer Joined()
        {
            return new Offer() { JoinedDate = DateTime.Now, IsPermenant = true, offer = new OfferLetter() { Message = "We are pleased to announce that offering a Job in our company.",SalaryPackage=550000} };
        }

        public bool EmpExists(Employee emp)
        {
            if (! string.IsNullOrEmpty(emp.Id))
            {                                 
                return coll.Any(x=>x.Id==emp.Id);              
            }
            else
            {
                throw new FaultException(new FaultReason("Employee not working in company"));
            }
        }

        public Employee GetEmployee(Employee empid)
        {
            if (!string.IsNullOrEmpty(empid.Id))
            {               
                return coll.Where(x => x.Id == empid.Id).FirstOrDefault();
            }
            else
            {
                EmployeeException ex = new EmployeeException() { ExceptionMessage="Employee  "+empid.Id+" is not working in our company"};
                throw new FaultException<EmployeeException>(ex,new FaultReason("Employee id is not present"));
            }
        }
    }

  public class EmployeeCollection:ObservableCollection<Employee>
    {
        public EmployeeCollection()
        {
            Add(new Employee() {Id="FG1",Name="Rajesh",PhoneNo="8056220725" });
            Add(new Employee() {Id="FG2",Name="Krish",PhoneNo="4535443223" });
            Add(new Employee() {Id="FG3",Name="Raju",PhoneNo="5635434334"});          
        }
    }

********************************************************************************
Invoking the service from the Client:
********************************************************************************
Create a Console Application and add a Service Reference the corresponding address.

Program.cs
*********
static void Main(string[] args)
        {
            try
            {
                OfficeClient client = new OfficeClient();
                Offer person1 = new Offer();
                OfferLetter letter=new OfferLetter();
                DateTime joineddate= client.Joined(out person1.IsExperience, out person1.IsPermenant, out letter);

                Console.WriteLine("Joined in Company");
                Console.WriteLine("");
                Console.WriteLine("Joined Date :{0},/nOfferLetter : {1},\nSalary : {2},\nIsExperience : {3},\nIsPermanentEmployee : {4}", joineddate, letter.Message, letter.SalaryPackage, person1.IsExperience, person1.IsPermenant);
                Console.WriteLine("");
                bool exists=client.EmployeeExists(new Employee() { Id="FG8" });
                Console.WriteLine("FG8  Employee Exists : " + exists);
                Console.WriteLine("");
                Employee emp = client.GetEmployee(new Employee() { Id = "FG1" });
                Console.WriteLine("Employee Details : id = {0}, Name = {1}, Mobile Number = {2}", emp.Id, emp.Name, emp.MobileNo);
                Console.Read();
            }           
            catch (FaultException<EmployeeException> ex)
            {
                Console.WriteLine(ex.Detail.Id);
            }
            catch (FaultException ex)
            {
                Console.WriteLine(ex.Reason);
            }
        }
**************************************************************************
Output:
**************************************************************************


From the article you can learn some of the basics of WCF.

No comments:

Post a Comment