Share via


How to: Use Health Monitoring to Instrument a WCF Service for Security

patterns & practices Developer Center

Applies to

  • Microsoft Windows Communication Foundation (WCF) 3.5
  • Microsoft Visual Studio 2008

Summary

This how-to article walks you through the process of configuring a WCF service for health monitoring in order to instrument a custom event. The article shows you how to create a custom Web event, configure a WCF service for health monitoring, instrument a WCF service for security events, and create a test client application to verify the events in the Event Log.

Contents

  • Objectives
  • Overview
  • Summary of Steps
  • Step 1: Create a Custom Web Event
  • Step 2: Create a WCF Service for Monitoring
  • Step 3: Configure Your WCF Service for Health Monitoring
  • Step 4: Instrument Your WCF Service
  • Step 5: Create a Test Client
  • Step 6: Add a WCF Service Reference to the Client
  • Step 7: Test the Client and WCF Service
  • Step 8: Verify the Service Events in the Event Log
  • Additional Resources

Objectives

  • Learn how to create a custom Web event.
  • Learn how to configure a WCF service for health monitoring.
  • Learn how to instrument a WCF service.

Overview

The health monitoring feature in WCF supports many standard events that you can use to check the health of your WCF service. This feature supports an event provider model. It allows you to instrument your WCF service and monitors user management events around authentication and authorization. You can track access to sensitive operations such as financial transactions or access to sensitive data by using the health monitoring feature to detect and react to potentially suspicious behavior.

This article shows you how to create a custom Web event in a class library project in Visual Studio 2008. You will then create a sample WCF service project and configure the service to use the health monitoring feature. Next, you will instrument the service by raising the custom event. Finally, you will create an ASP.NET test client project to verify the security events in the Event Log by invoking the custom event.

Summary of Steps

  • Step 1: Create a Custom Web Event
  • Step 2: Create a WCF Service for Monitoring
  • Step 3: Configure Your WCF Service for Health Monitoring
  • Step 4: Instrument Your WCF Service
  • Step 5: Create a Test Client
  • Step 6: Add a WCF Service Reference to the Client
  • Step 7: Test the Client and WCF Service
  • Step 8: Verify the Service Events in the Event Log

Step 1: Create a Custom Web Event

