Thursday, September 5, 2013

Create your first WCF 4.0 application in C#

This is the initial step that i'm gonna describe you as the first step, as well as just to give a small idea of how to create a simple WCF service application. Let work through the code snippet that i have provided here. 

Step 01 : Create New WCF Class Library

Open VS 2010 -> File -> New -> Project -> WCF Class Library -> Name it as PersonServiceLibrary. By default it will create Service.cs and IService.cs files. Just delete those two. Will create the service from the sketch.

Step 02 : Add a new Class "Person" & add following fields.

Add using System.Runtime.Serialization namespace to the file.
namespace PersonServiceLibrary
{
    [DataContract]
    public class Person
    {
        [DataMember]
        public string PersonID;
        [DataMember]
        public string FirstName;
        [DataMember]
        public string LastName;
        [DataMember]
        public string Address;
        [DataMember]
        public bool Status;
        [DataMember]
        public DateTime CreatedDate;
    }
}

Step 03 : Add an Interface "IPersonService"
This is to add the service methods of the Person. Add following codes snippets to the IPersonService Interface.

namespace PersonServiceLibrary
{
    [ServiceContract]
    public interface IPersonService
    {
        [OperationContract]
        void AddPerson(Person person);
        
        [OperationContract]
        List<Person> GetAll();

        [OperationContract]
        void RemovePerson(string personID);
    }
}
Step 04 : Add another Class "PersonService"
Implement IPersonService in PersonService Class & add following snippets init.
namespace PersonServiceLibrary
{
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
    public class PersonService : IPersonService
    {
        List<Person> personList = new List<Person>();

        public void AddPerson(Person person)
        {
            person.PersonID = Guid.NewGuid().ToString();
            personList.Add(person);
        }
        public List<Person> GetAll()
        {
            return personList;
        }
        public void RemovePerson(string personID)
        {
            personList.Remove(personList.Find(e => e.PersonID.Equals(personID)));
        }
    }
}

Step 05 : Edit WCF Configuration 
Now Right-Click on App.config & click Edit WCF Configuration. AS shown in attached image, set the Name to PersonServiceLibrary.PersonService.

Now Expand the EndPoints & click and change the contract into PersonServiceLibrary.IPersonService

Step : 06 Run the Application
Press F5 to run the program. It will open a WCF Test Client which displays exposed service methods. Double Click "AddPerson " method and enter some values. Press "Invoke" button to display the results. Like wise check all three methods. We are done with first application in WCF.

Download

No comments:

Post a Comment