Thursday, January 30, 2014

WCF Tutorial Part-II

Lesson 5:
Deploying a WCF Service
When you have built and tested your WCF service, you must then deploy it to your target platform.
This lesson discusses some of the options that you can use to deploy WCF services housed in different host environments.

Preparing Services for Deployment

When you prepare your WCF service for the host environment, you must perform the following steps:
·         Prepare your code for deployment; for example, sign your assemblies where necessary.
·         Check that your configuration is production-ready; for example, disable the passing of remote exception details.
·         Change the environment-specific configuration such as WCF endpoints for the target environment.

Deploying IIS-Hosted Services

When you deploy a typical WCF service to IIS, you perform the following tasks:
1.    Check that your configuration is production-ready so that things like debugging and exception detail propagation are disabled in your WCF service.
2.    Ensure that your local assemblies are deployed into the \bin directory and that globally shared assemblies are sourced from the Global Assembly Cache (GAC).
3.    Check the environment-specific configuration such as your WCF service endpoints and security information.
4.    Ensure that you have the correct version of the .NET Framework installed on the host computer.
5.    Create a new Application folder in IIS that points to your WCF service folder.

Deploying WAS-Hosted Services

Deploying your WCF service to a WAS host environment follows the same process as hosting your WCF service in IIS 7.0. The main different is that you must also install the Windows Activation components and configure the non-HTTP activation for your WCF service.


Deploying Self-Hosted Services

If you use a self-hosted WCF service, you must deploy both the hosting assembly and the WCF service library assemblies to your target computer.
In a production environment, you can perform deployment by:
·         Installing Microsoft Installer (MSI) packages on the target machine.
·         Deploying by using administrative mechanisms such as Active Directory® directory service group policy or Systems Management Service (SMS). In this latter case, you may have to hand off files and folders or Microsoft Windows Installers (.msi files) to the installation team.
You can deploy your assemblies by using the Publish wizard in Visual Studio 2008, which can build your solution to a specific location such as a network share. To use the Publish wizard, in Visual Studio 2008, on the Build menu, click Publish <project name>.
You can create a MSI in Visual Studio 2008 with the Setup Project template.
If you use a Windows service to host your WCF service, you must also register it with the Windows service manager so that you can configure it to start and stop correctly in the Windows Service MMC snap-in. The following code shows the ServiceProcessInstaller and ServiceInstaller classes that you would typically package in your MSI to register the Windows service at installation time.
[Visual Basic]
<RunInstaller(True)> _
Public Class ProjectInstaller
   Inherits Installer
   Private process As ServiceProcessInstaller
   Private service As ServiceInstaller
   Public Sub New()
      process = New ServiceProcessInstaller()
     process.Account = ServiceAccount.LocalSystem
     service = New ServiceInstaller()
     service.ServiceName = "WCFBankService"
     Installers.Add(process)
     Installers.Add(service)
   End Sub
End Class

