Chapter 19. Manageability

<feature><title>In This Chapter</title> </feature>

Introduction

For any software to be an asset that the system administrators can manage effectively—can confirm that it is in a healthy state and take effective remedial action if it is not—the software must provide at least four layers of management facilities.

The first layer is instrumentation, which consists of data points and control points. Data points provide information about the state of the software, whereas control points allow one to make adjustments to it to apply remedies for problems divined from the data points.

The second layer consists of tools for reading from the data points and for manipulating the control points. The third layer provides a management model. Given sufficient instrumentation and good tools for using it, a management model provides the system administrators with knowledge of how to use the tools to maintain the health of the system. That is, how to determine whether the system is in a healthy state or an unhealthy one, what actions to take to maintain the health of the system, and how to remedy its maladies.

The fourth layer of management facilities an application should provide consists of a control panel integrated into the administrator’s preferred integrated management environment—an environment such as IBM’s Tivoli Software, Hewlett-Packard’s HP OpenView, or Microsoft Operations Manager (MOM). Having such a control panel integrated into a familiar integrated management environment not only serves to automate the processes described in the management model, but also to translate the elements of the management model that are specific to an application into the standard terms of the integrated management environment.

There is a comprehensive set of instrumentation and tooling for the Windows Communication Foundation. The chapter describes those facilities in detail, and goes on to show how developers can use those instruments and tools as the foundation of management models specific to their own applications, as well as how to incorporate those management models into a control panel within an integrated management environment.

Instrumentation and Tools

The Windows Communication Foundation provides the following instrumentation:

  • A configuration system for deployment and for post-deployment control and tuning

  • Security event logging

  • Message logging

  • The tracing of internal activities, and of sequences of activities across nodes

  • Performance counters for key operational, security, reliability, and transaction statistics for services, for the various endpoints of a service, for the individual operations of an endpoint

  • A Windows Management Instrumentation (WMI) provider for querying and modifying the properties of running systems

Familiar tools already exist for accessing and using some of this instrumentation. For example, the Windows operating system provides a Performance Monitor by which the new performance counters of the Windows Communication Foundation can be examined. In a few cases, new tools had to be provided. Table 19.1 identifies the tools, new and familiar, available for monitoring and controlling the Windows Communication Foundation through its instrumentation.

Table 19.1. Management Tools

Instrumentation

Tools

Configuration System

New Windows Communication Foundation Service Configuration Editor

Security Event Logging

Familiar Windows Event Viewer

Message Logging

New Windows Communication Foundation Service Trace Viewer

Activity Tracing

New Windows Communication Foundation Service Trace Viewer

Performance Counters

Familiar Windows Performance Monitor

WMI Provider

Many familiar tools including WMI CIM Studio, ScriptOMatic, and Windows PowerShell

To prepare for the introduction to the Windows Communication Foundation’s instrumentation and tooling provided in this chapter, follow these steps:

  1. Copy the code associated with this chapter downloaded from http://www.cryptmaker.com/WindowsCommunicationFoundationUnleashed to the folder C:WCFHandsOn. The code is all in a folder called Management, which has three subfolders, one called CompletedSolution, another called StartingPoint, and a third one called Logs.

  2. Open the solution C:WCFHandsOnManagementStartingPointTradingService.sln.

The solution is for building a derivatives trading system. Derivatives were introduced in Chapter 2, “The Fundamentals,” and the derivatives trading system manages the risk in buying them.

The TradingService project in the solution builds a trading service for pricing and purchasing derivatives. The TradingServiceHost project constructs the host for that service.

The TradeRecordingService project builds a trade-recording service that the trading service uses to execute the purchase of derivatives. The TradeRecordingServiceHost project constructs the host of the recording service.

The client project in the solution is for building a risk management system. That risk management system uses the trading service to price and execute two derivatives purchases at a time: a primary purchase, and another one that is intended as a hedge against the possibility of losses on the first purchase. Depending on the difference in the prices of the primary and hedge purchases, the risk management system will commit either to both purchases together or to neither. If the risk management system chooses not to commit to the purchases, the records of those purchases in the recording service are erased; otherwise, those records are kept.

The Configuration System and the Configuration Editor

At the management instrumentation layer, the Windows Communication Foundation provides a configuration system by which administrators can control the endpoints of Windows Communication Foundation applications. The Service Configuration Editor is provided as a tool for them to use in doing so.

The Configuration System

Windows Communication Foundation services are defined by an address that specifies where they are located, a binding that specifies how to communicate with them, and a contract that specifies what they can do. The internal operations of Windows Communication Foundation services and clients can be controlled through properties called behaviors. Although one can write code to specify the addresses, bindings, and contracts of services, and to modify the behaviors of services and clients, the Windows Communication Foundation allows one to instead specify addresses, bindings, and contracts and to modify behaviors in configuration files.

The Windows Communication Foundation’s configuration system is made fully programmable via the classes of the System.ServiceModel.Configuration namespace. Those classes allow developers to create their own tools for interrogating and modifying the configurations of Windows Communication Foundation applications. The code in Listing 19.1 is for a method that adds the Windows Communication Foundation endpoint to a specified .NET application configuration file.

Example 19.1. Writing a Windows Communication Foundation Configuration

void WriteConfiguration(string configurationFilePath)
{
    ServiceEndpointElement endpointElement =
        new ServiceEndpointElement(
            new Uri(@"Calculator",UriKind.Relative),
            @"DerivativesCalculator.IDerivativesCalculator");
    endpointElement.Binding = @"netTcpBinding";

    ServiceElement serviceElement =
        new ServiceElement(
@"DerivativesCalculator.DerivativesCalculatorServiceType");
    serviceElement.Endpoints.Add(endpointElement);

    BaseAddressElement baseAddressElement =
        new BaseAddressElement();
    baseAddressElement.BaseAddress =
        @"net.tcp://localhost:8000/Derivatives/";

    serviceElement.Host.BaseAddresses.Add(baseAddressElement);

    ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
    fileMap.ExeConfigFilename =
        configurationFilePath;
    Configuration configuration =
        ConfigurationManager.OpenMappedExeConfiguration(
            fileMap,
            ConfigurationUserLevel.None);

    ServiceModelSectionGroup sectionGroup =
        (ServiceModelSectionGroup)configuration.GetSectionGroup(
            "system.serviceModel");

    ServicesSection servicesSection =
        (ServicesSection)sectionGroup.Sections["services"];
    servicesSection.Services.Add(serviceElement);

    configuration.Save();
    Console.WriteLine("Done");
    Console.ReadKey(true);
}

