Tuesday, April 27, 2010

Creating a LogError Activity

Surprisingly, in Visual Studio 2010 there is not an Activity in Windows Workflow Foundation (WF) 4.0 that writes an error to the Windows Event Log / Viewer. The good news is that it is very easy to write. Below are the instructions for creating one.

Step 1: Add new Code Activity

Add a new Code Activity called LogError to your Workflow project (This could be any of them, but I recommend putting your Activities in an Activity Library project.).

Step 2: Modify Code Activity to look similar to the following example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;
using System.Diagnostics;

namespace MyApp.MyActivities
{

public sealed class LogError : CodeActivity
{
// Define an activity input argument of type string
public InArgument<string> PreMessageText { get; set; }
public InArgument<Exception> Exception { get; set; }

protected override void Execute(CodeActivityContext context)
{
Log(PreMessageText.Get(context), Exception.Get(context));
}

public void Log(string preMessageText, Exception ex)
{
string sourceName = "My App";
string logName = "Application"; // i.e. System, Application , or other custom name

if (!EventLog.SourceExists(sourceName))
{
EventLog.CreateEventSource(sourceName, logName);
}

string message = string.Empty;
message += ex.Message + "\r\n";
message += ex.StackTrace;

EventLog.WriteEntry(sourceName, preMessageText + "\r\n" + message, EventLogEntryType.Error);

}
}
}

To use the Activity just compile your project. It will then show up in your Toolbox. You will probably want to drag a TryCatch Activity onto your workflow. Then drag the LogError Activity we created to the Exception section of the TryCatch Activity. Set the Exception property to the argument name in the Exception section.

No comments: