To Be Posted



Learning Links

Programming Reference Links
Lessons Learned - The Hard Way
Create WCF Service (still a bit confusing, needs work)
  1. Create a New Project using the WCF Service Library template.
    Name it ProductService.

  2. Add a Web.config file.
  3. Rename the Service1.cs file to ProductsService.cs
  4. Rename the IService1.cs file to IProductsService.cs
  5. Open the code view of IProductsService.cs.
    • Decide what you will publish in your service.
    • Use DataContract/DataMember to declare your data class objects to the service.
    • Use ServiceContract/OperationContract to declare your Methods to the service.
    • Do NOT include the actual code for the methods.
  6. Listing: IProductsService.cs
    
    ...
    namespace ProductService
    {
        /* NOTE: If you change the interface name "IService1" here, you must also update the reference to "IService1" in App.config.   */
        [ServiceContract]
        public interface IProductService
        {
            [OperationContract]
            List ListProducts();
    
            [OperationContract]
            CompositeType GetDataUsingDataContract(CompositeType composite);
    
            // TODO: Add your service operations here
        }
    
        // Use a data contract as illustrated in the sample below to add composite types to service operations
        [DataContract]
        public class Product
        {
        
            [DataMember]
            public string Name;
    
            [DataMember]
            public string ProductNumber;
    
            [DataMember]
            public string Color;
    
            [DataMember]
            public decimal ListPrice;
        }
    }
    
  7. Implementing the Service.
    • Open the ProductService.cs class file.
    • Rename the ProductService class to ProductServiceImpl
    • Develop the Methods which will be exposed via the service.
    • Listing: ProductService.cs
      
      ...
      namespace ProductService
      {
          /* NOTE: If you change the interface name "IService1" here, you must also update the reference to "IService1" in App.config.   */
          public class ProductServiceImpl : IProductService
          {
              public List<string> ListProducts()
              {
                  // Read the configuration information for connecting to
                  // the AdventureWorks database
                  Database dbAdventureWorks =
                  DatabaseFactory.CreateDatabase("AdventureWorksConnection");
                  
                  // Retrieve the details of all products by using a DataReader
                  string queryString = @"SELECT ProductNumber
                  FROM Production.Product";
                  IDataReader productsReader =
                  dbAdventureWorks.ExecuteReader(CommandType.Text, queryString);
                  
                  // Create and populate a list of products
                  List<string> productsList = new List<string>();
                  while (productsReader.Read())
                  {
                      string productNumber = productsReader.GetString(0);
                      productsList.Add(productNumber);
                  }
                  //Return the list of products
                  return productsList;
              }
              
              public Product GetProduct(string productNumber)
              {
                  Database dbAdventureWorks =
                  DatabaseFactory.CreateDatabase("AdventureWorksConnection");
      
                  // Retrieve the details of the selected product by using a DataReader
                  string queryString = @"SELECT ProductNumber, Name, Color, ListPrice
                  FROM Production.Product
                  WHERE ProductNumber = '" + productNumber + "'";
                  IDataReader productsReader =
                  dbAdventureWorks.ExecuteReader(CommandType.Text, queryString);
                  
                  // Create and populate a product
                  Product product = new Product();
                  if (productsReader.Read())
                  {
                      product.ProductNumber = productsReader.GetString(0);
                      product.Name = productsReader.GetString(1);
                      if (productsReader.IsDBNull(2))
                      {
                          product.Color = "N/A";
                      }
                      else
                      {
                          product.Color = productsReader.GetString(2);
                      }
                      product.ListPrice = productsReader.GetDecimal(3);
                  }
                  
                  //Return the product
                  return product;
              }                
              
              
              public int CurrentStockLevel(string productNumber)
              {
                  Database dbAdventureWorks =
                  DatabaseFactory.CreateDatabase("AdventureWorksConnection");
                  
                  // Obtain the current stock level of the selected product
                  // The stock level can be found by summing the quantity of the product
                  // available in all bins in the ProductInventory table
                  // The ProductID value has to be retrieved from the Product table
                  string queryString = @"SELECT SUM(Quantity)
                      FROM Production.ProductInventory
                      WHERE ProductID =
                      (SELECT ProductID
                          FROM Production.Product
                          WHERE ProductNumber = '" + productNumber +
                      "')";
                      
                  int stockLevel = (int)dbAdventureWorks.ExecuteScalar(CommandType.Text, queryString);
                      
                  //Return the current stock level
                  return stockLevel;
              }
      
              public bool ChangeStockLevel(string productNumber, int newStockLevel, string shelf, int bin)
              {
                  Database dbAdventureWorks =
                  DatabaseFactory.CreateDatabase("AdventureWorksConnection");
                  
                  // Modify the current stock level of the selected product
                  // The ProductID value has to be retrieved from the Product table
                  string updateString = @"UPDATE Production.ProductInventory
                  SET Quantity = Quantity + " + newStockLevel +
                      "WHERE Shelf = '" + shelf + "'" +
                      "AND Bin = " + bin +
                      @"AND ProductID =
                      (SELECT ProductID
                          FROM Production.Product
                          WHERE ProductNumber = '" + productNumber +
                      "')";
                  int numRowsChanged = (int)dbAdventureWorks.ExecuteNonQuery(CommandType.Text, updateString);
                  
                  // If no rows were updated, return false to indicate that the input
                  // parameters did not identify a valid product and location
                  // Otherwise return true to indicate success
                  return (numRowsChanged != 0);
              }
              
      }
      
  8. Build the project.
  9. Configuring, Deploying and Testing the WCF Service.
    1. Open the Properties pages for the project.
    2. Click the Build tab. In the Output section of the page, change the Output path property to bin.
    3. Click Save All
    4. Add a new Text File template to the project. Name the file ProductsService.svc. The name of this file must be the same name of the Web Service and have the .svc suffix.
    5. Add the following code to the ProductsService.svc file. The Service attribute of the ServiceHost directive specifies the namespace (Products) and
      the class (ProductsServiceImpl) that implements the service. The Assembly directive specifies
      the name of the assembly (ProductsService) containing this namespace and class.
    6. <%@ServiceHost Service="Products.ProductsServiceImpl" %>
      <%@Assembly Name="ProductsService" %>
      
    7. Edit the Web.config file. Add the following sections shown in bold.
    8. 
      <?xml version="1.0" encoding="utf-8" ?>
      <configuration>
          <configSections>
              <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.
                  Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, 
                  Version=2.0.0.0, Culture=neutral, PublicKeyToken=null" />
          </configSections>
          <dataConfiguration defaultDatabase="AdventureWorksConnection" />
          <connectionStrings>
              <add name="AdventureWorksConnection" connectionString="Database=
                  AdventureWorks;Server=(local)\SQLEXPRESS;Integrated Security=SSPI;"
                  providerName="System.Data.SqlClient" />
          </connectionStrings> 
          <system.serviceModel>
              <services>
                  <service name="Products.ProductsServiceImpl" behaviorConfiguration="ProductsBehavior">
                          <endpoint address=""
                                      binding="basicHttpBinding"
                                      contract="Products.IProductsService" />
                  </service>
              </services>
              <behaviors>
                  <serviceBehaviors>
                      <behavior name="ProductsBehavior">
                          <serviceMetadata httpGetEnabled="true" />
                      </behavior>
                  </serviceBehaviors>
              </behaviors>
          </system.serviceModel>
      </configuration>
      
      
    9. Build the Solution.
    10. You can now deploy the service to IIS by creating a virtual folder. You must also ensure that
      the account used to run the code for the Web service, the local ASPNET account on your computer
      by default, has sufficient rights to access the contents of this folder.
    11. Deploy the WCF service to IIS (Windows Vista only)
      1. In the Windows Control Panel, click System and Maintenance, click Administrative
        Tools, and then double-click Internet Information Services (IIS) Manager.
        The Internet Information Services (IIS) Manager starts.
      2. In the Internet Information Services (IIS) Manager, expand the node corresponding to
        your computer in the tree-view, and then expand Web sites.
      3. Right-click Default Web Site, and then click Add Application.
        The Add Application dialog box appears.
      4. In the Add Application dialog box, in the Alias text box type ProductsService.
      5. Click the browse button (with the ellipses “…”) adjacent to the Physical path text box. In
        the Browse for Folder dialog box, select the folder Microsoft Press\WCF Step By
        Step\Chapter 1\ProductsService\ProductsService under your \My Documents folder,
        click then click OK.
      6. In the Add Application dialog box, click OK.
        The ProductsService Web application should appear under the Default Web site node in
        the Internet Information Services (IIS) Manager.
      7. Close the Internet Information Services (IIS) Manager.
    12. Deploy the WCF service to IIS (Windows Vista only)
      1. On the Windows Start menu, click Internet Explorer.
      2. In the Address bar, type the address http://localhost/ProductsService/
        ProductsService.svc, and then click Go. This page describes how you can obtain the metadata describing the service and use this
        information to help build a client application.
    13. Building a WCF Client
      1. Add a new Console Application template project to the solution. Name it ProductsClient<.span>.
      2. Add a referenct to the System.ServiceModel assembly to the ProductsClient project
      3. On the Project menu, click Add Service Reference. In the Add Service Reference dialog
        box, type http://localhost/ProductsService/ProductsService.svc?wsdl for the service
        URL, type ProductsService for the service reference name, and then click OK.
      4. Open the codeview for the ProductsClient.app.config file.
      5. Display the Program.cs file for the ProductsClient project in the code view window. Add the following statements to the top of the file
        using System.ServiceModel;
        using ProductsClient.ProductsService;
        
        
      6. In the Main() method, add the following statements.
            // Create a proxy object and connect to the service
            ProductsServiceClient proxy =
                new ProductsServiceClient("BasicHttpBinding_IProductsService");
        
            // Test the operations in the service
            
            // 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: " + productNumber);
            }
            Console.WriteLine();
            
            // Fetch the details for a specific product
            Console.WriteLine("Test 2: Display the details of a product");
            Product product = proxy.GetProduct("WB-H098");
            Console.WriteLine("Number: " + product.ProductNumber);
            Console.WriteLine("Name: " + product.Name);
            Console.WriteLine("Color: " + product.Color);
            Console.WriteLine("Price: " + product.ListPrice);
            Console.WriteLine();
        
            // Query the stock level of this product
            Console.WriteLine("Test 3: Display the stock level of a product");
            int numInStock = proxy.CurrentStockLevel("WB-H098");
            Console.WriteLine("Current stock level: " + numInStock);
            Console.WriteLine();
            
            // Modify the stock level of this product
            Console.WriteLine("Test 4: Modify the stock level of a product");
            if (proxy.ChangeStockLevel("WB-H098", 100, "N/A", 0))
            {
                numInStock = proxy.CurrentStockLevel("WB-H098");
                Console.WriteLine("Stock changed. Current stock level: " + numInStock);
            }
            else
            {
                Console.WriteLine("Stock level update failed");
            }
            Console.WriteLine();
            
        
      7. Save the Project and Build the Solution
    14. Run the client application
      1. Set the ProductsClient project as the Start-Up Project
      2. Run the Project