How To: Create a Web Service with WCF

Man it has been crazy busy as of late…lots of projects…not enough time. Sorry for the lack of articles!!

Ok…so one of my latest projects has been a bit different. They have an old Access database that they have been using for years as an admin tool to keep track of their clients. A lot of work has been put into this system so they didn’t want to throw it away, but at the same time they wanted to ease the load of the admins by allowing the clients to update their own information over the web.

So basically what they needed was a website that talked to their server and updated their info behind the scenes. Sounds like a job for web service right? Yup, but times are changing with the whole MS web service thing…with .NET 3 and 3.5 the new concept of WCF has been introduced. Now WCF (Windows Communication Foundation) can do A LOT of different stuff, but today I am going to give a quick lesson on how to setup and use WCF services in place of a traditional web service.

Its not all that tricky, and once you get it, you can really expand what a website can do…so lets get started.

Pieces and Parts
So here is the situation…client has a server with goodies on it…they want a website that is on a different server…and they want the two to communicate. To do this with WCF you basically need 2 parts.

1. A Website…fancy that.
2. A WCF Service…

Poof! And then you are done. Thanks, and goodnight.

If it were that easy we all would be out of a job. Fortunately though, its just complicated enough to keep us employed. Lets focus on number 2 first cause it has all the new fancy stuff in it.

Plumbing…its a dirty job
The Service is what will live on the client’s server so it will have an easy time touching the database and getting through security because it lives on the same network.

The easiest way to create a new WCF service is to use Visual Studio 2008 and add a new WCF Service application to your solution. Once you do that VS will stub out the basics for you.

1. IService1.cs
2. Service1.svc (and Service1.svc.cs)
3. Web.config

So the first thing I did was rename everything…I hate files and controls that have numbers in their name (its a thing…). So to satiate my OCD, I picked the handy moniker “DataService” for my stuff (IDataService.cs, DataService.svc).

So what are these things? Well, the DataService file is where all the work is, and the IDataService is how the world connects to it.

IDataService is our Interface to the world (hence the I). This is how your website will talk to the client’s server. To do this you will create OperationContracts…like so.

[OperationContract]
List<Goody> GetSomeGoodies();

This tells the website that there is a method in this service that will get some goodies. The attribute [OperationContract] is what exposes the method to the world. Obviously this doesn’t do anything here…the real work happens in DataService. Any OperationContract you specify in IDataService must be detailed in DataService or it won’t compile.

Make sense? Now for the easy part.

DataService is just like any server side file or code-behind. You can connect to a database (in my case I used LINQ to hook into the SQL server backend that we setup to interface with Access), talk to files, or just about anything else you need to do without a UI. The only difference is, you have to return serializable objects (which means LINQ tables are out of the question unfortunately). In fact, to return anything to the website you have to create new objects called DataContracts…

DataContracts are built in the IDataService file and look like so…

[DataContract]
public class Goody
{
    [DataMember]
    public int ID { get; set; }

    [DataMember]
    public string Name { get; set; }
}

Nothin’ fancy here…this is just a C# data class…the only difference is on the top you specify that it is a [DataContract] and each property is a [DataMember]. These attributes allow the class to be serialized and used by the WCF service.

So in our DataService file you would have a method that looks like this.

public List<Goody> GetSomeGoodies()
{
      DBContext db = new DBContext();
      var list = from tbl in db.tblGoody
                   orderby tbl.Name
                   select tbl;

      List<Goody> goodyList = new List<Goody>();
      foreach (tblGoody tg in list)
      {
          Goody g = new Goody();
          g.ID = tg.GoodyID;
          g.Name = tg.GoodyName;
          goodyList.Add(g);
      }

      return goodyList;
}

So there you have it…a method that is available to the website using WCF…lets recap.

IDataService: Interface that details the methods that can be called from the website. Any methods detailed here must be filled out in DataService. Also includes the custom DataContract classes that are passed around the service (they can be either parameters or returned values).

DataService: Where the real work happens. Standard server-side files that accept and return the DataContract objects (you can also use primitives if you wish).

Use it or Lose it…
So now you have a method that can be used by the website…how do you actually use it? Well first you have to connect to the WCF service you just created. If they are on different computers, then you would have to get the IP address and locate the service, but in our little example they are in the same solution. Just right click on the website project and hit “Add Service Reference”, click Discover and poof…DataService.svc should show up. Type in the namespace (I called mine DataService) and hit Ok.

Once you have that all setup your website is ready to consume the service you just created. Now all you need to do is wire it up.

Go to the code behind of any webpage…add a “using” statement that is the same as the namespace you just typed in. Once you do that you will get a new object called “<namespace>Client” (in my case it is called DataServiceClient). Instantiate this object and you can call the GetSomeGoodies method you created earlier…that’s all there is to it!!

One thing to note however…remember in the IDataService we specified that the return object was a List<goody>? Well, if you notice, what the WCF service really returns is an array of Goody (Goody[]). I am not exactly sure why it does this, but my best guess is the generic list object is too complex to send through the service. No biggie, but worth paying attention to.

Also, once you reference your service, all of your DataContracts you made in your interface are now usable anywhere on the webpage.

One last important thing to remember while you are building your site and your service: if you update the interface to any of your methods in your service you will have to rebuild your project in VS and then update your service reference before the changes you made will be visible on the website. To update the reference simply right click on the “App_WebReferences” folder in your website and click “Update Web/Service References”.

So there ya go…a simple illustration of how to create an old school web service with the fancy new WCF. I hope this helps. Please let me know if you have any difficulties.

UPDATE: After working with these guys more I have learned one more critical step while consuming a webservice. With all WCF calls, you have to close your client when you are finished with them (just like a DataReader or a Stream). In the example with DataServiceClient, you would simply call your variable and say .Close() and you are good to go. If you don’t close it, then the connection will stay open and you will quickly start running into errors.

5 Comments so far »

  1. Bjorn van der Neut said,

    Wrote on May 27, 2008 @ 2:44 am

    Create! Newer now what:
    WCF (Windows Communication Foundation) exactly was. But now I do. Its just another way of making an web service.

    Bye
    Bjorn

  2. David Baxter said,

    Wrote on May 27, 2008 @ 8:26 am

    WCF is actually a lot more than just a way to create webservices…this just happens to be one aspect of it. If you go digging, you will find that the WCF stuff is a pretty deep hole. Lots of good stuff in there.

    David

  3. Dino said,

    Wrote on July 13, 2008 @ 7:43 pm

    Thanx for the Explanation. It made me very easy to understand WCF.

  4. Min Lin said,

    Wrote on July 30, 2008 @ 1:03 am

    Thanks for the article; a great read! The article shows how to read / retrieve data but how for example write data back to the web service for storage to database?

  5. David Baxter said,

    Wrote on July 30, 2008 @ 8:27 am

    Hey Min…glad you liked the article. Basically my goal here was to give the basics on how to do just about anything with a WCF…sending data to the service would follow basically the same rules.

    Email me if you are having trouble.

    David

Comment RSS · TrackBack URI

Leave a Comment

Name: (Required)

E-mail: (Required)

Website:

Comment: