Building Custom Code to Monitor Activity

The most common implementation option among developers is to develop their own custom code for monitoring. Developers can utilize interfaces in C# or VB .NET to build monitoring classes to audit, trace, and manage their services. This was common with ASMX and other previous technologies because of the lack of tools available "out of the box" from the Windows platform. This method also delivers the flexibility to concentrate on the features the developer prefers to monitor. In this section, you'll investigate how you can utilize custom code building to implement some monitoring functionality in the QuickReturns Ltd. example. Specifically, you will create an ITradeMonitor interface that will act as a framework monitor to the ExchangeService service requests.

NOTE

We have decided to use Chapter 4's Example04 to build these monitoring examples, and we have decided to self-host the service. This is different from Chapter 4's implementation of the service being hosted as an IIS service. The design change is simply to facilitate the ease of creating sample code. The self-host concepts will facilitate IIS hosting without any major modifications (that is, you need to make some trivial changes such as creating a Web.config file as opposed to an App.config file). We have used Visual Studio 2005 as the IDE for these examples.

Here are the steps for implementing the code:

  1. Open the Visual Studio 2005 IDE (Start Programs Microsoft Visual Studio 2005 Microsoft Visual Studio 2005).

  2. Create a blank solution in Visual Studio 2005 (File New Project).

  3. You will see the New Project dialog box. Select Other Project Types, then select Visual Studio Solutions, and finally choose Blank Solution. Name this solution WCFManagement, and point to your preferred directory (in this case we have chosen C:PracticalWcfChapter06), as shown in Figure 6-1.

    Creating a blank solution file
  4. Add the ExchangeService project from Chapter 4's Example04 folder. Now you need to make some changes to the code. Specifically, add a new C# file to the project by right-clicking ExchangeService and selecting Add New Item. When the Add New Item dialog box appears, name it ITradeMonitor.cs, as shown in Figure 6-2.

    Adding the ITradeMonitor class to ExchangeService

Listing 6-1 illustrates the code in this class.

Example. ITradeService.cs
Using System;
using System.Collections.Generic;
using System.ServiceModel;
using System.Text;

namespace ExchangeService
{
    [ServiceContract]
    public interface ITradeMonitor
    {
        [OperationContract]
        string StartMonitoring(string ticker);
        [OperationContract]
        string StopMonitoring(string ticker);
    }
}

The ITradeMonitor interface is simple. You are implementing two methods: StartMonitoring and StopMonitoring. What is the objective of this interface? You are forcing the classes that implement this interface to address monitoring activities that are "before" and "after" implementing the business logic. Therefore, alter TradeService.cs to implement this interface, as shown in Listing 6-2.

NOTE

We are illustrating how to use custom-built interfaces as monitoring utilities in order to illustrate WCF managing and monitoring concepts. We have not implemented the best practices or any optimization required to run this in production environments. This is an exercise to illustrate the "pain" developers will encounter when implementing management logic. We will walk through the WCF tools available that can deliver far more efficient and productive outcomes with only a configuration file switch.

Example. Altering the TradeService.cs Code
using System;
using System.ServiceModel;

namespace ExchangeService
{
    [ServiceContract(
        Namespace = "http://PracticalWcf/Exchange/TradeService",
        Name = "TradeService")
    ]
    public interface ITradeService
    {
        [OperationContract]
        double TradeSecurity(string ticker, int quantity);
    }
    public class TradeService : ITradeService, ITradeMonitor
    {
        //Same code as Example 4, Chapter 4

        public string StartMonitoring(string ticker)
						         {
						             lock (this)
						             {
						                 // Start the monitoring process here. In other words, you can
						                 // configure this function to start a manual log file
						                 // or send information to the event log. For this example, we are
						                 // returning a string to indicate the monitoring has commenced.
						                 return "Monitoring has started for " + ticker;
						            }
						         }

         public string StopMonitoring(string ticker)
						         {
						             lock (this)
						             {
						                 // End the monitoring process here.
						                  return "Monitoring has finished for " +ticker;
						             }
						         }
    }//end of TradeService Class
}//end of Namespace

In this code, you have implemented the ITradeMonitor interface in TradeService.cs and will display a message and the ticker name as the functionality of these methods. Traditionally, developers utilized this mechanism to create log files, implement auditing, and enable trace information. The WCF service is operational now, so let's try to host it (refer to Chapter 5 for detailed descriptions on various hosting options in WCF).

As mentioned, we will show how to utilize the self-hosting option for this example. Therefore, create a new console project (select File Add New Project Console Application) called TradeServiceHost, and add it to the WCFManagement solution. Rename the program.cs file to host.cs. You will need to add a reference to the ExchangeService project and add a reference to the System.ServiceModel namespace. Listing 6-3 illustrates the code for host.cs.

