Wednesday, May 27, 2009

Creating WindowsEventLogger Custom Workflow Activity In WF 4.0

We will end up creating a custom workflow activity when we won't find in WF 4.0 designer  Toolbox.

Here i am going to create Custom Workflow Activity which logs the Message into Windows EventViewr.  This custom activity can be used for many purpose like Logging Error, Information message into Windows Event viewer. 

First we need  create a Activity Library Project..


After creating new Activity  Library  project add the  Workflow Element Template to the newly created project.


Note: This custom activity is code only activity so the  SreeniWindowsEventLogger   is inherited  from CodeActivity .

SreeniWindowsEventLogger  Custom Activity class derived from CodeActivity  class as shown below. Next we need to add public Property which takes string as a Message and write to the Windows Event Log.

namespace SreeniWindowsEventLogger
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;
using System.Diagnostics;
using System.ComponentModel;

public class SreeniWindowsEventLogger :
public string Message { get; set; }
protected override void Execute(CodeActivityContext context)
EventLog.WriteEntry("Application", Message);
Now I am going to Add Activity Designer for my WindowsEventLogger so that it looks nice when we use it in other workflow applications.


Now we can use   XAML  to design our custom activity Look and feel.  this is really cool .


In this Activity designer inside the StackPanel  have added One Label and  TextBox where you can enter the message which you wanted to write in Windows Event Log when custom activity is executed..

<TextBox BorderBrush="Red" Margin="5" Height="30" Width="204" Text="{Binding Path=ModelItem.Message,Mode=TwoWay}"></TextBox>
Here I am binding TextBox Text property to the Message Property of the SreeniWindowsEventLogger class as shown above.

once you are done with XAML coding, now we need to  add  Designer Attribute to our Custom activity class as shown below. 

public class SreeniWindowsEventLogger : CodeActivity
Now Add new sequential console application workflow and add SreeniWindowsEventLogger  Reference project compile the project
you will see newly created custom activity in the ToolBox as shown here.
Now Drag and Drop the newly created custom activity and edit message property and press F5 to execute. 


The message we put in Custom activity was written to Windows event log .




1 comment:

swati said...

Great Article!!
Really useful..
I wanted to know how we can add the Web Reference in the Activity Libray Project.
Directly i can not see the option to add web reference.
Could you please help me on this..