The classes of the Windows Communication Foundation’s System.ServiceModel.Configuration.Namespace rely on the facilities of the .NET Framework’s configuration system for loading and applying configuration data to an application, though, and those facilities have important limitations. In particular, applying configuration data from any given file is not supported, yet less being able to apply configuration data in a database.

Of course, the primary benefit of the Windows Communication Foundation’s configuration system is not that it allows developers to read and write the configuration of Windows Communication Foundation applications programmatically. The primary benefit is that it allows system administrators to control how services behave without requiring programming modifications. Indeed, using configuration files to specify addresses, bindings, and contracts is preferred to using code.

The Windows Communication Foundation’s configuration system simply extends that of Microsoft .NET. Therefore, it should be familiar to any administrator of .NET applications. The language of the Windows Communication Foundation’s configuration system is defined in the file Program FilesMicrosoft Visual Studio 8XmlSchemasDotNetConfig.xsd, on the disc where Visual Studio 2005 resides after the .NET Framework 3 Development Tools have been installed.

The Service Configuration Editor

The Windows Communication Foundation provides the Service Configuration Editor to ease, and give guidance for, the task of editing configuration files. The Service Configuration Editor is SvcConfigEditor.exe. It should be found in the folder Program FilesMicrosoft SDKsWindowsv1.0Bin, assuming a complete and normal installation of the Microsoft Windows SDK for the .NET Framework 2.0. If the .NET Framework 3.0 Development Tools have also been installed, the Service Configuration Editor is also accessible right from within Visual Studio.

Configuring the Trade Recording Service with the Configuration Editor

Recall that the trade-recording service of the trading service solution is a service for recording the purchase of derivatives. That service is not currently in a working state. To confirm that, do the following:

  1. Right-click on the TradeRecordingServiceHost project of the trading service solution in Visual Studio 2005, and choose Debug, Start New Instance from the context menu. An exception should be thrown with this error message:

    Service 'Fabrikam.TradeRecorder' has zero application (non-infrastruc-
    ture) endpoints. This might be because no configuration file was found
    for your application, or because no service element matching the service
    name could be found in the configuration file, or because no endpoints
    were defined in the service element.
    

    The message is quite accurate: The service cannot start because no endpoints have been defined for it. There is indeed no configuration file with endpoint definitions.

  2. Choose Debug, Stop debugging from the Visual Studio 2005 menus to terminate the application.

Follow these steps to use the Configuration Editor to configure an endpoint for the trade recording service:

  1. Right-click on the TradeRecordingServiceHost project and choose Add, New Item from the context menu, and proceed to add an application configuration file called App.config to the project.

  2. Right-click on the new App.config file and choose Edit WCF Configuration from the context menu. The Service Configuration Editor will open, as shown in Figure 19.1.

    The Service Configuration Editor.

    Figure 19.1. The Service Configuration Editor.

  3. Click on the Create a New Service link in the right pane to start the New Service Element Wizard.

  4. The first step in the wizard is to identify the service type of the service. To do that for the trade-recording service, start by clicking on the Browse button to open the Type Browser dialog.

  5. In the Type Browser dialog, locate the TradeRecordingService.dll assembly in the bindebug subdirectory of the TradeRecordingServiceHost project directory.

  6. Double-click on that assembly to see a list of the service types defined in that assembly. Select the Fabrikam.TradeRecordingService type, and click Open. The Type Browser dialog will close and the New Service Element Wizard will be back in the foreground.

  7. Click Next. A list of Windows Communication Foundation service contracts implemented by the Fabrikam.TradeRecordingService type is displayed.

  8. There is only one such contract, so there is no need, in this case, to select one. Simply click Next.

  9. The next dialog asks what mode of communication is to be used, as shown in Figure 19.2. The trade-recording service receives requests via a Microsoft Message Queue, so choose MSMQ from among the options displayed, and click Next.

    The communication mode dialog of the New Service Element Wizard.

    Figure 19.2. The communication mode dialog of the New Service Element Wizard.

  10. The next dialog is for the New Service Element Wizard to choose between the predefined bindings NetMsmqBinding and LegacyMsmqBinding. To do so, it asks the user whether Windows Communication Foundation clients for MSMQ clients will be connecting to the service. Select the former option, and click Next.

  11. Now the address for the endpoint is to be entered. Enter net.msmq://localhost/private/TradeRecording as the address and click Next.

  12. Click Finish on the final screen of the New Service Element Wizard.

  13. The binding for the newly defined endpoint will need to be modified slightly to accommodate the possibility of the host system not being attached to a Windows domain. To initiate that modification, click on the link labeled Click to Create opposite the Binding Configuration label on the right pane of the Service Configuration Editor, shown in Figure 19.3. A panel for configuring the NetMsmqBinding opens in the right pane of the Editor, as shown in Figure 19.4.

    Service endpoint configuration.

    Figure 19.3. Service endpoint configuration.

    Binding Configuration panel.

    Figure 19.4. Binding Configuration panel.

  14. Enter MyMSMQBindingConfiguration as the name of the binding configuration opposite the Name label in the right pane of the editor.

  15. Click on the Security tab.

  16. Select None as the mode from the list of security modes opposite the Mode label on the right pane of the editor.

  17. Choose File, Save from the Service Configuration Editor menus.

  18. Choose File, Exit to close the Service Configuration Editor.

Now that an endpoint has been defined in the configuration of the Trade Recording Service Host, that application should be able to start properly. Confirm that by following these steps:

  1. Right-click on the TradeRecordingServiceHost project of the trading service solution in Visual Studio 2005, and choose Debug, Start New Instance from the context menu. A console window for the application should open, and after a few moments, a message should appear confirming that the trade-recording service is available.

  2. Choose Debug, Stop Debugging from the Visual Studio 2005 menus to terminate the application.