Example. Self-Hosting Code
using System;
using System.Collections.Generic;
using System.ServiceModel;
using System.Text;

namespace ExchangeService
{
    public class Program
    {
        public static void Main(string[] args)
        {
            using (ServiceHost host = new ServiceHost(typeof(
                 TradeService),
                 new Uri[] { new Uri("http://localhost:8000/") }))
            {
                host.Open();
                Console.WriteLine("The WCF Management trading
                    service is available.");
                Console.ReadKey();
            }
        }
    }
}

In this code, you are creating a WCF self-hosted service on port 8000 on the localhost machine. You display a message indicating the service is functioning after you start the host with the host.Open() method. You also need to add the endpoints for ITradeService and ITradeMonitor. Both these endpoints will use wsHttpBinding as the preferred binding mechanism.

Next, you need to detail this information in the App.config file. You can add App.config by right-clicking the solution and choosing Add New Item. Listing 6-4 shows the code for App.config.

Example. Configuration File for host.cs
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
      <services>
       <service name="ExchangeService.TradeService"
              behaviorConfiguration="returnFaults">
         <endpoint address="http://localhost:8000/TradeService"
						              binding="basicHttpBinding"
						          contract="ExchangeService.ITradeService" />
						        <endpoint address=http://localhost:8000/TradeMonitor
						           binding="wsHttpBinding"
						          contract="ExchangeService.ITradeMonitor" />
       </service>
      </services>
      <behaviors>
       <serviceBehaviors>
        <behavior name="returnFaults">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug httpHelpPageEnabled="true"
              includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>

Now you'll concentrate on the client that consumes these services. You will reuse the WCFSimpleClient project from Example04 from Chapter 4. You will alter the code to implement the ITradeMonitor interface and utilize the StartMonitoring and EndMonitoring code. You need to right-click the solution file and select the Add Project option to achieve this. You will also need to add references to System.SystemModel and System.Runtime.Serialiation. Listing 6-5 shows the client code.

Example. Client Code for the Trade Service
ITradeService proxy = new System.ServiceModel.ChannelFactory
    <ITradeService>("TradeServiceConfiguration").CreateChannel();
ITradeMonitor monitor = new System.ServiceModel.ChannelFactory
						    <ITradeMonitor>("TradeMonitorConfiguration").CreateChannel();
Console.WriteLine( "
Trade IBM" );
    Console.WriteLine(monitor.StartMonitoring("IBM"));
double result = proxy.TradeSecurity( "IBM", 1000 );
Console.WriteLine( "Cost was " + result );
    Console.WriteLine(monitor.StopMonitoring("IBM"));

Finally, you need to add the configuration code for the client, as shown in Listing 6-6.

Example. Client Configuration Settings for the Trade Service
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.serviceModel>
    <client>
      <endpoint name="TradeServiceConfiguration"
            address="http://localhost:8000/TradeService"
            binding="wsHttpBinding"
          contract="ExchangeService.ITradeService"/>
      <endpoint name="TradeMonitorConfiguration"
            address="http://localhost:8000/TradeMonitor"
            binding="wsHttpBinding"
          contract="ExchangeService.ITradeMonitor"/>
    </client>
  </system.serviceModel>
</configuration>

Now you are ready to test your new monitoring code, so right-click the solution file, and select Build All. Start the service, browse to the Bindebug directory of the TradeServiceHost project, and double-click TradeServiceHost.exe. You should see the screen shown in Figure 6-3.

TradeServiceHost running

Let's execute the client now. Browse to the Bindebug directory of the WCFSimpleClient project, and execute WCFSimpleClient.exe. You should see the screen shown in Figure 6-4.

TradeServiceClient running

As you can probably gather, creating custom code to manage a web service is a tedious task. You should also not discount the developer effort that goes into creating these modules. You can use the same time and effort to solve more business problems (as opposed to building a custom framework that manages services). You probably are saying now, "There must be a better way to do these monitoring activities. There must be better tools to utilize my time and effort. What does WCF offer?"

We believe that one of the most appealing features about WCF is its management functionality. It is safe to say that with Microsoft service offerings, WinFx and WCF will have the greatest breath and depth when they address the management of services. The management is one of the key features that really sells WCF. Therefore, what do you have in WCF to assist you?

  • Using configuration files

  • Using tracing functionality

  • Using message logging

  • Using performance monitors—both built-in WCF counters and custom-made counters

  • Implementing WMI

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

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