In this step, you create a custom Web event by creating a class that inherits from System.Web.Management.WebAuditEvent.

  1. In Visual Studio, on the File menu, click New Project.

  2. In the Templates section, select Class Library. Specify the name of the project and the location to be created in the Path (e.g., C:/Projects/MyEventLibrary).

  3. In the New Project dialog box, click OK to create a Class Library project and sample class file named Class1.cs.

  4. Rename Class1.cs as MyEvent.cs.

  5. Add a reference to your new project to System.Web and then add the System.Web.Management namespace to the top of MyEvent.cs.

  6. Derive MyEvent from WebAuditEvent and create appropriate public constructors that call the protected equivalents in the parent WebAuditEvent class, as follows:

    using System.Web.Management;
    
     public class MyEvent : WebAuditEvent
        {
    
            public MyEvent(string msg, object eventSource, int eventCode)
                : base(msg, eventSource, eventCode)
            {
            }
    
            public MyEvent(string msg, object eventSource, int eventCode, int eventDetailCode)
                : base(msg, eventSource, eventCode, eventDetailCode)
            {
            }
    
  7. To log some custom details, override the FormatCustomEventDetails method as follows:

       public override void FormatCustomEventDetails(WebEventFormatter formatter)
            {
                base.FormatCustomEventDetails(formatter);
    
                // Add some custom data.
                formatter.AppendLine("");
                formatter.IndentationLevel += 1;
                formatter.AppendLine("******** SampleWebAuditEvent Start ********");
    
                formatter.AppendLine(string.Format("Request path: {0}",
                    RequestInformation.RequestPath));
    
                formatter.AppendLine(string.Format("Request Url: {0}",
                    RequestInformation.RequestUrl));
    
                // Display some custom event message
                formatter.AppendLine("Some Critical Event Fired");
    
                formatter.AppendLine("******** SampleWebAuditEvent End ********");
    
                formatter.IndentationLevel -= 1;
            }
    
  8. Build the assembly by compiling the project.

Step 2: Create a WCF Service for Monitoring

In this step, you create a WCF service in Visual Studio.

  1. In Visual Studio, on the File menu, click New Web Site.

  2. In the Templates section, select WCF Service. Make sure that the Location is set to Http and specify the virtual directory to be created in the Path (e.g., https://localhost/HMWCFService).

  3. In the New Web Site dialog box, click OK to create a virtual directory and a sample WCF service.

  4. Browse to your WCF service (i.e., https://localhost/HMWCFService/Service.svc).

    You should see details of your WCF service.

Step 3: Configure Your WCF Service for Health Monitoring

In this step, you configure the WCF service to use health monitoring. You can configure your application to use any of the three default providers. For this exercise, you will use the EventLogWebEventProvider, which uses the EventLogWebEventProvider class to write entries to the Windows application Event Log.

  • In the Web.config file of your service application, add the following code, which specifies the event mapping and the rules for using the EventLogProvider for the custom event type MyEventLibrary.MyEvent.

    …
    <system.web>
    <healthMonitoring>
    <eventMappings>
    <add name="Some Custom Event" type="MyEventLibrary.MyEvent, MyEventLibrary"/>
    </eventMappings>
    <rules>
    <add name="Custom event" eventName="Some Custom Event" provider="EventLogProvider" minInterval="00:00:01"/>
    </rules>
    </healthMonitoring>
    </system.web>
    …
    

Step 4: Instrument Your WCF Service

In this step, you instrument your WCF service to raise custom events.

  1. In the Solution Explorer, select the WCF Service project and add a reference to the Class Library project created in step1.

  2. Expand the App_Code folder, open IService.cs, and add the following operation contract:

        [OperationContract]
        string InvokeCriticalEvent();
    
  3. Add a reference to System.Web and then add the System.Web.Management namespace to the top of Service.cs as follows:

    using CustomEvents;
    using System.Web.Management;
    
  4. Implement the above contract by creating a new custom event object of type MyEvent and calling its Raise method to fire the event as follows:

       public string InvokeCriticalEvent()
        {
            MyEvent obj = new MyEvent("Invoking Some Custom Event", this, WebEventCodes.WebExtendedBase + 1);
            obj.Raise();
            return "Critical event invoked";
        }
    
  5. Compile the WCF service project and test the service.

Note

When you raise a custom Web event, you must specify an event code that is greater than System.Web.Management.WebEventCodes.WebExtendedBase. Codes that are less than this value are reserved for system-generated events.

Step 5: Create a Test Client

In this step, you create an ASP.NET application to monitor your WCF service.

  1. In the Solution Explorer, right-click your solution and then click New Website.
  2. In the Templates section, select ASP.NET Website. Make sure that the Location is set to Http and specify the virtual directory to be created in the Path (e.g., https://localhost/HMWCFService).
  3. In the New Web Site dialog box, click OK to create a virtual directory and a sample ASP.NET Web site.

Step 6: Add a WCF Service Reference to the Client

In this step, you add a reference to your WCF service.

  1. Right-click your ASP.NET client application and then click Add Service Reference.

  2. In the Add Service Reference dialog box, set the URL to your WCF service, (e.g, https://localhost/HMWCFService/Service.svc) and then click Go.

  3. In the Web reference name field, change ServiceReference1 to HMWCFService.

  4. Click Add Reference.

    A reference to HMWCFService should appear beneath Web References in your client project.

Step 7: Test the Client and WCF Service

In this step, you access the WCF service and invoke the custom event.

  1. In your ASP.NET test application project, drag a button control onto your Web form.

  2. Double-click the button control to show the underlying code.

  3. Create an instance of the proxy, and then call the InvokeCriticalEvent operation of your WCF service. The code should look as follows:

    protected void button1_Click(object sender, EventArgs e)
    {
          HMWCFService.ServiceClient myService = new
                        HMWCFService.ServiceClient();
          Response.Write(myService.InvokeCriticalEvent());
          myService.Close();
    }
    
  4. Right-click the client project and then click Set as Startup Project.

  5. Run the client application by pressing F5 or CTRL+F5. When you click the button on the form, the message “Critical event invoked” should appear.

Step 8: Verify the Service Events in the Event Log

In this step, you verify the WCF service events in the application Event Log.

  1. On your Service host machine, click Start and then click Run.

  2. In the command line, type eventvwr and then click OK to open the Event Viewer window.

  3. In the left pane, select the Application node to view a list of application events in the right pane.

  4. In the list, search for the latest event. You will see an event of Web Event category, ASP.NET <<version no>> source, and Information type.

  5. Open the event and view the following information, which appends your custom message event:

    Event code: 100001 
    Event message: Invoking Some Custom Event
    Event time: 3/31/2008 10:55:42 AM 
    Event time (UTC): 3/31/2008 5:25:42 AM 
    Event ID: 1515c05420ea46e189f83e1550cb1f8a 
    Event sequence: 10 
    Event occurrence: 2 
    Event detail code: 0 
    
    Application information: 
    …
    Process information: 
    …
    
    Request information: 
    …
    Custom event details: 
    

******* SampleWebAuditEvent Start ******* Request path: /Health/Default.aspx Request Url: https://localhost/HMWCFService/Default.aspx Password changed ******* SampleWebAuditEvent End *******

Additional Resources