Configuring a Client Application with the Configuration Editor

The client risk management application communicates with the trading service, which, in turn, uses the trade-recording service to record derivatives purchases. The trading service has an endpoint at the address http://localhost:8000/TradingService. That endpoint uses the Windows Communication Foundation’s standard WSHttpBinding. The WSHttpBinding is customized to include information about the state of transactions within messages, and to ensure that the messages are delivered exactly once, and in order. Follow these steps to configure the client risk management application appropriately to communicate with the trading service:

  1. Right-click on the Client project within the trading service solution, and choose Build from the context menu.

  2. Right-click on the TradeRecordingServiceHost project and choose Add, New Item from the context menu, and proceed to add an application configuration file called App.config to the project.

  3. Right-click on the new App.config file and choose Edit WCF Configuration from the context menu. The Service Configuration Editor will open as shown in Figure 19.1.

  4. Click on the Create a New Client link on the Tasks panel on the bottom left of the Service Configuration Editor. The New Client Element Wizard opens.

  5. On the first dialog, select the option to configure the client manually using the wizard, rather than have the wizard configure the client from the configuration file of the service.

  6. The next dialog is for identifying the service contract. Click Browse to open the Type Browser dialog.

  7. Use the dialog’s controls to locate the Client.exe assembly, which should be in the bindebug subdirectory of the Client project directory.

  8. Double-click on that assembly to display a list of service contracts it defines.

  9. Select the Client.ITradingService contract, and click Open, which should serve to close the Type Browser dialog, and bring the New Client Element Wizard back to the foreground.

  10. Click Next to proceed to a selection of communication modes.

  11. Select HTTP from the list, and click Next.

  12. The next screen is for the wizard to choose between the predefined BasicHttpBinding and the predefined WSHttpBinding. It displays that choice to the user as a choice between Basic Web Services Interoperability and Advanced Web Services Interoperability. Opt for the latter, and click Next.

  13. Enter http://localhost:8000/TradingService as the address on the subsequent dialog, and click Next.

  14. Enter TradingServiceConfiguration as the name for the client endpoint configuration, and click Next.

  15. Click Finish to complete the wizard’s steps.

  16. The binding for the newly defined endpoint will need to be modified slightly to add the assurance of the messages being delivered exactly once and in order. To initiate that modification, click on the link labeled Click to Create opposite the Binding Configuration label on the right pane of the Service Configuration Editor. A panel for configuring the WSHttpBinding opens in the right pane of the Editor.

  17. Enter MyReliableBindingConfiguration as the name of the binding configuration opposite the Name label in the right pane of the editor.

  18. Scroll down to the ReliableSession properties section.

  19. Select True as the value for the Enabled property in that section, as shown in Figure 19.5.

    Enabling a Reliable Session.

    Figure 19.5. Enabling a Reliable Session.

  20. Choose File, Save from the Service Configuration Editor menus.

  21. Choose File, Exit to close the Service Configuration Editor.

Test the newly configured solution by following these steps:

  1. Choose Debug, Start Debugging from the Visual Studio 2005 menus.

  2. Choose Debug, Start Debugging from the menus.

  3. When there is activity in the console application windows of the Trade Recording Service Host and the Trading Service Host applications confirming that the services they host are ready, enter a keystroke into the console application window of the client application.

    After a few moments, activity should start to appear in the console application window of the trading service host, as the client risk management system begins pricing and purchasing a derivative. There might be a pause as the trading service loads the Microsoft Distributed Transactions Coordinator for the first time. Then the pricing and purchasing of primary and hedging derivatives purchases should proceed.

  4. Choose Debug, Stop Debugging from the Visual Studio 2005 menus.

Configurable Auditing of Security Events

The Windows Communication Foundation records security events in the Windows event log—a management instrumentation facility that is complemented by the Windows Event Viewer as a tool for examining the entries made in the log. The security auditing facility is one of the Windows Communication Foundation’s many behaviors, and it is configurable. To see it in action, follow these steps to modify the default configuration so that not only authentication failures, but also authentication successes will be recorded in the log:

  1. Right-click on the App.config file of the TradingServiceHost project and choose Edit WCF Configuration from the context menu. The Service Configuration Editor opens.

  2. To proceed to edit a behavior, in the top-left pane, expand the Advanced node of the tree, and select Service Behaviors as shown in Figure 19.6.

    Preparing to edit service behaviors.

    Figure 19.6. Preparing to edit service behaviors.

  3. Click on the New Service Behavior Configuration link that will have appeared in the right pane.

  4. Enter TradingServiceBehaviors as the name for a behavior configuration as shown in Figure 19.7.

    Naming a behavior configuration.

    Figure 19.7. Naming a behavior configuration.

  5. Click on the Add button in the Behavior Element Extension Position section.

  6. Choose serviceSecurityAudit from the list of behaviors in the Adding Behavior Element Extension dialog that appears, and click the Add button. An entry for the serviceSecurityAudit behavior should appear in the list of behavior elements as shown in Figure 19.8.

    List of behaviors.

    Figure 19.8. List of behaviors.

  7. Double-click on the entry to be able to modify the properties of the security-auditing behavior.

  8. In the property editor for the behavior, select Security as the AuditLogLocation.

  9. Choose SuccessOrFailure as the value for the MessageAuthenticationAuditLevel.

  10. Choose SuccessOrFailure as the value for the ServiceAuthenticationAuditLevel.

  11. Now a behavior configuration has been created that includes the configuration of the security-auditing behavior. That behavior configuration now has to be associated with the trading service. To do so, select Fabrikam.TradingSystem under the Services node in the tree in the left pane, and then select the TradingServiceBehaviors configuration from the list opposite the BehaviorConfiguration label on the right pane, as shown in Figure 19.9.

    Associating a behavior configuration with a service.

    Figure 19.9. Associating a behavior configuration with a service.

  12. Choose File, Save from the Service Configuration Editor menus.

  13. Choose File, Exit to close the Service Configuration Editor.

Follow these steps to see the effect of the new configuration of the security-auditing behavior:

  1. In Visual Studio 2005, in the trading service solution, choose Debug, Start Debugging from the menus.

  2. When there is activity in the console application windows of the trade recording service host and the trading service host, confirming that the services they host are ready, enter a keystroke into the console application window of the client application.

  3. After seeing activity in the console application windows of the trading service host and the client as they price and purchase derivatives, choose Debug, Stop Debugging from the Visual Studio 2005 menus.

  4. Open the Windows Event viewer.

  5. Refresh the security log.

  6. Locate and examine events with the source ServiceModel Audit. Those are the Windows Communication Foundation’s security audit events. They should look like the event shown in Figure 19.10.

    Windows Communication Foundation security audit event.

    Figure 19.10. Windows Communication Foundation security audit event.

Message Logging, Activity Tracing, and the Service Trace Viewer

At the management instrumentation layer, the Windows Communication Foundation applications can be configured to log messages, and to record traces of their activities. Those facilities can assist administrators in diagnosing problems with the applications. The Service Trace Viewer is provided as a tool for them to use in doing so.

Message Logging

Windows Communication Foundation applications can be configured to log incoming and outgoing messages. Messages can be logged not only at the point at which they are transported, but also as they proceed through the channel layer.

The message-logging facility is implemented using the trace-listening mechanism already incorporated in .NET, in the System.Diagnostics namespace. A trace listener is a class that knows how to output diagnostic information to a particular destination, such as an event log, or a file of a particular format. When particular categories of diagnostic information are directed to a trace listener, the information in that category is dispatched to the destination to which the trace listener sends its output. The same diagnostic information can be recorded in various ways when information is directed to multiple trace listeners.

Message logging is a particular type of diagnostic information that can be sent to a trace listener for recording. By providing message logging via trace listeners, the Windows Communication Foundation not only uses a mechanism with which .NET developers will already be familiar, but also allows developers, enterprises, and other software vendors that might have developed custom trace listeners to use them for logging messages.

To see how to configure Windows Communication Foundation applications to log messages, follow these steps:

  1. Right-click on the App.config file of the TradingServiceHost project and choose Edit WCF Configuration from the context menu. The Service Configuration Editor opens.

  2. Click on the Diagnostics node in the tree in the left pane. The right pane should now show links for configuring message logging and other diagnostic facilities, as shown in Figure 19.11.

    Diagnostics configuration.

    Figure 19.11. Diagnostics configuration.

  3. Click on the Enable Message Logging link.

  4. Click on the ServiceModelMessageLoggingListener link that will have appeared, to configure the trace listener to which logged messages will be directed.

  5. In the Listener Settings window, observe that the trace listener will, by default, be writing the logged messages to a file called app_messages.svclog in the same folder as the Trading Service Host project.

  6. Click OK to close the Listener Settings dialog and return to the Diagnostics Configuration pane.

  7. Click the link labeled Malformed, Transport opposite the Log Level label. The Message Logging Settings dialog appears, which allows one to determine which messages will be captured.

  8. Selecting Transport Messages on that dialog will mean that messages will be logged as they are sent or received, which would mean that if the messages being exchanged are encrypted, the logged messages will be encrypted. Selecting Service Messages will mean that messages are logged as they pass in or out of the Windows Communication Foundation Service model layer, at which point they would usually no longer be encrypted. Select all the options on the dialog and click OK.

  9. Click on the Enable Log Auto Flush link which will ensure that any message log data cached by the trace listener will be flushed to the message log.

  10. Choose File, Save from the Service Configuration Editor menus.

  11. Choose File, Exit to close the Service Configuration Editor.

To see messages being logged, do the following:

  1. In Visual Studio 2005, in the trading service solution, choose Debug, Start Debugging from the menus.

  2. When there is activity in the console application windows of the trade recording service host and the trading service host, confirming that the services they host are ready, enter a keystroke into the console application window of the client application.

  3. Wait until the console application window of the client application confirms that it is done pricing and purchasing derivatives.

  4. Choose Debug, Stop Debugging from the Visuals Studio 2005 menus.

  5. Execute the Windows Communication Foundation’s Trace Viewer, which is SvcTraceViewer.exe. It should be found in the bin subdirectory of the installation of folder of the .NET Framework 3 SDK. The Trace Viewer is shown in Figure 19.12.

    The Trace Viewer.

    Figure 19.12. The Trace Viewer.

  6. Choose File, Open from the menus, and open the file app_messages.svclog, which should be found in the same folder as the TradingServiceHost project file.

  7. Select the first entry in the activity list on the left of the Trace Viewer.

  8. Select the XML tab on the lower right, and scroll through the entry on that tab. It contains a record of a message, as shown in Figure 19.13.

    A logged message.

    Figure 19.13. A logged message.

Activity Tracing

Wikipedia defines a trace as “a detailed record of the steps a computer program executes during its execution, used as an aid in debugging” (Wikipedia 2006). The Windows Communication Foundation generates traces for internal processing milestones, events, exceptions, and warnings. The traces are intended to enable administrators to see how an application is behaving and understand why it might be misbehaving without having to resort to using a debugger. In fact, the members of the Windows Communication Foundation development team are encouraged to diagnose unexpected conditions they encounter using the traces rather than a debugger, and to file a bug report demanding additional traces if the existing traces are not sufficient to allow them to render a diagnosis.

The Microsoft .NET Framework Class Library 2.0 provides an enhanced tracing infrastructure in the form of classes that have been added to the System.Diagnostics namespace, and the Windows Communication Foundation leverages those new classes. The most important of them is the TraceSource class that allows one to generate traces associated with a named source:

private static TraceSource source = new TraceSource("ANamedSource");
source.TraceEvent(TraceEventType.Error,1,"Trace error message.");

Given a named source of traces, one can configure trace listeners to listen for traces from that particular source:

