In their book Understanding SOA with Web Services, Eric Newcomer and Greg Lomow present a vision of “the service-oriented enterprise”: “Driven by the convergence of key technologies and the universal adoption of Web services, the service-oriented enterprise promises to significantly improve corporate agility, speed time-to-market for new products and services, reduce IT costs, and improve operational efficiency” (Newcomer and Lomow 2005, 2).
This is precisely the vision being used to sell business decision-makers on the idea of adopting service orientation. Yet service orientation is merely a way of making software, developing it in the form of classes that implement WSDL interfaces. So what is the magic by which a particular approach to developing software yields significant improvements in corporate agility and time-to-market, reduced information technology costs, and operational efficiency? Well, service-oriented software is assumed to be readily composable units of which not only the functionality but also the costs and other operational characteristics are well-known. Thus, a business equipped with service-oriented software is presumed to be able to adjust to its market by quickly reassembling its information systems appropriately from various service-oriented components, “deriving the information system design from the business design [to] more easily drive changes into the information system at the rate and pace of change in the business design” (High, Kinder and Graham 2005, 7). For that to be possible, it is not sufficient only to know what a software service can do and how it communicates, which is all that WSDL can say. It is also necessary for its cost of ownership to be measurable and monitored so that the financial feasibility of a given assembly of services can be readily and continually assessed, and it must be easy to deploy and administer. Only then can one hope to be able to “tun[e] the operational environment to meet the business objectives…and measur[e] success or failure to meet those objectives” (High, Kinder and Graham 2005, 23). Software services, then, are supposed to be manageable, both as software entities by systems administrators and as components of a business enterprise, as budget line items.
Yet, although an important impetus for the adoption of service orientation is the prospect of an information services infrastructure composed of readily manageable units, the manageability of services has been quite neglected in the various facilities for developing software services that have been available up to this point. Microsoft .NET Web Services and the Web Services Enhancements for Microsoft .NET provide no management features specifically for software services, although AmberPoint Express, which provides for monitoring the performance of services and diagnosing errors in them, is freely available for use with certain versions of Microsoft Visual Studio 2005. IBM’s Emerging Technologies Toolkit for Web Services and Autonomic Computing only provides classes for developing implementations of the WS-Resource Framework specification. That specification defines a language by which a service can identify properties it can monitor and manipulate, and by which clients can retrieve and modify property values. IBM also offers for sale the Tivoli Application Manager for SOA, which, similar to AmberPoint’s free Express product, allows one to monitor and remedy the performance of software services.
In stark contrast to its predecessors, the Windows Communication Foundation is deliberately designed to meet the requirement for manageable software services. It does so in two ways. First, it provides a rich variety of tools for systems administrators to use to manage Windows Communication Foundation solutions. Second, it allows software developers to easily augment those tools for systems administrators, and also to add facilities that will be unique to each business enterprise, by which business administrators can monitor costs, risks, and returns.
In preparation for exploring these tools, follow these steps:
Copy the code associated with this chapter that you downloaded from www.samspublishing.com to the folder C:WCFHandsOn
. The code is all in a folder called Management
. After the code has been unzipped, there should be a folder that looks like the one shown in Figure 12.1.
Open the solution C:WCFHandsOnManagementTradingService.sln
.
Install Microsoft Message Queuing (MSMQ), if it is not already installed.
Also complete these next few steps if support for the WS-AtomicTransactions protocol in the Microsoft Distributed Transactions Coordinator has not already been enabled:
Open the Microsoft Windows Vista DEBUG Build Environment prompt, which, assuming a complete and normal installation of the Microsoft Windows SDK for the December 2005 WinFX CTP, should be accessible from the Windows Start menu by choosing All Programs, Microsoft Windows SDK, CMD Shell.
xws_reg –wsat+
Then enter this one:
exit
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, and 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, and 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 Windows Communication Foundation provides these tools for administering software services:
A configuration system for deployment and for post-deployment control and tuning
A configuration editor
Message logging
The tracing of internal activities and of sequences of activities across nodes
A Trace Viewer designed for following sequences of activities across nodes
Performance counters for key operational, security, reliability, and transaction statistics for services; the various endpoints of a service; and the individual operations of an endpoint
A Windows Management Instrumentation (WMI) provider for querying and modifying the properties of running services
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. That 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 Visual Studio 2005 Extensions for WinFX have been installed.
A configuration editor is provided to ease, and give guidance for, the task of editing configuration files. This tool is one of the most rapidly evolving components of the Windows Communication Foundation. The Windows Communication Foundation’s Service Model had to be completed before coding of the tools for using it could proceed in earnest, and after initial versions of the tools were released, refinements to them have followed quickly. Indeed, the configuration editor is being superseded by a configuration wizard, a prototype of which was being shown internally at Microsoft in early January 2006. Consequently, details on the use of the tools in these pages are very likely to have been made obsolete by changes in how the tools work in subsequent releases. So do not read these details to see exactly how to use the tools, but rather to see that even in early versions, the tools are intuitive to use and they work. Because future versions will be even more intuitive to use, adapting the details that follow to those subsequent versions should be quite straightforward.
The 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 December 2005 WinFX CTP.
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:
Right-click on the trade recording service host 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 has zero application (non-infrastructure) endpoints, [which] might be because no configuration file was found for your application, or because there was a problem with the type in the configuration file.” 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.
Stop debugging.
Follow these steps to use the Configuration Editor to configure an endpoint for the trade recording service:
Execute Program FilesMicrosoft SDKsWindowsv1.0BinSvcConfigEditor.exe
.
Choose File, Open, Executable from the menus, as shown in Figure 12.2.
Select the trade recording service’s host assembly C:WCFHandsOnManagementTradeRecordingServiceHostinDebugTradeRecordingServiceHost.exe
, as shown in Figure 12.3.
On the Services tab, click on the New button shown in Figure 12.4.
A service is configured by identifying the service type and defining its endpoints. To select the service type from the General tab of the Service Editor, shown in Figure 12.5, click on the ellipsis button opposite the ServiceType label.
The service type of the trade recording service is in the assembly built from the trade recording service project: C:WCFHandsOnManagementTradeRecordingServiceHostinDebugTradeRecordingService.dll
. Select that assembly, as shown in Figure 12.6, and click on the Open button.
Choose the Fabrikam.TradingRecorder service type from within the assembly, as shown in Figure 12.7, and click on the Open button.
The General tab of the Service Editor should now show Fabrikam.TradeRecorder as the service type, as shown in Figure 12.8. Click OK to return to the main screen of the Configuration Editor, which should now appear as shown in Figure 12.9.
Select the Bindings tab, and then choose netMsmqBinding from the list of binding types as shown in Figure 12.10.
Click on the New button, and then configure a netMsmqBinding with the name QueuedBinding, as shown in Figure 12.11.
Select the Security tab, and select None from the list of security modes, as shown in Figure 12.12.
Click OK, and the Bindings tab should appear as shown in Figure 12.13.
Now that a suitable binding configuration has been created, an endpoint with that binding can be added to the service. Select the Services tab again, and click on the Edit button, depicted in Figure 12.14.
Select the Endpoints tab of the Service Editor represented in Figure 12.15.
Specify the address of the endpoint as shown in Figure 12.16.
Select netMsmqBinding from the list of bindings, as shown in Figure 12.17.
Select the QueuedBinding binding configuration, which was defined in the preceding steps, from the list of available binding configurations, as shown in Figure 12.18.
To identify the contract exposed at the endpoint, click on the ContractType ellipsis button shown in Figure 12.19.
Select the Fabrikam.ITradeRecorder service contract in the assembly C:WCFHandsOnManagementTradeRecordingServiceHostinDebugTradeRecordingService.dll
, as shown in Figure 12.20, and click on the Open button.
The endpoint configuration should now appear as shown in Figure 12.21. Click on the OK button to return to the Endpoints tab of the Service Editor.
The Endpoints tab of the Service Editor should now appear as depicted in Figure 12.22, showing the address and the binding of the endpoint. Click on the OK button to return to the main screen of the Configuration Editor.
Choose File, Save from the Configuration Editor menus, as shown in Figure 12.23.
Confirm that whereas the trade recording service was not initially in a working state, it now is able to work because it has been properly configured using the Windows Communication Foundation’s configuration editor:
Right-click on the trade recording service host project of the trading service solution in Visual Studio 2005, and choose Debug, Start New Instance from the context menu. After a few seconds, the console application window of the trade recording service host should appear, confirming that the service is available.
Stop debugging.
Follow these steps to configure the client risk management application to communicate 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:
Choose File, Open, Executable from the Configuration Editor’s menus, as shown in Figure 12.24.
Select C:WCFHandsOnManagementClientinDebugClient.exe
, as shown in Figure 12.25.
Select the Bindings tab, as shown in Figure 12.26.
Select wsHttpBinding
from the list of bindings, and then click on the New button to create a new configuration of that standard binding, as shown in Figure 12.27.
As shown in Figure 12.28, give the binding configuration the name ReliableHttpBinding
, set the value of the TransactionFlow
property to True
, and, under the ReliableSession Properties heading, set the values of the Enabled
and Ordered
properties to True
.
Click OK, and the Bindings tab should appear as shown in Figure 12.29.
Now that a suitable binding configuration has been created, the service endpoint to be addressed by the client application can be defined. Select the Client tab, and click on the Edit button, depicted in Figure 12.30.
Enter TradingService
as the name of the endpoint configuration, and http://localhost:8000/TradingService
as the address of the service endpoint, as shown in Figure 12.31.
Choose wsHttpBinding
from the list of bindings, as indicated in Figure 12.32.
Select ReliableHttpBinding
from the list of binding configurations, as indicated in Figure 12.33.
To identify the contract exposed at the endpoint, click on the ContractType
ellipsis button shown in Figure 12.34.
The contract is defined in the client assembly, so select the C:WCFHandsOnManagementClientinDebugClient.exe
assembly, as shown in Figure 12.35, and click on the Open button.
Select the Client.ITradingService
service contract as shown in Figure 12.36, and click on the Open button.
The endpoint configuration should now appear as shown in Figure 12.37. Select the Identity tab.
Enter the current user’s principal name in the format domain
ame
as the value of the UserPrincipalName
property, as shown in Figure 12.38, but substituting the current user’s principal name for the name shown. Click on the OK button to return to the Client tab of the Service Editor.
The client configuration should now appear as shown in Figure 12.39. Choose File, Save from the Configuration Editor’s menus, as shown in Figure 12.40.
Choose File, Exit from the menus to close the Configuration Editor.
Test the newly configured solution by following these steps:
In Visual Studio 2005, right-click on the solution at the top of the tree in the Solution Explorer, and choose Set Startup Projects from the context menu. Confirm that the Startup Project properties are configured as shown in Figure 12.41
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.
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 may 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.
Stop debugging.
The Windows Communication Foundation records security events in the Windows event log. That facility is one of the Windows Communication Foundation’s many behaviors, and it is configurable. To see how to configure it, follow these steps:
Execute Program FilesMicrosoft SDKsWindowsv1.0BinSvcConfigEditor.exe
.
Choose File, Open, Executable from the menus, as shown in Figure 12.42, and open the assembly C:WCFHandsOnManagementTradingServiceHostinDebugTradingServiceHost.exe
.
Select the Behaviors tab, and click on the New button, as shown in Figure 12.43.
In the Behavior Editor, provide the name TradingService
for the behavior, as shown in Figure 12.44.
Select serviceSecurityAudit
from the list of behaviors meant to be configured by an administrator, as shown in Figure 12.45. The ServiceSecurityAudit
behavior is the behavior by which the Windows Communication Foundation’s auditing of security events can be controlled.
Click on the Add button.
Back in the main screen of the Behavior Editor, select serviceSecurityAudit
, which now appears in the list in the Elements section, as shown in Figure 12.46, and click on the Properties button.
In the property editor for the ServiceSecurityAudit
behavior, select Application
as the AuditLogLocation
, as shown in Figure 12.47.
Choose SuccessOrFailure
as the value for the MessageAuthenticationAuditLevel
, as shown in Figure 12.48.
Choose SuccessOrFailure
as the value for the ServiceAuthenticationAuditLevel
, as shown in Figure 12.49.
Click OK to return to the main screen of the Configuration Editor.
Now a behavior configuration including the ServiceSecurityAuditBehavior
has been created. That behavior configuration will now be associated with the trading service.
Select the Services tab, and select Fabrikam.TradingSystem
in the list of services, as shown in Figure 12.50, and click on the Edit button.
Select the TradingService
behavior configuration from the list of behavior configurations, as shown in Figure 12.51.
Click the OK button to return to the main screen of the Configuration Editor.
Choose File, Save from the menus, as shown in Figure 12.52.
Select File, Exit from the menus to close the Configuration Editor.
Follow these steps to test the new configuration of the security auditing behavior:
In Visual Studio 2005, in the trading service solution, Choose Debug, Start Debugging from the menus.
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.
After seeing activity in the console application windows of the trading service host and the client as they price and purchase derivatives, stop debugging.
Open the Windows Event viewer.
Refresh the application log.
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 12.53.
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 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 may have developed custom trace listeners to use those for logging messages. To see how to log messages, follow these steps:
Execute Program FilesMicrosoft SDKsWindowsv1.0BinSvcConfigEditor.exe
.
Start the Configuration Editor; choose File, Open, Executable from the menus, and open the assembly C:WCFHandsOnManagementTradingServiceHostinDebugTradingServiceHost.exe
.
Select the Diagnostics tab as shown in Figure 12.54.
Click on the Logging button to access the Message Logging Editor shown in Figure 12.55.
Select the Logging tab, shown in Figure 12.56, and set the values of the LogEntireMessage
, LogMessagesAtServiceLevel
, and LogMessagesAtTransportLevel
properties to True
.
Select the Listeners tab, shown in Figure 12.57, and click on the Create button. Doing that serves to direct the message logs to a custom trace listener.
Use the Save Log As dialog, shown in Figure 12.58, to specify that the trace listener is to record the message log in the file C:WCFHandsOnManagementTradingServiceHost_messages.e2e
.
The Message Logging Editor should now appear as shown in Figure 12.59. Click on the OK button.
Choose File, Save from the Configuration Editor menus to save the configuration, as shown in Figure 12.60.
Select File, Exit from the menus to close the Configuration Editor.
To see messages being logged, do the following:
In Visual Studio 2005, in the trading service solution, choose Debug, Start Debugging from the menus.
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.
Wait until the console application window of the client application confirms that it is done pricing and purchasing derivatives.
Enter a keystroke into each console application window.
Execute the Windows Communication Foundation’s Trace Viewer, which is SvcTraceViewer.exe
. It should be found at C:Program FilesMicrosoft SDKsWindowsv1.0Bin
, assuming a complete and normal installation of the Microsoft Windows SDK for the December 2005 WinFX CTP. The Trace Viewer is shown in Figure 12.61.
Choose File, Open from the menus, and open the file C:WCFHandsOnManagementTradingServiceHost_messages.e2e
, which is the file in which the trace listener was to record the message logs.
Select the first entry in the activity list on the left of the Trace Viewer; then 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 12.62.
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 may 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 might 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.e2e" /> </listeners> </source> </sources> </system.diagnostics> </configuration>
Traces emitted by the Windows Communication Foundation’s own XML serializer, XmlFormatter
, originate from a source named System.Runtime.Serialization
, whereas traces from XSI have a source with the name System.SecurityAuthorization
.
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 12.1. Filtering a source for traces with a given level of importance will exclude traces with a lower level of importance, and include any traces of which the level of importance is the specified level or higher.
Table 12.1. 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 may 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:
From the Diagnostics pane, click on the Tracing button shown in Figure 12.63.
In the Diagnostics Tracing dialog, shown in Figure 12.64, click on the Create button to configure a trace listener.
Specify where the tracing information is to be written, as shown in Figure 12.65.
After traces have been recorded, they can be examined using the Trace Viewer, C:Program FilesMicrosoft SDKsWindowsv1.0BinSvcTraceViewer.exe
. An example of what might be seen is displayed in Figure 12.66.
The Windows Communication Foundation’s Trace Viewer has already been introduced. As can be seen in Figure 12.66, 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 12.62, 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:
Open the Trace Viewer, C:Program FilesMicrosoft SDKsWindowsv1.0BinSvcTraceViewer.exe
.
Choose File, Open from the menus, as shown in Figure 12.67.
In the File Open dialog, select all the trace files in the folder C:WCFHandsOnManagementTraces
, as shown in Figure 12.68, and click on the Open button.
Click the OK button on the File Partial Loading dialog shown in Figure 12.69.
Select an activity from the list in the pane on the left, as shown in Figure 12.70.
Select the Graph tab, shown in Figure 12.71.
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 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. To examine the performance counters, follow these steps:
Start the Configuration Editor, and choose File, Open, Executable from the menus, and open the assembly C:WCFHandsOnManagementTradingRecordingServiceHostinDebugTradingRecordingServiceHost.exe
.
Select the Diagnostics tab.
Check the box labeled Enable Performance Counters, as shown in Figure 12.72.
Choose File, Save from the Configuration Editor menus to save the configuration.
Select File, Exit from the menus to close the Configuration Editor.
In Visual Studio 2005, in the trading service solution, choose Debug, Start Debugging from the menus.
Wait until there is activity in the console window of the trade recording service host.
Choose Run from the Windows Start menu; then enter
perfmon
and click OK.
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 12.73.
Select ServiceModelService
from the Performance object list, as shown in Figure 12.74.
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 12.74, because that is a service for which performance counters have been enabled.
Scroll through the extensive list of performance counters in the ServiceModelService
category, as shown in Figure 12.75.
Choose File, Exit from the Performance Console’s menus to close it.
In Visual Studio 2005, stop debugging the trading service solution.
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 a WMI provider by which Windows Communication Foundation applications become accessible via WMI. Follow these steps to observe its effects:
Start the Configuration Editor; choose File, Open, Executable from the menus, and open the assembly C:WCFHandsOnManagementTradingRecordingServiceHostinDebugTradingRecordingServiceHost.exe
.
Select the Diagnostics tab.
Check the box labeled Enable WMI, as shown in Figure 12.76, to activate the WMI provider.
Choose File, Save from the Configuration Editor menus to save the configuration.
Select File, Exit from the menus to close the Configuration Editor.
Download the WMI Administrative Tools from http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=6430F853-1120-48DB-8CC5-F2ABDC3ED314.
Install the WMI Administrative Tools.
In Visual Studio 2005, in the trading service solution, choose Debug, Start Debugging from the menus.
Wait until there is activity in the console window of the trade recording service host.
Choose WMI Tools, WMI CIM Studio from the Windows Start menu.
Enter rootServiceModel
into the Connect to Namespace dialog that appears, as illustrated in Figure 12.77. rootServiceModel
is the namespace of the classes that the Windows Communication Foundation exposes to WMI.
Click OK on the WMI CIM Studio Login dialog, depicted in Figure 12.78, to log in as the current user.
The classes that the Windows Communication Foundation exposes to WMI are enumerated in the pane on the left. Select ServiceEndpoint
, as shown in Figure 12.79.
Click on the Instances button, which is the fourth button from the left in the row of buttons at the top of the righthand 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 12.80. The WMI CIM Studio is retrieving that information via WMI, which, in turn, retrieves it using the Windows Communication Foundation’s WMI provider.
Select the AppDomainInfo
class in the pane on the right. As illustrated in Figure 12.81, 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 Configuration Editor.
Choose File, Close to close the WMI CIM Studio.
In Visual Studio 2005, stop debugging the trading service solution.
Evidently, the Windows Communication Foundation provides a rich set of tools for managing Windows Communication Foundation applications. It also allows software developers to add their own tools for systems, and allows business administrators to monitor characteristics unique to a system.
For example, 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.
To add this performance counter, or any other management facility, to a Windows Communication Foundation application, a step that is often required is that of accessing a running instance of the application via WMI. To see how to do this to add the trade volume performance counter, follow these instructions:
In Visual Studio 2005, 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(); } }
Examine that method, which is in the TradeRecorder.cs
module of the TradeRecordingService project. It is reproduced in Listing 12.1.
Example 12.1. 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."); }
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; }
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 succeed in retrieving the running instance of the service to which to add the performance counter.
Because the WMI provider has now been activated for the service, comment out the return
statement:
Console.WriteLine("Recording trade ..."); //return;
Choose Debug, Start Debugging from the menus.
Wait until there is activity in the console window of the trade recording service host.
Choose Run from the Windows Start menu; then enter
perfmon
and click OK.
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 12.73.
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 12.82, the Trade Volume counter is shown as being available for the running instance of the trade recording service.
Click the Add button on the Add Counters dialog, and then the Close button.
Enter a keystroke into the console application window of the client application.
Observe, in the Performance Console, the movement of the custom trade volume performance counter, as depicted in Figure 12.83.
In Visual Studio 2005, stop debugging the trading service solution.
In the Performance Console, choose File, Exit from the menus to close the console.
Software services are supposed to be manageable, both as software entities by systems administrators, and as components of a business enterprise as budget line items. The Windows Communication Foundation is designed to provide manageable software services. It offers a considerable number of 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.
18.221.126.56