Consuming a simple WCF service

In my previous post, a simple wcf service, i showed how to make a WCF service that can return an array of strings.

In this post i will show you how to make a client in a regular ASP.NET website that can question this service and display the returned value on a page.
Start off by creating a new Website:

new-aspnet-project
I selected “ASP.NET Web Site”, picked .NET Framework 3.5 and i gave the thing a custom name.
Visual Studio will now create the files we typically need in a .NET website. Let’s just leave that now for what it is and make the reference to our service allready.

Adding a reference to the WCF Service

So in order to use our service in our website we will have to make some sort of reference to it. Luckily, Visual Studio can do nearly all the work for us.
Make sure your service is up and running (either on your localhost or somewhere else). You’ll need to know the address on which it is running so if you’ve got the service running on your local computer you might as well look in the WCF Test Client to see the exact url of the service.

In our web project right click the project and choose “”Add Service Reference”:
select-add-service-reference

Now with the Service reference dialog open we can input the address of our service and add it to our project. Notice that by doing this our IService contract is being used to communicate the functions of our service:

add-service-url-reference

Just click “Ok” and Visual Studio will take care of the rest. I will explain in a future post what exactly the files are that are being constructed since this is supposed to be a brief demo.

Databinding from the Service to a gridview

We’re nearly done.
Drag a gridview into the markup of your default.aspx and put AutoGenerateColumns on “True”. This is merely because i’m too lazy to create the colums myself.
Give your gridview and appropriate name like BrandsGridView.

In the codebehind we can now implement this code to get the info from the service and databind it:

protected void Page_Load(object sender, EventArgs e)
{
      string[] brandsList;
      ServiceReference1.CarServiceClient wcfService = new ServiceReference1.CarServiceClient();
      try{
            //i added an integer parameter to the get method so i can later use it to select the brands from a certain collection
           brandsList = wcfService.GetBrands(0);
           wcfService.Close(); //don't forget this!
        }
        catch (Exception)
        {
            wcfService.Abort();
        }

        BrandGridView.DataSource = brandsList;
        BrandGridView.DataBind();
    }

And when we run this website (F5) all should work out just fine:
final-result

Next stop on my WCF journey will be DataContracts; juggeling with object from service to client and vice versa.

Posted in ASP.NET, WCF. Tags: , . 1 Comment »

A simple WCF service

So today i have been playing around with the relatively new WCF, that stands for Windows Communication Foundation.

In this post i will not try to explain the entire thing but merely give a brief example of how this tool can help you.

WCF, in short, will help you create webservices more easily:

  • WCF can keep state
  • it’s easy to create and transmit objects using JSON
  • it has AJAX integration

I’m sure there’s a lot more going on there that i am yet to discover.

So, let’s get our hands a little dirty.

I started off by creating a new WCF project (using Visual Studio 2008 ofc) and i choose for a WCF service library.

wcf-serviclibrary

Now give your new project a good name and press “Ok”.
As you can see Visual Studio will create a Service1.cs and an IService.

Before we delete those it’s smart to know what these files actually are. The IService basicly is an interface that will describe your service to the future clients. For example it will contain all your public methods!
The IService is called the contract. Your service will have to implement the contract perfectly or it wont even build.

The other file, the Service1.cs is the service itself. Here you will implement all your methods, public or not.

The contract (IService.cs)

As we take a little look in the IService file we can distinct two seperate parts; the Interface that will describe your service and a “data contract”.

In the first part, the Service Contract we will define all our public methods and we’ll give them the [OperationContract] attribute. This tag just makes clear that this is indeed a public function that future client applications will be able to call.

Int the second part, the DataContract, we can define a custom object that will be transmitted to the client applications. For example; if you write a service that will do certain operations for a bookstore you might want to create an object called “Book”.
Obviously, this is just the same thing as creating a class. All we have to do extra is define a [DataMember] attribute above each of the properties we want our object to have exposed to the clients.

What happens behind the curtains is that WCF will use this DataContract to create a JSON (or some sort) object that can be thrown to client apps.

The Service (Service.cs)

Our service class will have to implement IService ofcourse and we will have to provide all the defined methods that we listed in the contract.

Note that we can allready use our DataContract-object here.

public CompositeType GetDataUsingDataContract(CompositeType composite)
{
if (composite.BoolValue)
{
composite.StringValue += “Suffix”;
}
return composite;
}

Just like this.

In my tryout app this is what i’ve done:

the contract:

[ServiceContract]

public interface ICarService

{

[OperationContract]

List<string> GetBrands(int depot);

}

and in the service:

public List<string> GetBrands(int depot)

{

            List brandsList = new List();
            brandsList.Add("BMW");
            brandsList.Add("Volkswagen");
            brandsList.Add("Chrysler");
            return brandsList;

}

Okay easy enough. When you run this small service a test application will start up:

wcf-test-application

When you double-click our GetBrands() method you’ll be able to invoke this method. When you do so the test application will return the brands that our service returns.

Posted in ASP.NET, WCF. Tags: , . 2 Comments »