<configuration>
  <system.diagnostics>
    <sources>
      <source name="ANamedSource"
        switchValue="Warning"
        <listeners>
          <add name="AListener"/>
          <remove name="Default"/>
        </listeners>
      </source>
    </sources>
    <sharedListeners>
      <add name="AListener"
        type="System.Diagnostics.TextWriterTraceListener"
        initializeData="myListener.log">
        <filter type="System.Diagnostics.EventTypeFilter"
          initializeData="Error"/>
      </add>
    </sharedListeners>
   </system.diagnostics>
</configuration>

The name of the source of traces emitted by the Windows Communication Foundation’s Service Model is System.ServiceModel. Thus, one might configure a trace listener to listen for traces emitted by the Service Model in this way:

<configuration>
  <system.diagnostics>
    <sources>
      <source name="System.ServiceModel"
        switchValue="Verbose"
        <listeners>
          <add name="xml"
            type="System.Diagnostics.XmlWriterTraceListener"
            initializeData="ClientTraces.svclog"
          />
        </listeners>
      </source>
    </sources>
   </system.diagnostics>
</configuration>

Trace sources have a Switch property for filtering traces emanating from that source according to their level of importance. Traces emitted by the Windows Communication Foundation can be filtered by six levels of importance, as shown, in descending order, in Table 19.2. Filtering a source for traces with a given level of importance will exclude traces with a lower level of importance and include any traces in which the level of importance is of the specified level or higher.

Table 19.2. Windows Communication Foundation Trace Levels

Level

Description

Critical

Traces of catastrophic errors that cause an application to cease functioning

Error

Traces of exceptions

Warning

Traces of conditions that might subsequently cause an exception, such as a limit having been reached or credentials having been rejected

Information

Traces of milestones significant for monitoring and diagnosis

Verbose

Traces of processing milestones interesting to developers for diagnosis and optimization

ActivityTracing

Traces of activity boundaries

The Windows Communication Foundation does not emit traces by default. Activating tracing is easily done using the Configuration Editor:

  1. Right-click on the App.config file of the TradingServiceHost project and choose Edit WCF Configuration from the context menu. The Service Configuration Editor opens.

  2. Click on the Diagnostics node in the tree in the left pane. The right pane should now show links for configuring message logging and other diagnostic facilities, as shown in Figure 19.11.

  3. Click on the Enable Tracing link.

  4. Click on the ServiceModelTraceListener link that will have appeared to configure the trace listener to which activity traces will be directed.

  5. In the Listener Settings window, observe that the trace listener will, by default, be writing the logged messages to a file called app_tracelog.svclog in the same folder as the Trading Service Host project.

  6. Click OK to close the Listener Settings dialog and return to the Diagnostics Configuration pane.

  7. Click the link labeled Warning, Activity Tracing, Propagate Activity opposite the Trace Level label. The Tracing Settings dialog appears, which allows one to set the trace level.

  8. Choose Verbose from the list of options, and click OK.

  9. Choose File, Save from the Service Configuration Editor menus.

  10. Choose File, Exit to close the Service Configuration Editor.

After traces have been recorded, they can be examined using the Service Trace Viewer, SvcTraceViewer.exe. An example of what might be seen is displayed in Figure 19.14.

Viewing traces.

Figure 19.14. Viewing traces.

The Trace Viewer

The Windows Communication Foundation’s Trace Viewer has already been introduced. As can be seen in Figure 19.14, the Trace Viewer displays a list of activities in a pane on the left, and all the traces pertaining to a selected activity in the pane on the upper right. The lower-right pane shows the details of a particular trace. As shown in Figure 19.13, the Trace Viewer can also be used to view logs of messages.

The most impressive capability of the Trace Viewer, though, is in allowing one to examine the flow of an activity across network nodes. Windows Communication Foundation traces have a globally unique identifier, and whenever a Windows Communication Foundation application is configured to emit traces, the activity identifiers are included in any messages it sends. To see the significance of that, follow these steps:

  1. Open the Service Trace Viewer, SvcTraceViewer.exe, in the bin subdirectory of the Windows SDK installation folder.

  2. Choose File, Open from the menus.

  3. In the File Open dialog, select all the trace files in the Logs subdirectory of the Management folder that contains the code associated with this chapter.

  4. Click on the Open button.

  5. If the Partial Loading Dialog appears, click OK to dismiss it.

  6. A progress bar might appear at the bottom of the Service Trace Viewer. Wait until it disappears and the counts of traces and activities appear. These activities were recorded from all three components of the trading system that has been used as an example throughout this chapter: the client risk management system, the trading service, and the trade-recording service. The total number of traces recorded at the verbose trace level across all three applications over a period of less than two minutes was 72,980—a quite considerable quantity of diagnostic information.

  7. Select any activity labeled Process Action in the list of activities in the left pane, such as the one shown highlighted in Figure 19.15.

    Selecting an activity.

    Figure 19.15. Selecting an activity.

  8. Select the Graph tab, shown in Figure 19.16. The Trace Viewer is able to show transfers of activity between the endpoints of a system! That feature allows one to follow an activity from a client to a service and back. For instance, one can select any step in the sequence depicted in the graphical view to see details of the traces emitted in that step in the panes on the right.

    The Graph tab.

    Figure 19.16. The Graph tab.

Incorporating Custom Trace Sources

One can direct one’s own activity traces to the Windows Communication Foundation’s trace listener. By doing so, one can see one’s own activity traces included among those in the service Trace Viewer.

Follow these steps to see how to take advantage of that capability:

  1. Open the Program.cs file of the Trading Service Host project, and modify the code therein as shown in Listing 19.2. The two additional lines serve to define a trace source with the arbitrary name, MyTraceSource, and to emit a trace from that source.

    Example 19.2. Emitting a Custom Trace

    using System;
    using System.Collections.Generic;
    using System.ServiceModel;
    using System.Text;
    
    namespace Fabrikam
    {
        public class Program
        {
            private static System.Diagnostics.TraceSource source =
                new System.Diagnostics.TraceSource("MyTraceSource");
    
            public static void Main(string[] args)
            {
                using (ServiceHost host = new ServiceHost(typeof(TradingSystem)))
                {
                     host.Open();
    
                     Console.WriteLine("The trading service is available.");
    
                     source.TraceEvent(
                         System.Diagnostics.TraceEventType.Verbose,
                         1,
                         "My trace message.");
    
                     Console.ReadKey(true);
                }
            }
        }
    }
    
  2. Right-click on the App.config file of the TradingServiceHost project and choose Edit WCF Configuration from the context menu. The Service Configuration Editor opens.

  3. Proceed to identify the new trace source to the Windows Communication Foundation. Begin by expanding the Diagnostics node in the tree in the left pane.

  4. Right-click on the Sources child node and choose New Source from the context menu.

  5. Enter MyTraceSource as the name of the source—the name of the trace source to which the activity trace emitted by the code in Listing 19.2 is ascribed.

  6. Select Verbose as the trace level.

  7. Now that the new trace source has been identified to the Windows Communication Foundation, traces from that source have to be directed to the Windows Communication Foundation’s trace listener. To begin doing that, expand the Listeners child node of the Diagnostics node.

  8. Select the ServiceModelTraceListener child node.

  9. Click Add on the right pane, and, from the Add Tracing Source dialog, select MyTraceSource from the list of defined trace sources, and click OK.

  10. Choose File, Save from the Service Configuration Editor menus.

  11. Choose File, Exit to close the Service Configuration Editor.

  12. Delete the app_tracelog.svclog file in the same folder as the TradingServiceHost project so that a new trace file will be created in which the custom trace emitted by the code in Listing 19.2 will be easier to pick out.

  13. Right-click on the TradingServiceHost project, and choose Debug, Start New Instance from the context menu.

  14. When the output in the console of the TradingServiceHost application confirms that the trading service is ready, enter a keystroke into the console to terminate the application.

  15. Open the Service Trace Viewer, SvcTraceViewer.exe, in the bin subdirectory of the Windows SDK installation folder.

  16. Choose File, Open from the Service Trace Viewer menus.

  17. In the File Open dialog, select the app_tracelog.svclog that is in the same folder as the TradingServiceHost project, and click the Open button.

  18. Select the first activity in the pane on the left, and the trace emitted by the code in Listing 19.2 will appear in the list of traces associated with that activity, as shown in Figure 19.17.

    A trace from a custom source in the Service Trace Viewer.

    Figure 19.17. A trace from a custom source in the Service Trace Viewer.

  19. Choose File, Exit from the Service Trace Viewer menus.

Performance Counters

At the management instrumentation layer, the Windows Communication Foundation provides a rich variety of performance counters for the monitoring, diagnosis, and optimization of applications. There are performance counters for monitoring services, the individual endpoints of a service, and the individual operations exposed at an endpoint. The performance counter instrumentation is accessible via the Windows Performance Monitor, among other tools.

To examine the performance counters, follow these steps:

  1. Right-click on the App.config file of the TradingServiceHost project and choose Edit WCF Configuration from the context menu. The Service Configuration Editor opens.

  2. Select the Diagnostics node from the tree in the left pane.

  3. Click twice on the Toggle Performance Counters link on the right pane to cycle through the performance counter settings. The first click turns on the performance counters for monitoring the service, whereas the second click turns on the performance counters for individual endpoints and operations as well.

  4. Choose File, Save from the Service Configuration Editor menus.

  5. Choose File, Exit to close the Service Configuration Editor.

  6. Choose Debug, Start Debugging from the Visual Studio 2005 menus.

  7. Wait until there is activity in the console window of the trade recording service host.

  8. Choose Run from the Windows Start menu; then enter

    perfmon

    and click OK.

  9. In the Performance console, right-click on the graph on the right side, and choose Add Counters from the context menu, as shown in Figure 19.18.

    Adding performance counters to the Performance console.

    Figure 19.18. Adding performance counters to the Performance console.

  10. Select ServiceModelService from the Performance Object list, as shown in Figure 19.19.

    Selecting a Windows Communication Foundation performance counter category.

    Figure 19.19. Selecting a Windows Communication Foundation performance counter category.

    ServiceModelService is the name of the category of Windows Communication Foundation performance counters at the service level. Note that there are also categories for performance counters at the level of both endpoints and operations. When the ServiceModelService category is selected, the trade-recording service shows up in the list of instances on the right, as shown in Figure 19.19, because that is a service for which performance counters have been enabled.

  11. Scroll through the extensive list of performance counters in the ServiceModelService category, as shown in Figure 19.20.

    Examining the Windows Communication Foundation performance counters.

    Figure 19.20. Examining the Windows Communication Foundation performance counters.

  12. Click on the Close button.

  13. Choose File, Exit from the Performance Console’s menus to close it.

  14. In Visual Studio 2005, choose Debug, Stop Debugging.

WMI Provider

WMI is Microsoft’s implementation of the Web-Based Enterprise Management architecture defined by the Desktop Management Task Force. The purpose of the architecture is to define a unified infrastructure for managing both computer hardware and software.

WMI is now built into Windows operating systems, and since its introduction as an add-on for Windows NT version 4.0, not only has it become very familiar to Windows systems administrators, but it also is the foundation for many computer management products. If a piece of software can be examined and manipulated via WMI, system administrators will be able to monitor and adjust it using their preferred computer management tools.

The Windows Communication Foundation takes advantage of that situation, incorporating, at the management instrumentation layer, a WMI provider. By virtue of that, Windows Communication Foundation applications become accessible via any WMI-enabled tools, of which there are a great many.

Accessing Data from the WMI Provider via WMI CIM Studio

Follow these steps to observe the effects of the WMI provider through WMI CIM Studio, a simple WMI explorer provided free of charge by Microsoft as part of its WMI toolkit:

  1. Right-click on the App.config file of the TradingServiceHost project and choose Edit WCF Configuration from the context menu. The Service Configuration Editor opens.

  2. Select the Diagnostics node from the tree in the left pane.

  3. Click on the link labeled Enable WMI Provider on the right pane to activate the WMI provider.

  4. Choose File, Save from the Configuration Editor menus to save the configuration.

  5. Select File, Exit from the menus to close the Configuration Editor.

  6. Download the WMI Administrative Tools from http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=6430F853-1120-48DB-8CC5-F2ABDC3ED314.

  7. Install the WMI Administrative Tools.

  8. In Visual Studio 2005, in the trading service solution, choose Debug, Start Debugging from the menus.

  9. Wait until there is activity in the console window of the trade-recording service host.

  10. Choose WMI Tools, WMI CIM Studio from the Windows Start menu.

  11. Enter rootServiceModel into the Connect to Namespace dialog that appears, as illustrated in Figure 19.21. rootServiceModel is the namespace of the classes that the Windows Communication Foundation exposes to WMI.

    Connecting to the rootServiceModel namespace.

    Figure 19.21. Connecting to the rootServiceModel namespace.

  12. Click OK on the WMI CIM Studio Login dialog to log in as the current user.

  13. The classes that the Windows Communication Foundation exposes to WMI are enumerated in the pane on the left. Select Endpoint, as shown in Figure 19.22.

    Selecting a class.

    Figure 19.22. Selecting a class.

  14. Click on the Instances button, which is the fourth button from the left in the row of buttons at the top of the right-hand pane. Information is displayed for each endpoint of any running Windows Communication Foundation application for which the WMI provider is enabled, as shown in Figure 19.23. The WMI CIM Studio retrieves that information via WMI, which, in turn, retrieves it using the Windows Communication Foundation’s WMI provider.

    Viewing data retrieved via WMI.

    Figure 19.23. Viewing data retrieved via WMI.

  15. Select the AppDomainInfo class in the pane on the right. As illustrated in Figure 19.24, one can modify properties of that class, such as the LogMessagesAtServiceLevel property, which configures message logging for a service. This facility allows one to configure properties of services while they are executing. Any modifications made in this way are made to the running instances only and are not persisted in any configuration file. To persist configuration elements in configuration files, use the Service Configuration Editor.

    Configuring running services.

    Figure 19.24. Configuring running services.

  16. Choose File, Close from the WMI CIM Studio menus to close WMI CIM Studio.

  17. Choose Debug, Stop Debugging from the Visual Studio 2005 menus.

Accessing Data from the WMI Provider Using Windows PowerShell

Windows PowerShell is another WMI-enabled management tool. The next few steps show how Windows PowerShell can be used to access information about running Windows Communication Foundation services via the Windows Communication Foundation WMI provider:

  1. Download Windows PowerShell from the Microsoft Downloads site, http://www.microsoft.com/downloads.

  2. Install Windows PowerShell.

  3. In Visual Studio 2005, in the trading service solution, choose Debug, Start Debugging from the menus.

  4. Wait until there is activity in the console window of the trade recording service host.

  5. Choose Programs, Windows PowerShell 1.0, Windows PowerShell from the Windows Start menu.

  6. Enter the following command at the Windows PowerShell command prompt:

    get-wmiobject endpoint -n rootServiceModel |ft name

    Windows PowerShell displays the names of each Windows Communication Foundation endpoint on the local machine by querying WMI for the data for all endpoint objects in the rootServiceModel namespace, and displaying the name property of each one.

  7. Close the Windows PowerShell console.

  8. In Visual Studio 2005, choose Debug, Stop Debugging from the menus.

Using the WMI Provider to Add Custom Performance Counters

The WMI provider allows one to add custom performance counters to monitor data points unique to a system. This section shows how one can accomplish that.

In the trading service solution, a natural quantity for business administrators to want to monitor is the volume of trades. Among various ways in which that quantity could be exposed for examination, adding a performance counter for trade volume to the trade recording service would allow it to be monitored using the Performance Console that is built into Windows operating systems.

