Saturday, August 7, 2010

How to Create WCF Application

Select WCF Service Application from New Project window in Visual Studio and name the project as MyWCFService

Add WCF Service to the “MyWCFService” project and named as Myservice.svc

What is Service Contracts ?
Describe which operations the client can perform on the service. There are two types of Service Contracts.
ServiceContract - This attribute is used to define the Interface.
OperationContract - This attribute is used to define the method inside Interface.

IMyService.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;


[ServiceContract]

public interface IService

{

    [OperationContract]

     Employeee GetEmployee(int id);// service method

      

}

Then we can implement above interface

MyService.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;

using Common;

    public class MyService: IMyService

    {


        #region MyService Members


        public Employeee GetEmployee(int id)//service method implimentation

        {

 Employeee emp = new Employeee { EmpId = Guid.NewGuid(),Name="Dinesh",Type=EmployeeTypesEnum.Accounter };

                     return emp;

        }


        #endregion

    }

What is Data contracts?

Define which data types are passed to and from the service. WCF defines implicit contracts for built-in types such as int and string, but we can easily define explicit opt-in data contracts for custom types.
Types Supported by the Data Contract Serializer

There are two types of Data Contracts.
DataContract - attribute used to define the class
DataMember - attribute used to define the properties

Add Class Employee to the solution

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Runtime.Serialization;

using System.ServiceModel;


    [DataContract]

    public class Employeee

    {

        [DataMember]

        public Guid EmpId { get; set; }

        [DataMember]

        public string Name { get; set; }

        [DataMember]

        public EmployeeTypesEnum Type { set; get; }

    }

How To Pass Enum with WCF services?

To pass Enum the Data contracts should be define with EnumMember() attributes.


using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Runtime.Serialization;


 [DataContract]

   public enum EmployeeTypesEnum

    {

    [EnumMember()]


          Administrator = 0,


    [EnumMember()]


          Manager = 1,


    [EnumMember()]


          Accounter = 2


}

How to Test WCF application ?

WCF service can test with WCF Test Client (WcfTestClient.exe) by  execute WcfTestClient.exe commond in Visual Studio Command prompt .