This article will guide you through, to create a WCF service, host it in your local IIS and consume the service using a client console application. The data are going to be retrieved from an SQL Server 2012 using the Entity Framework. The database used in this tutorial is the AdventureWorks, a sample database which Microsoft provides for free. You can download it but have in mind that you need to convert it to a database compatible to the SQL Server 2012. If you have earlier versions like SQL Server 2008 R2 I am pretty sure you won’t have any problem. Before starting, I assume you have already installed the above database in your SQL Server. So let’s start:
1. Open VS 2012 and create a new class library project (C# template). Name your solution AdventureWorksService and the project name AdventureWorksEntityModel. This class library will provide as the database access through the Entity Framework. Delete Class1.cs file and right click the project to add a new Item of type ADO.NET Entity Data Model. Name it AdventureWorksModel. In the wizard appears next, click “create from database”. Create a new connection to the AdventureWorks database to your server. You should peek Microsoft SQL Server as a datasource, fill your server name and select the database from the dropdown list. Test your connection to assure everything is ok.
Click OK, and continue till you select the tables for your Entity Framework. These will be your Entities. Select from Production, the Product and ProductCostHistory tables. Leave all the rest at the default values.
Click finish, save the edmx file and build the solution. The Entity Model is ready. At the next step we are going to create the service through a WCF website. We ‘ll use this website to publish it in the IIS so we can later consume the service from there.
2. Right click the solution (be careful, not the class library project) and add a new website. From templates select WCF servise. As a location browse to the folder of your solution and add a \AdventureWorksService\ so it will be created under a new folder with the same name as the solution. Rename the file IService.cs file to IAdventureWorksService.cs. This will be the service interface where the contracts will be declared. Remove all the code from it, except the using declarations. Add the following code to the file.
namespace AdventureWorks { // Data contract describing the details of a product passed to client applications [DataContract] public class ProductData { [DataMember] public string Name; [DataMember] public string ProductNumber; [DataMember] public string Color; [DataMember] public decimal ListPrice; } // Service contract describing the operations provided by the WCF service [ServiceContract] public interface IAdventureWorksService { // Get the product number of every product [OperationContract] List<string> ListProducts(); // Get the details of a single product [OperationContract] ProductData GetProduct(string productNumber); } }
At the next step we ‘ll implement the interface. First of all, we need to add two basic references to our website project. Right click it, select add reference and add the System.Data.Entity assembly and the AdventureWorksEntityModel project. Rename the Service.cs file to AdventureWorksService.cs, delete the entire code from it except the using declarations. Add the above code to the file. Be careful with the “using AdventureWorks2012Entities” code. Your App.config file in your Entity Model project may have save the connection string with different name. Also, copy the the entire connection string element (from start to end) and paste it to the Web.config file of your website project right after the opening configuration tag.
using AdventureWorksEntityModel; namespace AdventureWorks { public class AdventureWorksServiceImpl : IAdventureWorksService { public List<string> ListProducts() { // Create a list for holding product numbers List<string> productsList = new List<string>(); try { // Connect to the AdventureWorks database by using the Entity Framework using (AdventureWorks2012Entities database = new AdventureWorks2012Entities()) { // Fetch the product number of every product in the database var products = from product in database.Products select product.ProductNumber; productsList = products.ToList(); } } catch { // Ignore exceptions in this implementation } // Return the list of product numbers return productsList; } public ProductData GetProduct(string productNumber) { // Create a reference to a ProductData object // This object will be instantiated if a matching product is found ProductData productData = null; try { // Connect to the AdventureWorks database by using the Entity Framework using (AdventureWorks2012Entities database = new AdventureWorks2012Entities()) { // Find the first product that matches the specified product number Product matchingProduct = database.Products.First( p => String.Compare(p.ProductNumber, productNumber) == 0); productData = new ProductData() { Name = matchingProduct.Name, ProductNumber = matchingProduct.ProductNumber, Color = matchingProduct.Color, ListPrice = matchingProduct.ListPrice }; } } catch { // Ignore exceptions in this implementation } // Return the product return productData; } } }
Change the content of the Service.svc file located at the root of the website to the following
<%@ ServiceHost Language="C#" Debug="true" Service="AdventureWorks.AdventureWorksServiceImpl" CodeBehind="~/App_Code/AdventureWorksService.cs" %>
At this time already, if you right click the service.svc file and select view in browser you should already see that the service is hosted. But not in your local IIS. At the moment it is hosted either in the IIS Exrpress or the ASP.NET Development Server.
Before we create the Client Application to consume the web service, let’s host it first, to the IIS. To do this, simply right click your web project, select publish web site, select Local IIS from left, click on the Default Web Site and for target location put
http://localhost/AdventureWorksService
. That’s it! Go with your browser to the following URL
http://localhost/AdventureWorksService/Service.svc
and you should see the same image as above. If not, be sure the the application pool that the hosted website use in your IIS is ASP.NET 4.0.
3. Right click the solution and create a C# Console Application project named AdventureWorksClient. Add a reference to the System.ServiceModel assembly. Next right click again the console application project, select add a service reference. As address put the service address in your IIS, that would be
http://localhost/AdventureWorksService/Service.svc
(depending of how you named your website). This will retrieve the metadata of the service and will create the proxy for the client, in order to consume the service. Name the namespace AdventureWorksService and click OK. Before I show you the code for calling the service, go to the App.config file of the console application project and ensure that the endpoint address points to the IIS hosted service. Your App.config should be kind like this:
<?xml version="1.0" encoding="utf-8" ?> <configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> </startup> <system.serviceModel> <bindings> <basicHttpBinding> <binding name="BasicHttpBinding_AdventureWorksService" /> </basicHttpBinding> </bindings> <client> <endpoint address="http://localhost/AdventureWorksService/Service.svc" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_AdventureWorksService" contract="AdventureWorksService.AdventureWorksService" name="BasicHttpBinding_AdventureWorksService" /> </client> </system.serviceModel> </configuration>
Remove all the code from the Program.cs file except the using declarations. Add the following code, right click the Client project and select Set as Start up project. Then run without debugging and you should see the client consuming the service, showing the results for the requested product.
using AdventureWorksClient.AdventureWorksService; namespace AdventureWorksClient { class Program { static void Main(string[] args) { // Create a proxy object and connect to the service AdventureWorksService.AdventureWorksServiceClient proxy = new AdventureWorksService.AdventureWorksServiceClient(); // Obtain a list of all products Console.WriteLine("Test 1: List all products"); string[] productNumbers = proxy.ListProducts(); foreach (string productNumber in productNumbers) { Console.WriteLine("Number: {0}", productNumber); } Console.WriteLine(); Console.WriteLine("Test 2: Display the details of a product"); ProductData product = proxy.GetProduct("AR-5381"); Console.WriteLine("Number: {0}", product.ProductNumber); Console.WriteLine("Name: {0}", product.Name); Console.WriteLine("Color: {0}", product.Color); Console.WriteLine("Price: {0}", product.ListPrice); Console.WriteLine(); // Disconnect from the service proxy.Close(); Console.WriteLine("Press ENTER to finish"); Console.ReadLine(); } } }
I hope I helped!
Categories: WCF
Howdy! Would you mind if I share your blog with my zynga group?
There’s a lot of folks that I think would really enjoy your content.
Please let me know. Cheers
Of course you can share it.
Kind regards,
C.S
Awesome site you have here but I was curious about if you knew of
any user discussion forums that cover the same topics discussed here?
I’d really love to be a part of online community where I can get feed-back from other knowledgeable individuals that
share the same interest. If you have any recommendations,
please let me know. Many thanks!
Thanks for posting this . iwas helped me to come out lot of problems ..
thanks lot..
Hi Chris. Could you help? When I host my WCF service on WcfSvcHost in VS my WCF service can read data from SQL db. In case when I host service on Console App or IIS I have exception fault. Do you know where the probmem could be? Many thanks.
Hi.
That’s a great Post. Can you help me? I want to update the data. But I have no idea how.