29 July 2013

Creating and Consuming WCF Services

TO CREATE

New --> Project --> (WCF) WCF Service Application

Erase defaults.

Add New Item --> (Web) WCF Service

DogServices.svc (service) + IDogServices.cs (interface)

Edit the interface.

Sample interface:

    [ServiceContract]
    public interface IDogServices
    {
        [OperationContract]
        List<Dog> ListOfDogs();
    }


Edit the service.

Sample service:

   public class DogServices : IDogServices
    {
        public List<Dog> ListOfDogs()
        {
            HayopDBEntities ctx = new HayopDBEntities();
            var dogs = ctx.Dogs.Select(y => y).ToList();
            return dogs;
        }
    }


Done. Simple, huh!


TO CONSUME

Add New Project.

Create An Empty Web Application.

"Add Service Reference" to the Reference folder.

Discover, Choose A Service, then OK.

Add A WebForm.

From Code Behind,

       protected void Page_Load(object sender, EventArgs e)
        {
            ServiceReference1.DogServicesClient myClient = new ServiceReference1.DogServicesClient();
            GridView1.DataSource = myClient.ListOfDogs();
            GridView1.DataBind();           
        }

That's it!

No comments:

Post a Comment