Remember that the Windows Communication Foundation performance counters can be monitored for each individual instance of a service, as shown in Figure 19.19, as well as for individual endpoints and operations. To associate the trace volume performance counter with a particular instance of a Windows Communication Foundation application, it is necessary to access the running instance of the application via WMI. To see how to do this, follow these steps:

  1. Right-click on the App.config file of the TradeRecordingServiceHost project and choose Edit WCF Configuration from the context menu. The Service Configuration Editor opens.

  2. Select the Diagnostics node from the tree in the left pane.

  3. Click on the link labeled Enable WMI Provider on the right pane to activate the WMI provider.

  4. Click twice on the Toggle Performance Counters link on the right pane to cycle through the performance counter settings to the setting by which all the performance counters are enabled.

  5. Choose File, Save from the Configuration Editor menus to save the configuration.

  6. Select File, Exit from the menus to close the Configuration Editor.

  7. Open the Program.cs file of the TradeRecordingServiceHost project in the trading service solution. After initializing the host of the trade recording service, the code in that file calls a custom IntializeCounters() method of the trading service’s service type:

    public static void Main(string[] args)
    {
        if (!(MessageQueue.Exists(queueName)))
        {
            MessageQueue.Create(queueName, true);
        }
    
        TradeRecorder tradeRecorder = new TradeRecorder();
        using (ServiceHost host = new ServiceHost(tradeRecorder))
        {
            host.Open();
            tradeRecorder.InitializeCounters(host.Description.Endpoints);
            Console.WriteLine("The trade recording service is available.");
            Console.ReadKey();
        }
    }
    
  8. Examine that method, which is in the TradeRecorder.cs module of the TradeRecordingService project. It is reproduced in Listing 19.3. The code for the method assembles a list of the names for the service’s endpoints:

    foreach (ServiceEndpoint endpoint in endpoints)
    {
      names.Add(
      string.Format("{0}@{1}",
      this.GetType().Name, endpoint.Address.ToString()));
    }
    

    Then it uses those names to retrieve the WMI objects corresponding to the endpoints of the running instance of the service:

    string condition = string.Format(
      "SELECT * FROM Service WHERE Name="{0}"", name);
    SelectQuery query = new SelectQuery(condition);
    ManagementScope managementScope =
      new ManagementScope(
        @"\.
    ootServiceModel",
        new ConnectionOptions());
    ManagementObjectSearcher searcher =
      new ManagementObjectSearcher(managementScope, query);
    ManagementObjectCollection instances = searcher.Get();
    

    Those objects are then used to add the trade volume counter to that instance of the service:

    foreach (ManagementBaseObject instance in instances)
    {
        PropertyData data =
            instance.Properties["CounterInstanceName"];
    
        this.volumeCounter = new PerformanceCounter(
            TradeRecorder.CounterCategoryName,
            TradeRecorder.VolumeCounterName,
            data.Value.ToString());
        this.volumeCounter.ReadOnly = false;
        this.volumeCounter.RawValue = 0;
        break;
    }
    

    Example 19.3. InitializeCounters() Method

    public void InitializeCounters(ServiceEndpointCollection endpoints)
    {
        List<string> names = new List<string>();
        foreach (ServiceEndpoint endpoint in endpoints)
        {
            names.Add(
                string.Format("{0}@{1}",
                    this.GetType().Name, endpoint.Address.ToString()));
        }
    
        while (true)
        {
            try
            {
                foreach (string name in names)
                {
                     string condition = string.Format(
                         "SELECT * FROM Service WHERE Name="{0}"", name);
                     SelectQuery query = new SelectQuery(condition);
                     ManagementScope managementScope =
                         new ManagementScope(
                             @"\.
    ootServiceModel",
                             new ConnectionOptions());
                     ManagementObjectSearcher searcher =
                         new ManagementObjectSearcher(managementScope, query);
                     ManagementObjectCollection instances = searcher.Get();
                     foreach (ManagementBaseObject instance in instances)
                     {
                         PropertyData data =
                             instance.Properties["CounterInstanceName"];
    
                         this.volumeCounter = new PerformanceCounter(
                             TradeRecorder.CounterCategoryName,
                             TradeRecorder.VolumeCounterName,
                             data.Value.ToString());
                         this.volumeCounter.ReadOnly = false;
                         this.volumeCounter.RawValue = 0;
    
                         break;
                     }
                }
                break;
            }
            catch(COMException)
            {
    
            }
    
        }
    
        if(this.volumeCounter != null)
        {
            Console.WriteLine("Volume counter initialized.");
        }
        Console.WriteLine("Counters initialized.");
    
    }
    
  9. Look at the RecordTrades() method of the trade-recording service’s service type, which is in the same module:

    void ITradeRecorder.RecordTrades(Trade[] trades)
    {
        Console.WriteLine("Recording trade ...");
        return;
        lock (this)
        {
            while (this.volumeCounter == null)
            {
                Thread.Sleep(100);
            }
        }
         foreach(Trade trade in trades)
         {
             this.tradeCount+=((trade.Count != null)?trade.Count.Value:0);
    
             this.volumeCounter.RawValue = this.tradeCount;
    
             Console.WriteLine(string.Format("Recorded trade for {0}",trade));
         }
    }
    

    The method updates the trading volume performance counter with the value of each trade the service records. Currently, however, this return statement

    Console.WriteLine("Recording trade ...");
    return;

    causes the method to exit prematurely. The reason is that the performance counter would not have been available until the WMI provider was activated for the service according to the instructions given previously. Only after the WMI provider was activated for the service would the InitializeCounters() method have been able to retrieve the running instance of the service to which to add the performance counter.

  10. Because the WMI provider has now been activated for the service, comment out the return statement:

    Console.WriteLine("Recording trade ...");
    //return;
  11. Choose Debug, Start Debugging from the menus.

  12. Wait until there is activity in the console window of the trade-recording service host.

  13. Choose Run from the Windows Start menu; then enter

    perfmon

    and click OK.

  14. In the Performance console, right-click on the graph on the right side, and choose Add Counters from the context menu, as shown in Figure 19.18.

  15. Select TradeRecording from the Performance Object list, TradeRecording being the name provided by the InitializeCounters() method for a custom performance counter category for the trade volume counter. As shown in Figure 19.25, the Trade Volume counter is shown as being available for the running instance of the trade recording service.

    Adding the Trade Volume performance counter.

    Figure 19.25. Adding the Trade Volume performance counter.

  16. Click the Add button on the Add Counters dialog, and then the Close button.

  17. Enter a keystroke into the console application window of the client application.

  18. Observe, in the Performance Console, the movement of the custom trade volume performance counter, as depicted in Figure 19.26.

    Monitoring the Trade Volume performance counter.

    Figure 19.26. Monitoring the Trade Volume performance counter.

  19. In Visual Studio 2005, choose Debug, Stop Debugging from the menus.

  20. In the Performance Console, choose File, Exit from the menus to close it.

Completing the Management Facilities

It should be apparent from the foregoing that there is ample instrumentation and tooling for Windows Communication Foundation applications. However, it must remain a task for developers to provide management models specific to their particular applications—because what needs to be monitored, what the values of instruments signify, and what remedial action needs to be taken, will be specific to each application.

A tool to assist in the process of building management models is the Microsoft Management Model designer, which is available free of charge from the Microsoft Downloads site, http://www.microsoft.com/downloads. A paper that describes how to use the tool to define normal and abnormal states for one’s application, and to specify the remedial actions to be taken is available at http://www.microsoft.com/windowsserversystem/dsi/designwp.mspx. In using the Management Model Designer to build a management model for a Windows Communication Foundation application, one will be specifying for administrators how to interpret the Windows Communication Foundation’s instrumentation in divining the health of the application, and how to use the Windows Communication Foundation’s management tools to sustain normal operation.

An especially useful feature of the Management Model Designer is that it allows one to export a management model as a Microsoft Operations Manager management pack. By importing the management pack in Microsoft Operations Manager 2003, one can achieve the integration of a particular application’s management model into an integrated management environment familiar to administrators.

Summary

The Windows Communication Foundation is designed to provide manageable software services. It offers a rich variety of instrumentation and tools for systems administrators to use to manage Windows Communication Foundation solutions, and it allows software developers to add their own. The administration facilities offered by the Windows Communication Foundation all build on familiar management components of the Windows platform, such as WMI and the .NET configuration system, thereby reducing what administrators and developers have to learn about managing Windows Communication Foundation applications.

References

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset