DCSIMG
A Walkthrough for WCF (MOC 6461) - David Sackstein's Blog

A Walkthrough for WCF (MOC 6461)

The source code for this walkthrough can be downloaded here.

I compiled this walkthrough for MOC 6461 that I am teaching these days. It corresponds to the work convered by units 1 and 2 of the MOC and will guide you through the following steps:

  1. Define the Contracts
  2. Implement the Contracts
  3. Implement a WCF Service hosted in IIS
  4. Create a Client Application
  5. Add a Self-Hosted Console Application for the Service
  6. Modify the Client Application to use the Console Host
  7. Add a Self-Hosted Windows Service for the Service
  8. Test the Client Application with the Windows Service Host

Define the Contracts

  1. Create a new project of type class library called “InventoryContracts”.
  2. Rename the Class1.cs file to IInventory.cs and add the following types:

    namespace InventoryContracts

    {

        public class Product

        {

            public string Name { get; set; }

            public int UnitsInStock { get; set; }

        }

     

        public interface IInventory

        {

            Product[] GetProducts();

            bool AddProduct(Product newProduct);

        }

    }

     

  3. Add references to the following assemblies: System.ServiceModel and System.Runtime.Serialization.
  4. Decorate the types with contract attributes as follows:

namespace InventoryContracts

{

    [DataContract]

    public class Product

    {

        [DataMember]

        public string Name { get; set; }

 

        [DataMember]

        public int UnitsInStock { get; set; }

    }

 

    [ServiceContract]

    public interface IInventory

    {

        [OperationContract]

        Product[] GetProducts();

 

        [OperationContract]

        bool AddProduct(Product newProduct);

    }

}

Implement the Contracts

  1. Create a new project of type class library called “InventoryAccessLibrary”.
  2. Rename Class1.cs to InventoryAccess.cs (and accept the name change for the class).
  3. Add a new Data Source to the project (Data -> Add New Data Source).
  4. In the new data source wizard select “Database” and add a connection to the Northwind database.
  5. Call the data set NothwindDataSet and add one DataTable corresponding to Products.
  6. Add a reference to the InventoryContracts assembly.
  7. In InventoryAccess.cs add using directives for the InventoryContracts and InventoryAccess.NorthwindDataSetTableAdapters namespaces.
  8. Have Inventory implement the IInventory interface as follows:

namespace InventoryAccessLibrary

{

    public class InventoryAccess : IInventory

    {

        #region IInventory Members

 

        public Product[] GetProducts()

        {

            ProductsTableAdapter tableAdapter = new ProductsTableAdapter();

 

            var query = from NorthwindDataSet.ProductsRow row in tableAdapter.GetData()

                        select new Product {

                            Name = row.ProductName,

                            UnitsInStock = row.UnitsInStock };

 

            return query.ToArray();

        }

 

        public bool AddProduct(Product newProduct)

        {

            ProductsTableAdapter tableAdapter = new ProductsTableAdapter();

 

            // Use default values and the valid SupplierId of 1

 

            int rowsChanged = tableAdapter.Insert(

                newProduct.Name, null, null, "1", null, null, null, null, false);

 

            return rowsChanged == 1;

        }

 

        #endregion

    }

}

Implement a WCF Service hosted in IIS

  1. Create a new web site of type WCF Service named InventoryServiceIIS.
  2. Add a reference to the InventoryAccessLibrary project.
  3. Delete the files Service.cs and IService.cs in the App_Code folder.
  4. Change the single line in the Services.svc file to read:

    <%@ ServiceHost Language="C#" Debug="true" Service="InventoryAccessLibrary.InventoryAccess" %>

  5. In the web.config file, make the following changes to the system.serviceModel element (at the end of the file).
    1. The service name should be “InventoryAccessLibrary.InventoryAccess” instead of “Service”.
    2. The contract attribute of the end point should be “InventoryContracts.IInventory” instead of IService.
    3. Also change the binding from “wsHttpBinding” to “basicBinding”.
    4. Enable debugging: Set the value of the debug attribute in the <compilation> element to “true”.
  6. Use port 11111:
    1. In Solution Explorer right click on the InventoryServiceIIS node.
    2. Go to the Properties window and change “Use dynamic ports” to false.
    3. Change the port field to 11111.
  7. Test the service:
    1. In Solution Explorer right click on Service.svc and select View in Browser.
    2. Verify that your browser successfully opens the test harness for the Inventory service.

Create a Client Application

  1. Create a new web site of type Console Application named InventoryClientApp.
  2. Add a reference to the InventoryContracts library.
  3. Add a service reference to the InventoryServiceIIS service and specify ServiceReferences as the namespace for the proxy class.
  4. In Program.cs add using directives for the InventoryContracts and InventoryClientApp.ServiceReferences namespaces.
  5. Consume the service by adding the following code in the Program.cs file:

    namespace InventoryClientApp

    {

        class Program

        {

            static void Main(string[] args)

            {

                InventoryClient client = new InventoryClient();

                foreach (Product product in client.GetProducts())

                {

                    Console.WriteLine("{0} {1}", product.Name, product.UnitsInStock);

                }

                Console.ReadLine();

            }

        }

    }

  6. Run the client and verify that it can retrieve the product information from the service.

Add a Self-Hosted Console Application for the Service

  1. Create a new project of type Console Application named InventoryServiceConsole.
  2. Add references to System.ServiceModel and to InventoryAccessLibrary.
  3. In Program.cs add using directives for the System.ServiceModel, InventoryContracts and InventoryAccessLibrary namespaces.
  4. Implement hosting of the InventoryAccessLibrary.InventoryAccess class by adding the following code in the Program.cs file:

namespace InventoryServiceConsole

{

    class Program

    {

        static void Main(string[] args)

        {

            Type serviceType = typeof(InventoryAccess);

            Uri baseAddress = new Uri(

                "http://localhost:11112/InventoryServiceConsole/");

 

            using (ServiceHost host = new ServiceHost(serviceType, baseAddress))

            {

                string endPointAddress = "Service.svc";

 

                host.AddServiceEndpoint(

                    typeof(IInventory),

                    new BasicHttpBinding(),

                    endPointAddress);

 

                host.Open();

 

                Console.WriteLine("Listening for requests on {0}",

                    baseAddress + endPointAddress);

 

                Console.ReadLine();

            }

        }

    }

}          

Modify the Client Application to use the Console Host

  1. Open the app.config file of the Client Applicationץ In the endpoint element, change the address to: http://localhost:11112/InventoryServiceConsole/Service.svc
  2. Test the console hosted service:
    1. Right click the InventoryServiceConsole project and select “Set as Start Up Project”.
    2. Control+F5 to start the host outside the debugger.
    3. Make sure the WCF service hosted in IIS is closed (e.g. from the icon on the system tray).
    4. Right click the InventoryClientApp project and select Debug->Start new instance.
    5. Verify that though the WCF Web Service Site is closed, the client functions correctly.

Add a Self-Hosted Windows Service for the Service

  1. Create a new project of type Windows Service named InventoryWindowsService.
  2. Add references to System.ServiceModel and to InventoryAccessLibrary. Rename the Service1.cs file and class to Service.
  3. In Service.cs copy the code from the self-hosted console application into the OnStart method with the following changes:
    1. The host variable should be a member not a local variable.
    2. The host variable should not be disposed of in the OnStart method, instead, Close it in the OnStop method.
  4. Create installer classes for the Windows service and its process:
    1. Add a new item of type Installer Class. Name it InventoryServiceInstaller.
    2. Update the constructor so you have this code in InventoryServiceInstaller.cs: 

      namespace InventoryWindowsService

      {

          [RunInstaller(true)]

          public partial class InventoryServiceInstaller : Installer

          {

              public InventoryServiceInstaller()

              {

                  InitializeComponent();

       

                  ServiceProcessInstaller pi = new ServiceProcessInstaller();

                  pi.Account = ServiceAccount.LocalSystem;

       

                  ServiceInstaller si = new ServiceInstaller();

                  si.ServiceName = "InventoryService";

       

                  Installers.Add(pi);

                  Installers.Add(si);

              }

          }

      }

  5. Install the service:
    From the Visual Studio 2008 command prompt navigate to the target folder of the InventoryWindowService project and run the following command:
    installutil /i InventoryWindowsService.exe
  6. Start the service:
    From the command prompt run: net start InventoryService.

Test the Client Application with the Windows Service Host

  1. Verify that the InventoryServiceConsole application is not running.
  2. Run the InventoryClientApp project
  3. Verify that though the WCF Web Service Site is not running and the InventoryServiceConsole application is not running, the client functions correctly.
  4. To clean up, run installutil /u InventoryWindowsService.exe from the command prompt to stop and uninstall the Windows service.
Published Sunday, May 31, 2009 11:57 PM by David Sackstein
תגים:, ,

Comments

# re: A Walkthrough for WCF (MOC 6461)

Sunday, March 07, 2010 8:32 AM by sergio alvarez

i´m taking the curse this week and i can´t get any sample to work, because the database is not i my system and don´t know how to install it.

where can i download and install the database the examples, here is part of the code

return new SqlConnection("Data Source=.\\SQLEXPRESS;" +

                                    "Initial Catalog=Appointments;" +

                                    "Integrated Security=SSPI;" +

                                    "Connection Timeout=15");    

Leave a Comment

(required) 
(required) 
(optional)
(required) 

Enter the numbers above:
Powered by Community Server (Commercial Edition), by Telligent Systems