[Visual C#]
[RunInstaller(true)]
public class ProjectInstaller : Installer
{
    private ServiceProcessInstaller process;
    private ServiceInstaller service;

    public ProjectInstaller()
    {
        process = new ServiceProcessInstaller();
        process.Account = ServiceAccount.LocalSystem;
        service = new ServiceInstaller();
        service.ServiceName = "WCFBankService";
        Installers.Add(process);
        Installers.Add(service);
    }
}


Demonstration: Deploying a Service to a Remote Host


Lab: Configure and Host a WCF Service

Scenario

You are a developer on the Contoso, Ltd Clinic Management product team. Your team has developed part of the Appointment service and your task now is to look at the different ways store the WCF configurations settings and hosting the Appointment service.
In this exercise, you will develop an EXE application to host the Appointment service.

Exercise 1: Creating a Programmatically Configured Managed Application to Host a Service

You are a developer on the Contoso, Ltd Clinic Management product team. Your team has developed part of the Appointment service and your task now is to look at the different ways store the WCF configurations settings and hosting the Appointment service.
In this exercise, you will develop an EXE application to host the Appointment service.
The main tasks for this exercise are as follows:
1.    Start the 6461A-LON-DEV-02 virtual machine and log on as Student.
2.    Open the existing ConnectedWCF solution.
3.    Add a new Windows console application to the ConnectedWCF solution.
4.    Add code to host the Appointment service.
5.    Change the endpoint address in the ClinicAdminClient project.
6.    Set the ConnectedWCF solution startup projects.
7.    Build and run the solution.

Task 1: Start the 6461A-LON-DEV-02 virtual machine and log on as Student

1.    Open the Virtual Server Remote Control Client, and then double-click 6461A-LON-DEV-02.
2.    Log on to 6461A-LON-DEV-02 as Student by using the password Pa$$w0rd.

Task 2: Open the existing ConnectedWCF solution

1.    Open Microsoft Visual Studio 2008 as an ADMINISTRATOR.
2.    Open the existing ConnectedWCF solution. If you are using Microsoft Visual Basic® development system, browse the E:\Labfiles\Starter\VB\Ex1\ConnectedWCF folder, and then double-click the ConnectedWCF.sln file. If you are using Microsoft Visual C#® development tool, browse to the E:\Labfiles\Starter\CS\Ex1\ConnectedWCF folder, and then double-click the ConnectedWCF.sln file.

Task 3: Add a new Windows Console application to the ConnectedWCF solution

1.    Add a new project with the following information to the ConnectedWCF solution:
    • Project types: If you are using Visual Basic, expand Visual Basic, and then click Windows. If you are using Visual C#, expand Visual C#, and then click Windows.
    • Templates: ConsoleApplication.
    • Name: AppointmentServiceSelfHost.
    • Location: If you are using Visual Basic, in the Location box, type E:\Labfiles\Starter\VB\Ex1\ConnectedWCF

       
      If you are using Visual C#, in the Location box, type E:\Labfiles\Starter\CS\Ex1\ConnectedWCF

Task 4: Add code to host the Appointment service

1.    In the AppointmentServiceSelfHost project, add a reference to the System.ServiceModel assembly and the AppointmentService assembly in the AppointmentService project.
2.    In the Module1 class (for Visual Basic) or Program class (for Visual C#), bring the System.ServiceModel namespace into scope.
3.    In the Main method, create a new Uri object named baseAddress. Pass the string http://localhost:8002/Contoso as a parameter.
4.    Create a new Type object named instanceType. Initialize the instanceType object to com.contoso.AppointmentService.AppointmentServiceImplementation.
5.    Create a new ServiceHost object named host. Pass the instanceType and baseAddress objects to the ServiceHost constructor.
6.    Add a Using block (for Visual Basic) or using (for Visual C#) block and pass the host object as a parameter.
7.    In the using block, add code to do the following:
    1. Create a new instance of the Type class named contractType. Initialize the contractType object to com.contoso.AppointmentService.AppointmentServiceContract.
    2. Create a new string variable named relativeAddress, and then initialize it to the text AppointmentService.
    3. Add a WSHttpBinding endpoint to the host object. Do this by invoking the AddServiceEndpoint method on the host object. Pass the contractType variable, a new WsHttpBinding object, and the relativeAddress variable as parameters.
    4. Invoke the Open method on the host object.
    5. Write the following message to the console:

      Appointment service running. Press <ENTER> to quit.
    6. Invoke the ReadLine method on the Console class to stop the console from closing.
    7. Invoke the Close method on the host object.

Task 5: Change the endpoint address in the ClinicAdminClient project

1.    In the Microsoft Service Configuration Editor, open the ClinicAdminClient project's app.config (for Visual Basic) or App.config (for Visual C#) file.
2.    Change the address for the client endpoint WSHttpBinding_AppointmentServiceContract to http://localhost:8002/Contoso/AppointmentService.
3.    Save your changes, and then close the Microsoft Service Configuration Editor.

Task 6: Set the ConnectedWCF solution startup projects

1.    In Solution Explorer, right-click the ConnectedWCF solution, and then click Set Startup Projects.
2.    Configure the ConnectedWCF solution so that the AppointmentServiceSelfHost and ClinicAdminClient projects start when you run the solution.

Task 7: Build and run the solution

1.    Build the ConnectedWCF solution.
2.    Run the ConnectedWCF solution with debugging.
3.    Wait for the console window to display the following message:

Appointment service running. Press <ENTER> to quit.

On the Clinic Administration Client form, on the Create Appointment tab, click Find Slots. You should see the list of available appointment slots.
4.    Stop debugging.

Results: After this exercise, you should have developed an EXE host for the Appointment service.

Exercise 1: Answer Key (detailed steps)


Exercise 2: Calling a Service Hosted in a Managed Application by Using Programmatic Configuration

In this exercise, you will programmatically define the WCF configuration for the ClinicAdminClient project.
The main tasks for this exercise are as follows:
1.    Remove the existing endpoint configuration from the ClinicAdminClient configuration file.
2.    Programmatically add code to define the endpoint configuration.
3.    Build and run the solution.

Task 1: Remove the existing endpoint configuration from the ClinicAdminClient configuration file

1.    Open the existing ConnectedWCF solution. If you are using Visual Basic, browse to the E:\Labfiles\Starter\VB\Ex2\ConnectedWCF folder, and then double-click the ConnectedWCF.sln file. If you are using Visual C#, browse to the E:\Labfiles\Starter\CS\Ex2\ConnectedWCF folder, and then double-click the ConnectedWCF.sln file.
2.    In the Code Editor window, open the ClinicAdminClient project's app.config (for Visual Basic) or App.config (for Visual C#) file.
3.    In the Code Editor window for the configuration file, remove the <system.serviceModel> </system.serviceModel> element and all its subelements.
4.    Save your changes.

Task 2: Programmatically add code to define the endpoint configuration

1.    In the Code Editor window, open the ClinicAdminForm class.
2.    If you are using Visual Basic, bring the System.ServiceModel namespace into scope.
3.    In the GetAppointmentServiceProxy method, locate the TODO 2 comment, and then remove the existing method body code.
4.    In the GetAppointmentServiceProxy method, add code to do the following:
    1. Create a new instance of the EndpointAddress class named address. Pass the text http://localhost:8002/Contoso/AppointmentService to the constructor.
    2. Create a new instance of the WSHttpBinding class named binding.
    3. Create a new instance of the AppointmentServiceContract class named proxy.
    4. Instantiate the proxy object to the return value of the CreateChannel method of the ChannelFactory class. Pass the binding and address objects as parameters in the method call.
    5. Return the proxy object to the method caller.

Task 3: Build and run the solution

1.    Build the ConnectedWCF solution.
2.    Run the ConnectedWCF solution with debugging.
3.    Wait for the console window to display the following message:

Appointment service running. Press <ENTER> to quit.

On the Clinic Administration Client form, on the Create Appointment tab, click Find Slots. You should see the list of available appointment slots.
4.    Stop debugging.
Results: After this exercise, you should have programmatically defined the WCF configuration for the AppointmentServiceSelfHost and ClinicAdminClient projects.

Exercise 2: Answer Key (detailed steps)


Exercise 3: Defining Service Settings by Using External Configuration

In this exercise, you will remove the programmatic WCF configuration from the AppointmentServiceSelfHost and ClinicAdminClient projects and then provide the configuration in external configuration files.
The main tasks for this exercise are as follows:
1.    Add an external configuration file to the AppointmentServiceSelfHost project.
2.    Remove the programmatic endpoint configuration from the AppointmentServiceSelfHost project.
3.    Remove the programmatic endpoint configuration from the ClinicAdminClient project.
4.    Build and run the solution.

Task 1: Add an external configuration file to the AppointmentServiceSelfHost project

1.    Open the existing ConnectedWCF solution. If you are using Visual Basic, browse to the E:\Labfiles\Starter\VB\Ex3\ConnectedWCF folder, and then double-click the ConnectedWCF.sln file. If you are using Visual C#, browse to the E:\Labfiles\Starter\CS\Ex3\ConnectedWCF folder, and then double-click the ConnectedWCF.sln file.
2.    Add a new Application Configuration File named App.config to the AppointmentServiceSelfHost project.
3.    In the Microsoft Service Configuration Editor window, open the app.config file (for Visual Basic) or the App.config (for Visual C#) file.
4.    Add a new service named com.contoso.AppointmentService.AppointmentServiceImplementation.
5.    Add a new service endpoint with the following information:
    • Name: APService_WsHTTP
    • Address: http://localhost:8002/Contoso/AppointmentService
    • Binding: wsHttpBinding
    • Contract: com.contoso.AppointmentService.AppointmentServiceContract
6.    Save your changes, and then close the Microsoft Service Configuration Editor window.

Task 2: Remove the programmatic endpoint configuration from the AppointmentServiceSelfHost project

1.    In the Code Editor window, open the AppointmentServiceSelfHost project's Module1 class (for Visual Basic) or Program class (for Visual C#).
2.    In the Main method, make the following changes to the existing code:
    1. Remove the code that defines the baseAddress object.
    2. Remove the baseAddress parameter from the ServiceHost constructor.
    3. Remove the code that defines the contractType object and relativeAddress string.
    4. Remove the line of code that adds a new service endpoint to the host object.

Task 3: Remove the programmatic endpoint configuration from the ClinicAdminClient project

1.    In the Microsoft Service Configuration Editor window, open the ClinicAdminClient project's app.config file (for Visual Basic) or App.config file (for Visual C#).
2.    Create a new client endpoint with the following information:
    • Name: APService_WsHTTP
    • Address: http://localhost:8002/Contoso/AppointmentService
    • Binding: wsHttpBinding
    • Contract: AppointmentServiceReference.AppointmentServiceContract

3.    Save your changes, and then close the Microsoft Service Configuration Editor window.
4.    In the Code Editor window, open the ClinicAdminForm class.
5.    In the GetAppointmentServiceProxy method, perform the following steps:
    1. Remove the existing method body code.
    2. Add code to return a new AppointmentServiceContractClient object.

Task 4: Build and run the solution

1.    Build the ConnectedWCF solution.
2.    Run the ConnectedWCF solution with debugging.
3.    Wait for the console window to display the following message:

Appointment service running. Press <ENTER> to quit.

On the Clinic Administration Client form, on the Create Appointment tab, click Find Slots.
4.    Stop debugging.
Results: After this exercise, you should have defined the WCF configuration for the AppointmentServiceSelfHost and ClinicAdminClient projects in external configuration files.

Exercise 3: Answer Key (detailed steps)


Exercise 4: Employing Different Hosting Options for a Service

In this exercise, you will host the appointment service by using WAS. To use WAS, you will add additional endpoints to both the AppointmentServiceIISHost and the ClinicAdminClient projects.
The main tasks for this exercise are as follows:
1.    Add a new Application directory to IIS.
2.    Add the netTcpBinding binding to the WAS configuration.
3.    Enable TCP support for the AppointmentServiceIISHost application.
4.    Configure a TCP endpoint for the AppointmentServiceIISHost application.
5.    Configure a TCP binding for the ClinicAdminClient project.
6.    Set the ConnectedWCF solution startup projects.
7.    Build and run the solution.

Task 1: Add a new Application directory to IIS

1.    Open the Internet Information Services (IIS) Manager window.
2.    Add a new application to the Default Web Site with the following information:
    • Alias: AppointmentServiceIISHost
    • Physical path: If you are using Visual Basic, browse to E:\Labfiles\Starter\VB\Ex4\ConnectedWCF\AppointmentServiceIISHost.
    • If you are using Visual C#, browse to E:\Labfiles\Starter\CS\Ex4\ConnectedWCF\AppointmentServiceIISHost.
3.    Close the Internet Information Services (IIS) Manager window.

Task 2: Add the net.tcp binding to the WAS configuration

1.    In Windows Explorer, browse to the E:\Labfiles\Starter\ folder.
2.    In Notepad, open the AddTcpBindingToWas.cmd file.
3.    Examine the command, and then close Notepad.
4.    As an ADMINISTRATOR, run the AddTcpBindingToWas.cmd file.
5.    In the Command Prompt window, ensure that the command executed successfully, and then press ENTER.

Task 3: Enable TCP support for the AppointmentServiceIISHost application

1.    In Windows Explorer, browse to the E:\Labfiles\Starter\ folder, and then open the AppointmentServiceIISHostTcpSupport.cmd file in Notepad.
2.    Examine the command, and then close Notepad.
3.    As an ADMINISTRATOR, run the AppointmentServiceIISHostTcpSupport.cmd file.
4.    In the Command Prompt window, ensure that the command executed successfully, and then press ENTER.
5.    Close Windows Explorer.

Task 4: Configure a TCP endpoint for the AppointmentServiceIISHost application

1.    Switch to Visual Studio 2008.
2.    Open the existing ConnectedWCF solution. If you are using Visual Basic, browse to the E:\Labfiles\Starter\VB\Ex4\ConnectedWCF folder, and then double-click the ConnectedWCF.sln file. If you are using Visual C#, browse to the E:\Labfiles\Starter\CS\Ex4\ConnectedWCF folder, and then double-click the ConnectedWCF.sln file.
3.    In the Microsoft Service Configuration Editor window, open the AppointmentServiceIISHost project's Web.config file.
4.    Add a new service endpoint to the com.contoso.AppointmentService.AppointmentServiceImplementation service with the following information:
    • Name: APService_TCP
    • Address: net.tcp://localhost:9090/AppointmentServiceIISHost/AppointmentServiceIISHost.svc
    • Binding: netTcpBinding
    • Contract: com.contoso.AppointmentService.AppointmentServiceContract
5.    Save your changes, and then close the Microsoft Service Configuration Editor window.

Task 5: Configure a TCP binding for the ClinicAdminClient application

1.    In the Microsoft Service Configuration Editor window, open the ClinicAdminClient project's app.config file (for Visual Basic) or App.config file (for Visual C#).
2.    Define a new client endpoint with the following information:
    • Name: APService_TCP
    • Address: net.tcp://localhost:9090/AppointmentServiceIISHost/AppointmentServiceIISHost.svc
    • Binding: netTcpBinding
    • Contract: AppointmentServiceReference.AppointmentServiceContract
3.    Save your changes, and then close the Microsoft Service Configuration Editor.
4.    In the Code Editor window for the ClinicAdminForm class, in the GetAppointmentServiceProxy method, pass the string APService_TCP to the AppointmentServiceContractClient constructor.

Task 6: Set the ConnectedWCF solution startup projects

1.    In Solution Explorer, right-click the ConnectedWCF solution, and then click Set Startup Projects.
2.    Configure the ConnectedWCF solution so only the ClinicAdminClient project starts when you run the solution.

Task 7: Build and run the solution

1.    Build the ConnectedWCF solution.
2.    Run the ConnectedWCF solution with debugging.
3.    On the Clinic Administration Client form, on the Create Appointment tab, click Find Slots.
4.    Stop debugging.
Results: After this exercise, you should have hosted the appointment service in IIS by using WAS.

Exercise 4: Answer Key (detailed steps)


Module 3
Endpoints and Behaviors
Endpoints and behaviors play an important role to achieve successful communication between your Windows® Communication Foundation (WCF) service and client application. Endpoints provide a gateway so that client applications can communicate with your service, and behaviors provide a way of layering additional runtime functionality.
This module discusses how you can expose your WCF service over multiple endpoints, how you can alter run-time behavior by applying behaviors, and how you can configure your WCF service to communicate with a non-WCF Web service.
·         Lesson 1:
·         Exposing WCF Services over Different Endpoints
·        
·         There may be situations that require you to expose your WCF service to clients that use different bindings; for example, clients may use TCP-based bindings as opposed to bindings that are based on Hypertext Transfer Protocol (HTTP). WCF supports different bindings for the same service by enabling you to define multiple service endpoints.
·         This lesson discusses the various binding configurations available and how you can expose multiple service endpoints.

Relating Services to Endpoints

Your WCF service may require one or many endpoints:
·         If you have one type of client (for example, intranet clients) then you may require only a single endpoint with a suitable binding.
·         If you have multiple types of client, you may have to use different bindings for the different types. This means that your service must expose multiple endpoints. For example, you could use a netTcpBinding endpoint to expose your service to an intranet client and simultaneously use a wsHttpBinding endpoint to expose your service to an Internet-based client.
·         If your service implements multiple service contracts, you will require different endpoints for the different contracts.
·         If the type of client or its communication requirements change over time, you may have to alter the binding that your service endpoint uses. The same applies if the service is relocated. In this case, the address will change. To ease migration, you may decide to support two endpoints: one that uses the new binding or address and one that uses the legacy binding or address. Exposing multiple endpoints does not force you to change existing endpoints; this enables you to keep your service available to existing clients who may still use the old endpoints.


Bindings and Channels

So far in this course, you have exposed a WCF service with multiple endpoints by using a wsHttpBinding binding and a netTcpBinding binding.
The following will influence your choice of bindings:
·         Style of communication such as request or response, one-way, and duplex.
·         Interoperability requirements.
·         Security requirements.
·         Performance requirements.
·         Transactional requirements.
The binding that you choose when you define each endpoint of your service dictates the makeup of the channel stack for that endpoint. You cannot use one type of binding for the service and another type for the client and expect them to communicate successfully, because each binding consists of different protocols. If any of these are missing or mismatched, an error will occur.
For example, if you use the basicHttpBinding binding, the channels in the channel stack will vary when compared to a wsHttpBinding binding.
The basicHttpBinding binding includes the System.ServiceModel.Channels.TextMessageEncodingBindingElement type and the System.ServiceModel.Channels.HttpTransportBindingElement type by default, but it does not include any security settings. The basicHttpBinding binding is classed as a “vanilla” binding, because it provides a blank canvas from which you can define your own settings. However, any changes that you make to the binding are reflected on both the client and the service.

Additional Reading

For more information about WCF bindings, see:
·         "Configuring System-Provided Bindings" on the MSDN Web site.
·         "WCF Bindings In Depth" on the MSDN Web site.


HTTP-Based Bindings

You typically use HTTP-based bindings to expose your WCF service over the Internet and an extranet, although HTTP-based bindings do not perform as well as some of the other types of bindings such as netTcpBinding.
However, what HTTP-based bindings lack in performance is balanced by their ability to interoperate not only with a wide range of existing clients and services but also with clients and services that were created by using non-WCF technologies.
WCF provides the following HTTP-based bindings by default:
·         BasicHttpBinding. Provides an HTTP-based Simple Object Access Protocol (SOAP) binding that enables interoperation with older or less sophisticated Web services such as Microsoft® ASP.NET Web services that use .ASMX files.
·         WsHttpBinding. Provides a binding that supports WS-* protocols.
·         WsDualHttpBinding. Provides an HTTP binding that supports two-way communication.
·         WsFederationHttpBinding. Provides a secure HTTP binding that supports federated security.

Additional Reading

For more information about HTTP-based bindings, see "BasicHttpBinding" Class on the MSDN Web site.


Connection-Oriented Bindings

You can use connection-oriented bindings such as netTcpBinding and NetNamedPipeBinding to expose your WCF service over local networks and intranets.
The netTcpBinding binding provides a secure, reliable method for communicating by using WS-ReliableMessaging, binary message encoding, and the TCP protocol.
The NetNamedPipeBinding binding provides a similar method of communication to the netTcpBinding binding but exposes fewer features because it is designed for communication between clients and services (or multiple services) that are deployed on the same computer.

Additional Reading

For more information about netTcpBinding and NetNamedPipeBinding, see:
·         "NetTcpBinding Class" on the MSDN Web site.
·         "NetNamedPipeBinding Class" on the MSDN Web site.

Queue-Based Bindings

You can also achieve communication in intranets and local networks by using the queue-based bindings in WCF.
Queue-based bindings such as the NetMsmqBinding and MsmqIntegrationBinding bindings focus primarily on providing a reliable communication mechanism that supports a high level of throughput.
One difference between queue-based bindings and HTTP and NetTCP bindings is that the former provide isolation between the client and service. For example, if you use an HTTP or NetTCP binding and the link between the client and service fails, the solution also fails. However, if you use a queue-based binding, the solution continues to function.
Queue-based bindings often use a storage mechanism to store client messages. The messages can then be sent to the service when the service is available.

Additional Reading

For more information about NetMsmqBinding and MsmqIntegrationBinding, see:
·         "NetMsmqBinding Class" on the MSDN Web site.
·         "MsmqIntegrationBinding Class" on the MSDN Web site.

Changing an Endpoint to Use a Different Binding

You can change the binding used in an existing endpoint by modifying the endpoint element either in the configuration file or in any programmatic configuration that you have defined.
With either approach, you must change the binding value. If you use a different transport protocol, you may also have to change the address value. The following code examples show how to change an existing endpoint from basicHttpBinding to netTcpBinding.
[basicHttpBinding endpoint]
<service name="ConnectedWCF.BankService">
   <endpoint address="BankService"
      binding="basicHttpBinding"
      contract="ConnectedWCF.IBank"/>
   <host>
      <baseAddresses>
         <baseAddress baseAddress="http://localhost:8080/Simple"/>
      </baseAddresses>
   </host>
</service>

[netTcpBinding endpoint]
<service name="ConnectedWCF.BankService">
   <endpoint address="BankService"
      binding="netTcpBinding"
      contract="ConnectedWCF.IBank"/>
   <host>
      <baseAddresses>
         <baseAddress baseAddress="net.tcp://localhost:9001/Simple"/>
      </baseAddresses>
   </host>
</service>


Using Both Bindings

To expose your WCF service over multiple endpoints, you must add additional endpoint elements to your WCF configuration. Instead of changing the binding in an existing endpoint, you can define a new endpoint that meets your new requirements, for example, to enable communication over TCP.
WCF provides the necessary functionality to route the requests from multiple endpoints to the same WCF service implementation. The instancing mode determines which service instance handles the request.
The following code example shows a WCF configuration that defines a basicHttpBinding and a netTcpBinding endpoint.
[Multiple endpoint configuration]
<service name="ConnectedWCF.BankService">
  <endpoint address="BankService"
     binding="basicHttpBinding"
     contract="ConnectedWCF.IBank"/>
  <endpoint address="BankService"
     binding="netTcpBinding"
     contract="ConnectedWCF.IBank"/>
  <host>
    <baseAddresses>
      <baseAddress
         baseAddress="http://localhost:8080/Simple"/>
      <baseAddress         
         baseAddress="net.tcp://localhost:9001/Simple"/>
    </baseAddresses>
  </host>
</service>

Additional Reading

For more information about multiple endpoints, see "Specifying an Endpoint Address" on the MSDN Web site.


Exposing Multiple Contracts

WCF enables you to expose multiple contracts in a WCF service, and multiple services each expose a different contract. Exposing multiple contracts is useful because it means that you can release a new version of a contract but still support legacy clients that may continue to use the old contract. You can also support various contracts for various audiences or contracts based on various requirements. For example, you can expose an administration contract for your service to which you will allow access for only a limited group of users.
WCF provides the necessary functionality to route requests through to the correct implementation.
The following code example shows how you can expose two contracts in the same service.
[Single service and multiple contract configuration]
<services>
   <service name="ConnectedWCF.BankImplementation">
      <endpoint address="BankService"
         binding="basicHttpBinding"
         contract="ConnectedWCF.IBank"/>
      <endpoint address="BankAdmin"
         binding="wsHttpBinding"
         contract="ConnectedWCF.IBankAdmin"/>
      <host>
         <baseAddresses>
            <baseAddress baseAddress="http://localhost:8080/Simple"/>
         </baseAddresses>
      </host>
   </service>
</services>

The following code example shows how you can expose two contracts in two different services.
[Multiple service and contract configuration]
<services>
   <service name="ConnectedWCF.BankServiceImplementation">
      <endpoint address="BankService"
         binding="basicHttpBinding"
         contract="ConnectedWCF.IBank"/>
      <host>
         <baseAddresses>
            <baseAddress baseAddress="http://localhost:8080/Simple"/>
         </baseAddresses>
      </host>
   </service>
   <service name="ConnectedWCF.BankAdminImplementation">
      <endpoint address=" BankAdmin"
         binding="wsHttpBinding"
         contract="ConnectedWCF.IBankTransfer"/>
      <host>
         <baseAddresses>
            <baseAddress baseAddress="http://localhost:8080/Simple"/>
         </baseAddresses>
      </host>
   </service>
</services>

Additional Reading

For more information about exposing multiple contracts, see "Multiple Contracts" on the MSDN Web site.

Configuring Bindings

WCF enables you to provide additional configuration for the default bindings. You can do this by defining a binding element in the WCF configuration and then reference that binding element in your endpoint configuration.
The settings that you can configure by using the binding element include the following:
·         allowCookies. Specifies whether the client accepts cookies.
·         maxBufferSize. Specifies the maximum size of the buffer that stores the messages during processing.
·         messageEncoding. Specifies the encoder used to encode the SOAP messages.
In the binding element, you can define the security element. By doing this, you can define additional security settings for your binding such as the mode attribute, which defines what type of security that you use.
The following code example shows how to define a binding configuration element.
[Additional binding configuration]
<system.serviceModel>
   <services>
      <service name="BankService" >
         <endpoint address="http://localhost:8080/BankService"
            contract="IBankService"
            binding="basicHttpBinding"
            bindingConfiguration="myBasicHttpBindingConfig"/>
      </service>
   </services>
   <bindings>
      <basicHttpBinding>
         <binding name="myBasicHttpBindingConfig">
            <!-- Binding configuration elements go here -->
         </binding>
      </basicHttpBinding>
   </bindings>
</system.serviceModel>

Additional Reading

For more information about providing additional binding configurations, see "How to: Specify a Service Binding in Configuration" on the MSDN Web site.


Demonstration: Using a Different Binding



Lesson 2:
Adding Behaviors to Services and Endpoints
WCF enables you to customize the default behavior of the WCF runtime by setting behaviors. This lesson explains how to define behaviors at the service, operation, and endpoint levels.

WCF Behaviors

WCF behaviors enable you to modify the behavior of the runtime; for example, you can use these behaviors to determine if the service contract supports a session-aware channel or the service supports the exposure of a metadata contract.
Your additional behavior configuration settings will be used to modify particular runtime properties when the runtime is constructed.
You can add your behaviors to the WCF configuration in an external configuration file or programmatically by using the classes provided by the client and service. For example, the service provides the DispatchRuntime and DispatchOperation classes, and the client provides the ClientRuntime and ClientOperation classes.
Not all behaviors are used by the runtime at the same time, so you can define your custom behavior to operate at various scope levels:
·         Service-level behaviors enable you to modify the entire runtime for each service.
·         Operation-level behaviors enable you to modify the runtime at operation level. For example, Operation A uses transactions and therefore requires the TransactionScopeRequired and TransactionAutoComplete behavior.
·         Endpoint-level behaviors enable you to modify the service and client for a particular endpoint.


Service Behaviors

You can define service-level behavior to control elements such as concurrency, transaction, and debugging for a particular service.
The following code example shows a custom service-level behavior configuration in an external configuration file that enables debugging and controls the publishing of metadata.
[WCF behavior configuration]
<services>
   <service name="ConnectedWCF.BankService"
      behaviorConfiguration="metadataAndDebugEnabled">
      ...
   </service>
</services>
<behaviors>
   <serviceBehaviors>
      <behavior name="metadataAndDebugEnabled">
         <serviceDebug includeExceptionDetailInFaults="true" />
         <serviceMetadata httpGetEnabled="true" httpGetUrl="" />
      </behavior>
   </serviceBehaviors>
</behaviors>
The following code examples show a custom service-level behavior configuration that is defined programmatically by using the ServiceBehavior attribute.
[Visual Basic]
<ServiceBehavior(InstanceContextMode := InstanceContextMode.PerCall)> _
Public Class BankService
   Implements IBank
   ' ...
End Class

[Visual C#]
[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerCall)]
public class BankService : IBank
{
   // ...
}

Custom Behavior Configuration

Default WCF behavior configurations deliver functionality that most applications require. There will be times when you have specialist requirements that the default behavior configuration will not satisfy.
WCF is designed to be extensible and enables you to address your additional requirements by using custom behaviors. For example, you can use message inspectors to modify messages before and after they are sent. Custom behaviors are beyond the scope of this course; for further information, see the additional resources.

Additional Reading

For more information about:


Operation Behaviors

You can also define behaviors for each operation in your service implementation. The behavior comes into force when the particular operation is invoked.
Behaviors at operation level can control aspects such as transactions, security, and instance management.
To define a behavior at operation level, you can use the OperationBehavior attribute. The following code illustrates this.
[Visual Basic]
<OperationBehavior(TransactionAutoComplete := True, _ 
   TransactionScopeRequired := True)> _
<TransactionFlow(TransactionFlowOption.Mandatory)> _
Public Function Transfer(ByVal sourceAccount As String, _
   ByVal amount As Decimal) As String
   '...
End Function

[Visual C#]
[OperationBehavior(TransactionAutoComplete = true,
                   TransactionScopeRequired = true)]
[TransactionFlow(TransactionFlowOption.Mandatory)]
public string Transfer(string sourceAccount,
                       targetAccount,
                       decimal amount)
{
  ...
}
Some aspects of execution that are controlled by behaviors must not be set on classes programmatically by the development team. Instead, they should be defined by the deployment team in external configuration files.


Endpoint Behaviors

You can also define behaviors for each endpoint that is exposed by your service. The behavior comes into force when a call to the particular endpoint is made.
Behaviors at endpoint level can control aspects of security and transport.
To define a behavior at endpoint level, you can use the endpointBehaviors element and the behaviorConfiguration attribute in your WCF configuration. The following code example shows how to define a behavior configuration called bankServiceCredentialBehavior for a basicHttpBinding endpoint.
[Endpoint behavior example]
<system.serviceModel>
   <behaviors>
      <endpointBehaviors>
         <behavior name="bankServiceCredentialBehavior">
            <!– Configuration elements go here. -->
         </behavior>
      </endpointBehaviors>
   </behaviors>
   <services>
      <service name="BankService" >
         <endpoint address="http://localhost:8080/BankService"
            contract="IBankService"
            binding="basicHttpBinding"
            bindingConfiguration="myBasicHttpBindingConfig"
            behaviorConfiguration="bankServiceCredentialBehavior"/>
      </service>
   </services>
</system.serviceModel>


Demonstration: Adding Metadata Exchange to a WCF Service by Using a Behavior


Lesson 3:
Interoperating with Non-WCF Web Services
When you develop WCF solutions, there will be situations where you want to utilize functionality that already exists in a legacy service. WCF provides the necessary components to enable you to interoperate with existing services with minimal effort.
This lesson discusses interoperating with old and new services and how to create your own custom bindings.

Overview of WCF Web Service Interoperability

When you start to develop your services, there may be times when you want to integrate your WCF service with services that are not based on WCF or the Windows operating system.
WCF enables you to interoperate with the following types of non-WCF services:
·         Legacy Web services. These include services that are based on protocol suites that preceded the WS-* standardization. They include ASP.NET Web services and older forms of various non-Microsoft technologies and products.
·         Newer services. These include services that are based on some combination of the WS-* protocol suite.
·          Plain old XML (POX) services. These include simple services that use raw XML over HTTP instead of SOAP messages.

Additional Reading

For more information about Web service protocols, see "Web Services Protocols Interoperability Guide" on the MSDN Web site.


Interoperability with Older Web Services

By using WCF, you can interoperate with legacy Web services. To ensure that your WCF solution is compatible with a legacy service such as an ASP.NET .ASMX service, you must configure the WCF client, the WCF service, and the legacy Web service in a particular way. The following list shows some of the configuration aspects that you must adhere to and some that you must avoid:
·         WCF client. Only use technologies that conform to Web Services Interoperability (WS-I) Basic Profile 1.1. For example, use a basicHttpBinding binding to ensure compatibility with the legacy ASP.NET Web service.
·         WCF service. Only use technologies that conform to WS-I Basic Profile 1.1, and also expose an HTTP/Get metadata endpoint.
·         ASP.NET Web service. Use default ASP.NET Web service settings. For example, do not use the authentication options provided in Internet Information Services (IIS). Also do not use custom serialization; for example, do not add additional XML serialization attributes to control the serialization of the legacy class.

Additional Reading

For more information about interoperating with an ASP.NET Web service, see "Interoperability with ASP.NET Web Services" on the MSDN Web site.


Demonstration: Consuming an ASP.NET Web Service


Web Service Standards Supported by WCF

WCF provides a set of Web services (WS)–based bindings. These bindings enable you to develop a WCF service that interoperates with clients and services that were implemented in newer, WS technologies.
You can take advantage of the following standards when you use the WS-based bindings:
·         Application-level interoperability. Web Services Description Language (WSDL) 1.1 and XML Schema Definition (XSD) 1.0 generated from contracts as metadata.
·         Transport-level interoperability. HTTP 1.1, and HTTP bindings for SOAP 1.1 and SOAP 1.2.
·         WS-Addressing 1.0.
·         Various Web services security (WSS) profiles.
·         WS-SecurityPolicy, WS-Trust, and WS-SecureConversation.
·         WS-Coordination and WS-AtomicTransaction.
·         WS-MetadataExchange, WS-Transfer, and WS-Policy.
When older clients and services interoperate with newer clients and services, you may have to consider the binding security mode, the binding transaction flow, and the type of message encoding.

Additional Reading

For more information about Web service standards, see "Web Services Specifications" on the MSDN Web site.

Example: Security Interoperability

To make interoperation simpler, WCF supports the WS-I standards and provides three bindings that are configured for interoperation:
·         BasicHttpBinding
·         WsHttpBinding
·         WsDualHttpBinding
You can use the binding element to specify additional security configuration for your binding.

Additional Reading

For more information about the protocols that are supported by the system-provided interoperability bindings, see "Web Services Protocols Supported by System-Provided Interoperability Bindings" on the MSDN Web site.


Creating a Custom Binding

When interoperating with other services, you may find that the default WCF bindings do not meet your requirements. WCF enables you to create your own custom binding to provide the functionality that you require in either of the following ways:
·         Create an instance of the CustomBinding class and define your binding elements such as binding, protocol, and transport elements.
·         Derive your own custom-binding class from an existing binding class such as wsHttpBinding, and then override the CreateBindingElements method.
Both methods result in a BindingElement collection, which is an ordered list of BindingElements. The WCF runtime uses each BindingElement to create the appropriate channel on the channel stack.
By default, WCF comes with the following BindingElements:
·         Transport. For example, HttpTransportBindingElement.
·         Security. For example, SslStreamSecurityBindingElement.
·         Message encoding. For example, MtomMessageEncodingBindingElement.
When you define the contents of your binding, it is important that you add the binding elements from top to bottom:
·         Start at the highest level such as Transaction Flow.
·         End with Transport (mandatory).
·         All of the binding elements except transport and message encoding are optional.
The following code examples show how to define the contents of a binding.
[Visual Basic]
Dim rel As New ReliableSessionBindingElement()

Dim trans As New HttpTransportBindingElement()

trans.AuthenticationScheme = AuthenticationSchemes.Anonymous

trans.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard

Dim elements As BindingElement() = New BindingElement(1) {}
elements(0) = rel
elements(1) = trans

Dim binding As New CustomBinding(elements)

[Visual C#]
ReliableSessionBindingElement rel =
   new ReliableSessionBindingElement();

HttpTransportBindingElement trans =
   new HttpTransportBindingElement();

trans.AuthenticationScheme = AuthenticationSchemes.Anonymous;

trans.HostNameComparisonMode =
   HostNameComparisonMode.StrongWildcard;

BindingElement[] elements = new BindingElement[2];
elements[0] = rel;
elements[1] = trans;

CustomBinding binding = new CustomBinding(elements);

Additional Reading

For more information about creating a custom binding, see "Creating User-Defined Bindings" on the MSDN Web site.


Lab: Changing Service Endpoints and Behaviors

Scenario

You are a developer on the Contoso, Ltd Clinic Management product team. Your manager has asked you to expose the Appointment service to both Internet and intranet clients and to remove the metadata endpoint. You must also experiment with how to expose a metadata endpoint and configure the Patient Letter service to interoperate with an ASP.NET legacy Web service.
In this exercise, you will configure both a wsHttpBinding and a netTcpBinding endpoint for the Appointment service. You will then manually generate a service proxy class by using the Svcutil.exe tool. Finally you will then add the necessary WCF configuration to the ClinicAdminClient and FPAdminClient projects.

Exercise 1: Exposing Services by Using Different Bindings

The main tasks for this exercise are as follows:
1.    Start the 6461A-LON-DEV-03 virtual machine and log on as Student.
2.    Open the existing ConnectedWCF solution.
3.    Add a netTcpBinding endpoint and a wsHttpBinding endpoint to the Appointment service.
4.    Generate a service proxy by using Svcutil.exe.
5.    Add the proxy to the FPAdminClient project and configure a wsHttpBinding binding.
6.    Add the proxy to the ClinicAdminClient project and configure a netTcpBinding binding.
7.    Set the ConnectedWCF solution startup projects.
8.    Build and run the solution.

Task 1: Start the 6461A-LON-DEV-03 virtual machine and log on as Student

1.    Open the Virtual Server Remote Control Client, and then double-click 6461A-LON-DEV-03.
2.    Log on to 6461A-LON-DEV-03 as Student by using the password Pa$$w0rd.

Task 2: Open the existing ConnectedWCF solution

1.    Open Microsoft® Visual Studio® 2008 development system as an ADMINISTRATOR.
2.    Open the existing ConnectedWCF solution. If you are using Microsoft Visual Basic® development system, browse to the E:\Labfiles\Starter\VB\Ex1\ConnectedWCF folder, and then double-click the ConnectedWCF.sln file. If you are using Microsoft Visual C#® development tool, browse to the E:\Labfiles\Starter\CS\Ex1\ConnectedWCF folder, and then double-click the ConnectedWCF.sln file.

Task 3: Add a netTcpBinding endpoint and a wsHttpBinding endpoint to the Appointment service

1.    In the Microsoft Service Configuration Editor window, open the AppointmentServiceSelfHost project’s App.config file.
2.    In the Microsoft Service Configuration Editor window, define a service endpoint with the following information:
    • Name: APService_TCP
    • Address: IntranetAppointmentService
    • Binding: netTcpBinding
    • Contract: com.contoso.AppointmentService.AppointmentServiceContract
3.    Define a second service endpoint with the following information:
    • Name: APService_wsHTTP
    • Address: InternetAppointmentService
    • Binding: wsHttpBinding
    • Contract: com.contoso.AppointmentService.AppointmentServiceContract
4.    Add the following base addresses to the com.contoso.AppointmentService.AppointmentServiceImplementation service:
    • http://localhost:8002/Contoso
    • net.tcp://localhost/Contoso
5.    Save your changes, and then close the Microsoft Service Configuration Editor window.
6.    Build the AppointmentServiceSelfHost project.

Task 4: Generate a service proxy by using Svcutil.exe

1.    In Windows Explorer, browse to the E:\Labfiles\Starter\Proxy folder.
2.    In Notepad, open the GenerateVbProxy.cmd file (for Visual Basic) or the GenerateCsProxy.cmd file (for Visual C#).

The GenerateVbProxy.cmd and GenerateCsProxy.cmd files contain a Svcutil.exe command to generate the metadata and proxy class for the Appointment service.
3.    If you are using Visual Basic, run the GenerateVbProxy.cmd file as an ADMINISTRATOR.

If you are using Visual C#, run the GenerateCsProxy.cmd file as an ADMINISTRATOR.

Task 5: Add the proxy to the FPAdminClient project and configure a wsHttpBinding binding

1.    Switch to Visual Studio 2008.
2.    Add the existing contoso.com.services.AppointmentService class to the FPAdminClient project. You can find the contoso.com.services.AppointmentService class in the E:\Labfiles\Starter\Proxy folder.
3.    If you are using Visual Basic, in the Microsoft Service Configuration Editor window, open the FPAdminClient project’s app.config file.

If you are using Visual C#, in the Microsoft Service Configuration Editor window, open the FPAdminClient project’s App.config file.
4.    In the Microsoft Service Configuration Editor window, define a new client endpoint with the following information:
    • Name: APService_wsHTTP
    • Address: http://localhost:8002/Contoso/InternetAppointmentService
    • Binding: wsHttpBinding
    • Contract: AppointmentServiceContract
5.    Save your changes, and then close the Microsoft Service Configuration Editor window.
6.    Build the FPAdminClient project.

Task 6: Add the proxy to the ClinicAdminClient project and configure a netTcpBinding binding

1.       Add the existing contoso.com.services.AppointmentService class to the ClinicAdminClient project. You can find the contoso.com.services.AppointmentService class in the E:\Labfiles\Starter\Proxy folder.
2.       If you are using Visual Basic, in the Microsoft Service Configuration Editor window, open the ClinicAdminClient project’s app.config file.

If you are using Visual C#, in the Microsoft Service Configuration Editor window, open the ClinicAdminClient project’s App.config file.
3.    In the Microsoft Service Configuration Editor window, define a new client endpoint with the following information:
    • Name: APService_TCP
    • Address: net.tcp://localhost/Contoso/IntranetAppointmentService
    • Binding: netTcpBinding
    • Contract: AppointmentServiceContract
4.    Save your changes, and then close the Microsoft Service Configuration Editor window.
5.    Build the ClinicAdminClient project.

Task 7: Set the ConnectedWCF solution startup projects

1.    In Solution Explorer, right-click the ConnectedWCF solution, and then click Set Startup Projects.
2.    Configure the ConnectedWCF solution so that the AppointmentServiceSelfHost, ClinicAdminClient, and FPAdminClient projects start when you start debugging.

Task 8: Build and run the solution

1.    Build the ConnectedWCF solution.
2.    Run the ConnectedWCF solution with debugging.
3.    Wait for the console window to display the message Appointment service running.
4.    On the FP Admin Client form, on the Create Appointment tab, click Find Slots.

Ensure that the Slots box is populated with a list of available appointment times.
5.    On the Clinic Administration Client form, on the Create Appointment tab, click Find Slots.

Ensure that the Slots box is populated with a list of available appointment times.
6.    Stop debugging.
Results: After this exercise, you should have exposed the Appointment service over a netTcpBinding and wsHttpBinding endpoint.

Exercise 1: Answer Key (detailed steps)


Exercise 2: Adding Metadata Exchange to a Service

In this exercise, you will add IMetadataExchange endpoints to the Appointment service to expose metadata over both TCP and HTTP. You will then use the Add Service Reference tool in Visual Studio 2008 to generate a proxy object from the metadata.
The main tasks for this exercise are as follows:
1.    Add a mexHttpBinding endpoint and a mexTcpBinding endpoint to the Appointment service.
2.    Set the ConnectedWCF solution startup projects.
3.    Add a service reference to the FPAdminClient project.
4.    Add a service reference to the ClinicAdminClient project.
5.    Set the ConnectedWCF solution startup projects.
6.    Build and run the solution.

Task 1: Add a mexHttpBinding endpoint and a mexTcpBinding endpoint to the Appointment service

1.    Open the existing ConnectedWCF solution. If you are using Visual Basic, browse to the E:\Labfiles\Starter\VB\Ex2\ConnectedWCF folder, and then double-click the ConnectedWCF.sln file. If you are using Visual C#, browse to the E:\Labfiles\Starter\CS\Ex2\ConnectedWCF folder, and then double-click the ConnectedWCF.sln file.
2.    In the Microsoft Service Configuration Editor window, open the AppointmentServiceSelfHost project’s App.config file.
3.    In the Microsoft Service Configuration Editor window, define a new service behavior called AppointmentServiceBehavior.
4.    Add a serviceMetadata element to the AppointmentServiceBehavior configuration that exposes metadata over HTTP.
5.    Add the AppointmentServiceBehavior configuration to the com.contoso.AppointmentService.AppointmentServiceImplementation service.
6.    In the Service Endpoint pane, define a service endpoint for the com.contoso.AppointmentService.AppointmentServiceImplementation service with the following information:
    • Name: APService_mexHttp
    • Binding: mexHttpBinding
    • Contract: IMetadataExchange
7.    Define a second service endpoint with the following information:
    • Name: APService_mexTcp
    • Binding: mexTcpBinding
    • Contract: IMetadataExchange
8.    Save your changes, and then close the Microsoft Service Configuration Editor window.
9.    Build the AppointmentServiceSelfHost project.

Task 2: Set the ConnectedWCF solution startup projects

1.    In Solution Explorer, right-click the ConnectedWCF solution, and then click Set Startup Projects.
2.    Configure the ConnectedWCF solution so that only the AppointmentServiceSelfHost project starts when you run the solution.
3.    Run the AppointmentServiceSelfHost project without debugging.

Leave the AppointmentServiceSelfHost console running.

Task 3: Add a service reference to the FPAdminClient project

1.    In the FPAdminClient project, if you are using Visual Basic, delete the contoso.com.services.AppointmentService.vb class file. If you are using Visual C#, delete the contoso.com.services.AppointmentService.cs class file.
2.    If you are using Visual Basic, in the Code Editor window, open the FPAdminClient project’s app.config file.

If you are using Visual C#, in the Code Editor window, open the FPAdminClient project’s App.config file.
3.    In the Code Editor window, remove the system.serviceModel element.
4.    Save and close the configuration file.
5.    Add a new service reference to the FPAdminClient project with the following information:
    • Address: http://localhost:8002/Contoso
    • Namespace: AppointmentServiceReference
6.    In the Code Editor window, open the FPAdminForm class.
7.    In the Code Editor window for the FPAdminForm class, add code to bring the FPAdminClient.AppointmentServiceReference namespace into scope.
8.    Locate the GetAppointmentServiceProxy method, and then pass the string APService_wsHTTP in the AppointmentServiceContractClient constructor.
9.    Build the FPAdminClient project.

Task 4: Add a service reference to the ClinicAdminClient project

1.    In the ClinicAdminClient project, if you are using Visual Basic, delete the contoso.com.services.AppointmentService.vb class file. If you are using Visual C#, delete the contoso.com.services.AppointmentService.cs class file.
2.    If you are using Visual Basic, in the Code Editor window, open the ClinicAdminClient project’s app.config file.

If you are using Visual C#, in the Code Editor window, open the ClinicAdminClient project’s App.config file.
3.    In the Code Editor window, remove the system.serviceModel element.
4.    Save and close the configuration file.
5.    Add a new service reference to the ClinicAdminClient project with the following information:
    • Address: net.tcp://localhost/Contoso
    • Namespace: AppointmentServiceReference
6.    In the Code Editor window, open the ClinicAdminForm class.
7.    In the Code Editor window for the ClinicAdminForm class, add code to bring the ClinicAdminClient.AppointmentServiceReference namespace into scope.
8.    Locate the GetAppointmentServiceProxy method, and then pass the string APService_TCP in the AppointmentServiceContractClient constructor.
9.    Build the ClinicAdminClient project.

Task 5: Set the ConnectedWCF solution startup projects

1.    In Solution Explorer, right-click the ConnectedWCF solution, and then click Set Startup Projects.
2.    Configure the ConnectedWCF solution so that the AppointmentServiceSelfHost, ClinicAdminClient, and FPAdminClient projects start when you run the solution.

Task 6: Build and run the solution

1.    Switch to the AppointmentServiceSelfHost console, and then close the console window.
2.    Build the ConnectedWCF solution.
3.    Run the ConnectedWCF solution with debugging.
4.    Wait for the console window to display the message Appointment service running.
5.    On the FP Admin Client form, on the Create Appointment tab, click Find Slots.

Ensure that the Slots box is populated with a list of available appointment times.
6.    On the Clinic Administration Client form, on the Create Appointment tab, click Find Slots.

Ensure that the Slots box is populated with a list of available appointment times.
7.    Stop debugging.
Results: After this exercise, you should have exposed an IMetadataExchange endpoint for netTcpBinding and wsHttpBinding and then used the Add Service Reference function in Visual Studio to generate a proxy object.

Exercise 2: Answer Key (detailed steps)

Exercise 3: Creating WCF Clients and Services That Interoperate with Non-WCF Web Services

In this exercise, you will add the necessary code and WCF configuration to the existing Patient Letter WCF service to interoperate with a legacy Web service.
The following diagram illustrates the components in the Patient Letter WCF service.
The main tasks for this exercise are as follows:
1.    Host a legacy Web service in Internet Information Services (IIS).
2.    Create a proxy for the PatientLetterService project.
3.    Add the proxy to the PatientLetterService project.
4.    Configure a basicHttpBinding for the PatientLetterService project.
5.    Add code to call the methods in the PatientLetterService project.
6.    Build and run the solution.

Task 1: Host a legacy Web service in IIS

1.    Open the Internet Information Services (IIS) Manager window.
2.    In the Internet Information Services (IIS) Manager window, add a new application with the following information:
    • Alias: PatientInformationService
    • Physical path: E:\Labfiles\Starter\LegacyWebServices\PatientInformationService
3.    Close the Internet Information Services (IIS) Manager window.
4.    Open Windows Internet Explorer®, and then go to http://localhost/PatientInformationService/Service.asmx.

If you have hosted the Web service correctly, you will see the default PatientInformationService page.
5.    Click Service Description to view the Web Services Description Language (WSDL) for the legacy Web service.

Examine the contents of the WSDL document, paying particular attention to the GetPatientDetails method.
6.    Close Internet Explorer.

Task 2: Create a proxy for the PatientLetterService project

1.    In Windows Explorer, browse to the E:\Labfiles\Starter\LegacyWebServices folder.
2.    If you are using Visual Basic, open the GenerateLegacyVbProxy.cmd file in Notepad.

If you are using Visual C#, open the nerateLegacyCsProxy.cmd file in Notepad.

The GenerateLegacyVbProxy.cmd and GenerateLegacyCsProxy.cmd files contain Svcutil.exe commands to generate the proxy class for the PatientLetterService project that uses the WSDL that you have just seen.
3.    If you are using Visual Basic, run the GenerateLegacyVbProxy.cmd file as an ADMINISTRATOR.

If you are using Visual C#, run the GenerateLegacyCsProxy.cmd file as an ADMINISTRATOR.
4.    In the Command Prompt window, ensure that the command executed successfully, and then press ENTER.

Task 3: Add the proxy to the PatientLetterService project

1.    Open the existing ConnectedWCF solution. If you are using Visual Basic, browse to the E:\Labfiles\Starter\VB\Ex3\ConnectedWCF folder, and then double-click the ConnectedWCF.sln file. If you are using Visual C#, browse to the E:\Labfiles\Starter\CS\Ex3\ConnectedWCF folder, and then double-click the ConnectedWCF.sln file.
2.    Add the LegacyPatientInformationServiceProxy class to the PatientLetterService project. You can find the LegacyPatientInformationServiceProxy class in the E:\Labfiles\Starter\LegacyWebServices folder.

Task 4: Configure a basicHttpBinding for the PatientLetterService project

1.    In the Microsoft Service Configuration Editor window, open the AppointmentServiceSelfHost project’s App.config file.
2.    Define a new client endpoint with the following information:
    • Name: PatientInformationServiceSoap
    • Address: http://localhost/PatientInformationService/Service.asmx
    • Binding: basicHttpBinding
    • Contract: PatientInformationServiceSoap
3.    Save your changes, and then close the Microsoft Service Configuration Editor.

Task 5: Add code to call the methods in the tientLetterService project

1.    In the PatientLetterService project, in the Code Editor window, open the PatientLetterServiceImplementation class.
2.    In the Code Editor window, locate the TODO 1 comment, and add code to bring the contoso.com.ClinicManagementSystem._2004._07 namespace into scope.
3.    In the PopulateTemplate method, locate the TODO 2 comment, and add code to do the following:
    • Create a new instance of the PatientInformationServiceSoapClient class called patientInformationService. Pass the string PatientInformationServiceSoap to the constructor.
    • Create a new instance of the PatientDetails class called patientDetails, and then initialize it to the return value of the GetPatientDetails method in the patientInformationService object. Pass the patientId variable as a parameter in the method call.

Task 6: Build and run the solution

1.    Build the ConnectedWCF solution.
2.    Run the ConnectedWCF solution with debugging.
3.    Wait for the console window to display the message Appointment service and patient letter service running. Press <ENTER> to quit.
4.    On the Clinic Administration Client form, on the Create Appointment tab, click Find Slots.
5.    In the Patient box, type NH991199Z and then click Create.
6.    In the Appointment Created dialog box, click OK.
7.    Switch to the AppointmentServiceSelfHost console window, and verify that the Entered SendLetter and Exited SendLetter messages are displayed.
8.    Open Windows Explorer, and browse to the E:\Labfiles\Starter\Letters folder.
9.    In the Letters folder, open the NH991199Z.txt file in Notepad.

The file contains a basic letter that provides details of the appointment.
Results: After this exercise, you should have added the necessary code and WCF configuration to the Patient Letter WCF service to interoperate with a legacy .asmx Web service.

Exercise 3: Answer Key (detailed steps)


Module 4
Debugging and Diagnostics
Windows® Communication Foundation (WCF) provides the necessary functionality for you to monitor and diagnose faults with your WCF solutions.
This module differentiates between message logging and activity tracing. It also explains how to implement them in your WCF solutions.
·         Lesson 1: Logging Messages
·         Lesson 2: Activity Tracing
·         Lesson 1:
·         Logging Messages
·        
·         WCF provides functionality to enable you to log the communications between your services and client applications for purposes such as debugging and troubleshooting.
·         This lesson explains how to configure message logging and how you can analyze the contents of a log file.

Tracking What Is Happening in a WCF Application

WCF provides functionality to help you monitor and diagnose your WCF solution.
This module focuses on message logging and activity tracing, but there are other diagnostic tools that you can use to gather Windows Management Instrumentation (WMI) metrics such as the number of operations per second and the number of errors per second. For more information about other diagnostic tools, see the additional resources.

Message Logging

Message logging captures the messages sent between your WCF service and client applications; typically, it writes them to a log file for offline inspection.

Trace Activities

Tracing provides an alternative to the debugger and enables you to monitor the behavior of your WCF solution and diagnose any exceptions. You can configure your WCF service to flush the trace information to a log file for inspection, where you can correlate the results to provide an end-to-end picture of your service's behavior.
For both message logging and trace activities, you are not limited to just writing your output to a log file. You can use any of the following trace listener classes:
·         EventLogTraceListener
·         TextWriterTraceListener
·         XmlWriterTraceListener

Additional Reading

For more information about the diagnostic functionality in WCF, see "Administration and Diagnostics" on the MSDN Web site.


Message Logging in WCF

By using the message logging functionality in WCF, you can log incoming and outgoing messages at both the client and the service. You can log messages at the transport and service level. Service level is just before WCF passes the message to the channel stack (for outbound messages) or just after it retrieves the message from the channel stack (for inbound messages). Transport level is at the bottom of the channel stack just before the message is passed to the transport mechanism (for outbound messages) or just after the message is retrieved from the transport mechanism (for inbound messages). This distinction can be important to determine where problems may occur.
The way that you configure your message logger will determine if each message contains just header information or header and body information.
Typically a message will contain the following:
·         The time when the message was sent.
·         The sender of the message.
·         The address to which the message was sent.
·         The operation that the message relates to and any parameters or return values that are defined on that operation.
WCF uses the .NET Framework 2.0 trace source and trace listener mechanisms to expose the flow of messages between client and service. WCF provides a message logging trace source that emits the message contents. You can then connect this to a trace listener that saves the messages for analysis by using the Microsoft® Service Trace Viewer tool.
When you log messages, it is important to consider the nature of the information you log whether it is sensitive personal data or application data. Some data may be covered by legislation such as Sarbanes-Oxley or the UK Data Protection Act. Regardless of the information, you must keep log files in a secure environment where they are inaccessible from unauthorized remote and local users.
If you use message level security, the message content may be encrypted when it is logged.

Additional Reading:

For more information about message logging, see "Message Logging" on the MSDN Web site.


Adding a Trace Listener to Log Messages

To enable your WCF service or WCF client to log messages, you must add the necessary configuration elements to your application's WCF configuration.
To enable message logging in your WCF solution, perform the following steps:
1.    Add a source element for the System.ServiceModel.MessageLogging trace source.
2.    Add a trace listener for the message logging trace source. This can be one of several different types of trace listener:
·         EventLogTraceListener
·         TextWriterTraceListener
·         XmlWriterTraceListener
3.    Set the location where you want the trace listener to log the messages. Typically, you do this by setting the initializeData property.
4.    Set the autoflush property to true. The trace listener will then push the messages to the log after every write operation instead of buffering them in memory.
The following WCF configuration example shows how you can configure message logging in its simplest form.
[Trace listener example]
...
<system.diagnostics>
   <sources>
      <source name="System.ServiceModel.MessageLogging">
         <listeners>
            <add name="messages"
               type="System.Diagnostics.XmlWriterTraceListener"
               initializeData="c:\logs\messages.svclog" />
         </listeners>
      </source>
   </sources>
   <trace autoflush="true" />
</system.diagnostics>
...

Additional Reading

For more information about how to configure message logging in your WCF solution, see "Configuring Message Logging" on the MSDN Web site.

Controlling Message Logging

When you add a trace listener for the System.ServiceModel.MessageLogging trace source, the default values used by the message logging trace source provide basic functionality that may not meet you requirements; for example, they may log only the message header, when in fact you also want the message body. If this is the case, you can add additional configuration to control how the message logging trace source functions and the information that it logs. For example, you can configure the message logging trace source to log the entire message instead of logging only the message header.
To control aspects of the message logging trace source, you add a messageLogging element to your WCF configuration file under the diagnostics subelement of the system.ServiceModel element. The following table lists the attributes for the messageLogging element.
Attribute
Description
logEntireMessage
Determines if the message logging trace source logs the message header and body or just the message header.
logMalformedMessages
Determines if the message logging trace source logs corrupt or incorrectly formatted messages.
logMessagesAtServiceLevel
Determines if the message logging trace source logs messages at the service level prior to encryption and transportation.
logMessagesAtTransportLevel
Determines if the message logging trace source logs messages at the transport level.
maxMessagesToLog
Determines the maximum number of messages that the message logging trace source will log.
maxSizeOfMessageToLog
Determines the maximum size in bytes of the message that the message logging trace source will log.
The following example shows the messageLogging element and its associated attributes.
 [Message logging example]
...
<system.serviceModel>
  <diagnostics>
    <messageLogging
         logEntireMessage="true"
         logMalformedMessages="false"
         logMessagesAtServiceLevel="true"
         logMessagesAtTransportLevel="false"
         maxMessagesToLog="3000"
         maxSizeOfMessageToLog="2000"/>
  </diagnostics>
</system.serviceModel>
...

Additional Reading:

For more information about how to control the message logging trace source, see "<messageLogging>" on the MSDN Web site.

Including Security Information in Message Logs

By default, the message logging trace source omits any known security information that may be present in the messages. Security information includes the following:
·         Keys
·         Personal Identifiable Information (PII) such as user names and passwords
You configure this capability by using a combination of application-level and machine-level configuration. The following examples show the necessary configuration elements at both the application level and the machine level.
[Application level configuration]
<system.diagnostics>
  <sources>
    <source name="System.ServiceModel.MessageLogging"
                 logKnownPii="true">
      <listeners>
        <add name="messages"
             type="System.Diagnostics.XmlWriterTraceListener"
             initializeData="c:\logs\messages.svclog" />
      </listeners>
    </source>
  </sources>
</system.diagnostics>

[Machine level configuration]
<configuration>
   <system.ServiceModel>
      <machineSettings enableLoggingKnownPii="true"/>
   </system.ServiceModel>
</configuration>

Additional Reading:

For more information about how to log sensitive information, see "Security Concerns for Message Logging" on the MSDN Web site.

Filtering Which Messages to Log

There may be times when you only want to log particular messages when you monitor or diagnose a fault with your WCF solution.
WCF provides message filtering functionality that causes the message logger to only log messages that match any of the filters. The filters support XPath, which enables you to define your own custom expressions to determine what messages are logged. If there are no filters, the message logging trace source logs all messages.
To configure message filtering, you must add a filters element to your WCF configuration. In the filters element, you can then add one or more filters and set their attributes such as the nodeQuota attribute, which limits the size of the XPath Document Object Model (DOM) examined when looking to match the filter criteria.
The following example shows how to enable message filtering.
[Filtering example]
<messageLogging
   logEntireMessage="true"
   logMalformedMessages="true"
   logMessagesAtServiceLevel="true"
   logMessagesAtTransportLevel="false"
   maxMessagesToLog=“3000">
   <filters>
      <add nodeQuota="10"
         xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
         /soap:Envelope/soap:Header
      </add>
   </filters>
</messageLogging>

Additional Reading

For more information about how to configure message filtering, see the "Message Filters section" in "Configuring Message Logging" on the MSDN Web site.

Viewing Messages

The log files produced by the trace listener mechanism would be difficult to analyze in their raw format. However, Microsoft provides the Service Trace Viewer tool, which enables you to open multiple log files to amalgamate individual service logs or client and server logs to get a complete picture of the overall communication process.

Additional Reading

For more information about the Service Trace Viewer tool, see "Viewing Message Logs" on the MSDN Web site.


Demonstration: Working With Logged Information


Lesson 2:
Activity Tracing
WCF provides functionality that enables you to monitor the activities that your services and clients perform when running.
This lesson explains how to configure such activity tracing and how to analyze the trace logs.

Enabling Activity Tracing

You can enable activity tracing in your WCF service or WCF client by performing the following steps:
1.    Add a source element for the System.ServiceModel trace source.
2.    Set the switchValue property to the trace level that you require. The switchLevel property instructs the trace source to log the following types of activities either individually or in combination (comma-separated):
o    Critical. Logs all failure activities, for example, if the system is out of memory.
o    Error. Logs all exceptions.
o    Warning. Logs all activities that can potentially generate an error or failure; for example, your service receives more requests than it can handle.
o    Information. Logs general information on all activities such as when channels are created.
o    Verbose. Logs debug-level trace activities with more detail than the information trace level.
o    ActivityTracing. Logs the flow of events between components.
o    All. Logs all activities regardless of their type.
3.    Add a trace listener of the desired type and set the location where you want the trace listener to log the trace activities. Typically, you do this by setting the initializeData property.
4.    Set the autoflush property to true. The trace listener will then push the traces to the log after every write operation instead of buffering them in memory.
The following example shows how you can enable activity tracing in a configuration file.
[Activity tracing example]
<system.diagnostics>
  <trace autoflush="true" />
  <sources>
    <source name="System.ServiceModel"
            switchValue="Information, ActivityTracing"
            propagateActivity="true">
      <listeners>
        <add name="traceActivity"
             type="System.Diagnostics.XmlWriterTraceListener"
             initializeData= "c:\logs\activity.svclog" />
      </listeners>
    </source>
  </sources>
</system.diagnostics>

Additional Reading

For more information about activity tracing, see:
·          "Configuring Tracing" on the MSDN Web site.
·         "Service Trace Viewer Tool (SvcTraceViewer.exe)" on the MSDN Web site.

Custom Activity Tracing

You can define your own application-specific or service-specific activities that you want to trace. To do this, you define a TraceSource in your code, and pass a name for the source. You can then use this source name in your WCF configuration file and add a trace listener to it.
As your code runs, you can notify your TraceSource of events and information that you want to make available to trace listeners. For example, the trace information can be a message that details the method, the parameters passed, and the return value. You can also create activity IDs to identify the operations that are associated with your trace information. Tools like the Service Trace Viewer can use these activity IDs to correlate related events.
The following example shows how you can enable custom activity tracing.
[Visual Basic]
Dim ts As New TraceSource("bankServiceTraceSource")

Dim oldActivityID As Guid = Trace.CorrelationManager.ActivityId
Dim newActivityID As Guid = Guid.NewGuid()
ts.TraceTransfer(0, "transfer", newActivityID)
Trace.CorrelationManager.ActivityId = newActivityID
ts.TraceEvent(TraceEventType.Start, 0, "Add request")

Dim msg As String = [String].Format("Tried to withdraw {0} from " _
   & "account {1}", amount, account)
ts.TraceInformation(msg)

ts.TraceTransfer(0, "transfer", oldActivityID)
ts.TraceEvent(TraceEventType.[Stop], 0, "Add request")
Trace.CorrelationManager.ActivityId = oldActivityID

[Visual C#]
TraceSource ts = new TraceSource("bankServiceTraceSource");

Guid oldActivityID = Trace.CorrelationManager.ActivityId;
Guid newActivityID = Guid.NewGuid();
ts.TraceTransfer(0, "transfer", newActivityID);
Trace.CorrelationManager.ActivityId = newActivityID; ts.TraceEvent(TraceEventType.Start, 0, "Add request");

string msg = String.Format("Tried to withdraw {0} from "
   + "account {1}", amount, account);
ts.TraceInformation(msg);

ts.TraceTransfer(0, "transfer", oldActivityID);
ts.TraceEvent(TraceEventType.Stop, 0, "Add request");
Trace.CorrelationManager.ActivityId = oldActivityID;

Additional Reading

For more information about custom tracing, see "Emitting User-Code Traces" on the MSDN Web site.


End-to-End Service Tracing

When you monitor activities in a distributed application, it can be difficult to correlate events on different machines such as the correct sequence in which activities occurred and which activity caused a subsequent one to occur.
WCF provides a solution with a built-in correlation mechanism, which you can enable by performing the following steps:
·         Enable activity tracing
·         Set the propagateActivity to true. This propagates the current activity ID across service boundaries and enables tools to associate client and service activities that share the same activity ID.
The following example shows how you can enable message correlation in a configuration file.
[Message correlation example]
<source name="System.ServiceModel"
        switchValue="Information, ActivityTracing"
        propagateActivity="true">
When you have enabled activity correlation in your client and service, you can run your solution to generate the log files. You can then open both the client and service log files in the Service Trace Viewer tool and analyze the end-to-end trace information.

Additional Reading

For more information about trace correlation, see "Activity Tracing and Propagation for End-To-End Trace Correlation" on the MSDN Web site.


Demonstration: Working with Activity Trace Information



Scenario

You are a developer on the Contoso, Ltd Clinic Management product team. You have been involved in the development of the Appointment service and your manager has now asked you to add additional configuration to the service to log messages sent to and from the clients and to monitor the activities that the clients and service perform.
In this exercise, you will configure the AppointmentService project, the PatientManagementService project, and the ClinicAdminClient project to log messages. You will then analyze these messages by using the Microsoft Service Trace Viewer tool.
The following diagrams illustrate the components in the two services that you will use in this lab.
Appointment Service
Patient Management Service

Exercise 1: Generating Logging Information for a Service

The main tasks for this exercise are as follows:
1.    Start the 6461A-LON-DEV-04 virtual machine and log on as Student.
2.    Open the existing WCFConnected solution.
3.    Enable message logging for the AppointmentService and the PatientManagementService.
4.    Enable message logging for the ClinicAdminClient.
5.    Build and run the solution.
6.    View the message logs.

Task 1: Start the 6461A-LON-DEV-04 virtual machine and log on as Student

1.    Open the Virtual Server Remote Control Client, and then double-click 6461A-LON-DEV-04.
2.    Log on to 6461A-LON-DEV-04 as Student by using the password Pa$$w0rd.

Task 2: Open the existing WCFConnected solution

1.    Open Microsoft Visual Studio® 2008 development system as an ADMINISTRATOR.
2.    Open the existing ConnectedWCF solution. If you are using Microsoft Visual Basic® development system, browse to the E:\Labfiles\Starter\VB\Ex1\ConnectedWCF folder, and then double-click the ConnectedWCF.sln file. If you are using Microsoft Visual C#® development tool, browse to the E:\Labfiles\Starter\CS\Ex1\ConnectedWCF folder, and then double-click the ConnectedWCF.sln file.

Task 3: Enable message logging for the AppointmentService and the PatientManagementService

1.    In the Microsoft Service Configuration Editor window, open the ServiceSelfHost project's configuration file.
2.    In the Microsoft Service Configuration Editor window, in the Diagnostics element, perform the following steps:
    • Enable the solution to automatically flush messages.
    • Enable message logging.
    • Click the ServiceModelMessageLoggingListener link to open the Listener Settings dialog box, and then change the log path to E:\Labfiles\Starter\Logs\service_messages.svclog.
3.    In the Diagnostics node, open the Message Logging instance, and then add configuration to log the entire message and log messages at service level.
4.    In the Source node, open the System.ServiceModel.MessageLogging instance, and then change the Trace level to information.
5.    Save your changes, and then close the Microsoft Service Configuration Editor window.

Task 4: Enable message logging for the ClinicAdminClient

1.    In the Microsoft Service Configuration Editor window, open the ClinicAdminClient project's configuration file.
2.    In the Microsoft Service Configuration Editor window, in the Diagnostics element, perform the following steps:
    • Enable the solution to automatically flush messages.
    • Enable message logging.
    • Open the Listener Settings dialog box, and then change the log path to E:\Labfiles\Starter\Logs\client_messages.svclog.
3.    In the Diagnostics node, open the Message Logging instance, and then add configuration to log the entire message and log messages at service level.
4.    In the Source node, open the System.ServiceModel.MessageLogging instance, and then change the Trace level to information.
5.    Save your changes, and then close the Microsoft Service Configuration Editor window.

Task 5: Build and run the solution

1.    Build the ConnectedWCF solution.
2.    Run the ConnectedWCF solution with debugging.
3.    Wait for the console window to display the message that starts with Service running.
4.    On the Clinic Admin Client form, on the Create Appointment tab, click Find Slots.

Ensure that the Slots box is populated with a list of available appointment times.
5.    Stop debugging.

Task 6: View the message logs

1.    On the Start menu, point to All Programs, point to Microsoft Windows SDK v6.0A, point to Tools, and then click Service Trace Viewer.
2.    In the Microsoft Service Trace Viewer, open both the client_messages.svclog and service_messages.svclog files.
3.    In the Activity pane, click the 000000000000 entry.
4.    In the Description column, click the first message, and then click the Message tab.

The first message is a client request message at the service level, which contains the parameters for the ListAvailableAppointmentTimes method call.

The second message is the equivalent transport-level message on the client, which is addressed to the http://localhost:8002/Contoso/AppointmentService endpoint.
5.    In the Description column, click the fifth message.

The fifth message is the service's response to the ListAvailableAppointmentTimes method call; it includes the available appointment times as the return value.

The sixth message is the equivalent response message at the transport level.
6.    Close the client_messages.svclog and service_messages.svclog files.
Results: After this exercise, you should have enabled message logging for the AppointmentService, PatientManagementService, and the ClinicAdminClient application.

Exercise 1: Answer Key (detailed steps)


Exercise 2: Enabling End-to-End Tracing for a Service

In this exercise, you will configure the AppointmentService, the PatientManagementService, and the ClinicAdminClient to log information on the various activities that they perform when the ConnectedWCF solution runs. You will then analyze the trace logs by using the Microsoft Service Trace Viewer tool.
The main tasks for this exercise are as follows:
1.    Open the existing WCFConnected solution.
2.    Enable tracing for the AppointmentService and the PatientManagementService.
3.    Enable tracing for the ClinicAdminClient.
4.    Build and run the solution.
5.    View the trace logs.

Task 1: Open the existing WCFConnected solution

·         Open the existing ConnectedWCF solution. If you are using Visual Basic, browse to the E:\Labfiles\Starter\VB\Ex2\ConnectedWCF folder, and then double-click the ConnectedWCF.sln file. If you are using Visual C#, browse to the E:\Labfiles\Starter\CS\Ex2\ConnectedWCF folder, and then double-click the ConnectedWCF.sln file.

Task 2: Enable tracing for the AppointmentService and the PatientManagementService

1.    In the Microsoft Service Configuration Editor window, open the ServiceSelfHost project's configuration file.
2.    In the Microsoft Service Configuration Editor window, in the Diagnostics element, perform the following steps:
o    Enable the solution to automatically flush messages.
o    Enable tracing.
o    Open the Listener Settings dialog box, and then change the log path to E:\Labfiles\Starter\Logs\service_tracelog.svclog.
                        In the Source node, open the System.ServiceModel instance, and then change the Trace level to information.
                        Save your changes, and then close the Microsoft Service Configuration Editor window.

Task 3: Enable tracing for the ClinicAdminClient

1.    In the Microsoft Service Configuration Editor window, open the ClinicAdminClient project's configuration file.
2.    In the Microsoft Service Configuration Editor window, in the Diagnostics element, perform the following steps:
o    Enable the solution to automatically flush messages.
o    Enable tracing.
o    Open the Listener Settings dialog box, and then change the log path to E:\Labfiles\Starter\Logs\client_tracelog.svclog.
                        In the Source node, open the System.ServiceModel instance, and then change the Trace level to information.
                        Save your changes, and then close the Microsoft Service Configuration Editor window.

Task 4: Build and run the solution

1.    Delete any existing trace log files in the E:\Labfiles\Starter\Logs folder
2.    Build the ConnectedWCF solution.
3.    Run the ConnectedWCF solution with debugging.
4.    Wait for the console window to display the message that starts with Service running.
5.    On the Clinic Admin Client form, on the Create Appointment tab, click Find Slots.

Ensure that the Slots box is populated with a list of available appointment times.
6.    In the Patient box, type NH991199Z and then click Create. Make a note of the appointment ID.
7.    In the Appointment Created dialog box, click OK.
8.    On the Cancel Appointment tab, in the Patient No box, type NH991199Z and then click Get Details.
9.    In the Appt ID box, type your appointment ID, and then click Delete.
10. In the Appointment Cancellation box, click OK.
11. Stop debugging.

Task 5: View the trace logs

1.    Switch to the Microsoft Service Trace Viewer.
2.    In the Microsoft Service Trace Viewer, open both the client_tracelog.svclog and service_tracelog.svclog files.

The activity pane contains a chronological list of activities associated with creating the AppointmentService, the PatientManagementService, and the ClinicAdminClient. The activity pane also contains a list of the methods invoked.
3.    In the Activity pane, click the Construct ServiceHost 'com.contoso.AppointmentService.AppointmentServiceImplementation' activity.

This activity represents the service host building an instance of the AppointmentService. The right pane contains the details of the activity such as the activity name, trace level, process name, and thread ID.

The next activity represents the similar process of building an instance of the PatientManagementService.
4.    In the Activity pane, click the Construct ChannelFactory. Contract types: 'ClinicAdminClient.AppointmentServiceReference.AppointmentServiceContract' activity.

This activity represents the building of the channel stack for the ClinicAdminClient.
5.    In the Activity pane, click the Execute 'com.contoso.AppointmentService.AppointmentServiceContract.ListAvailableAppointmentTimes' activity.

This activity represents the process of invoking the ListAvailableAppointmentTimes method.
6.    In the Activity pane, examine some of the other activities.
7.    In the Activity pane, click the 000000000000 activity.
8.    In the left pane, click the Graph tab.

The graph view enables you to view the correlation between the different activities.

The ServiceSelfHost column contains the activities associated with building the AppointmentService, the PatientManagementService instances, and starting listening for requests over the configured endpoints.

The ClinicAdminClient column contains activities associated with the following processes:
    1. Building the channel stack for the client to communicate with the AppointmentService.
    2. Opening the client for the AppointmentServiceContract.
    3. Calling the ListAvailableAppointmentTimes method in the AppointmentService.
    4. Opening the client for the AppointmentServiceContract.
    5. Calling the CreateAppointment method in the AppointmentService.
    6. Building the channel stack for the client to communicate with the PatientManagementService.
    7. Opening the client for the PatientManagementServiceContract.
    8. Calling the GetPatientDetails method in the PatientManagementService.
    9. Opening the client for the AppointmentServiceContract.
    10. Calling the CancelAppointment method in the AppointmentService.
9.    On the File menu, click Close All
Results: After this exercise, you should have enabled tracing for the AppointmentService, the PatientManagementService, and the ClinicAdminClient application.

Exercise 2: Answer Key (detailed steps)

1 comment: