Hosting Workflow Applications in Microsoft Windows Workflow Foundation 4.0

Exclusive offer: get 50% off this eBook here
Microsoft Windows Workflow Foundation 4.0 Cookbook

Microsoft Windows Workflow Foundation 4.0 Cookbook — Save 50%

Over 70 recipes with hands-on, ready to implement solutions for authoring Microsoft Windows Workflow Foundation 4.0 workflows with this book and eBook

$29.99    $15.00
by Andrew Zhu | October 2010 | Cookbooks Enterprise Articles Microsoft

In this article, by Andrew Zhu, author of Microsoft Windows Workflow Foundation 4.0 we will cover:

  • Hosting a workflow service in IIS7
  • Hosting workflow in ASP.NET
  • Hosting workflow in WPF
  • Hosting workflow in a Windows Form

 

Microsoft Windows Workflow Foundation 4.0 Cookbook

Microsoft Windows Workflow Foundation 4.0 Cookbook

Over 70 recipes with hands-on, ready to implement solutions for authoring workflows

  • Customize Windows Workflow 4.0 applications to suit your needs
  • A hands-on guide with real-world illustrations, screenshots, and step-by-step instructions
  • Explore various functions that you can perform using WF 4.0 with running code examples
  • A hands-on guide with real-world illustrations, screenshots, and step-by-step instructions

 

Read more about this book

(For more resources on this subject, see here.)

Introduction

WF4 is one part of .NET Framework 4.0, which means WF4 workflow can be hosted and run in any type of application running with the .NET framework. We can host a workflow as a WCF service. We can also invoke a workflow service from a workflow or host workflow in an ASP.NET application and handle all the business logic behind the page.

When we design workflow applications, please let workflow be workflow. Don't couple workflow with other logic. For example, in this chapter, hosting workflow in ASP.NET is for conception demonstration only, not the best practice. In the real world, most of the time, workflow should be implemented as a workflow service hosted in IIS7 or AppFabric.

AppFabric is an IIS7 extension that includes many tools to help us host a workflow service. AppFabric is to workflow service like IIS7 is to ASP.NET website. However, we can run a workflow service in IIS7 without AppFabric installed. Although AppFabric is powerful, we need to spend some time to learn it. For more information about AppFabric, you can check this link: http://msdn.microsoft.com/appfabric

Hosting a workflow service in IIS7

The process of sending an e-mail would consume some time—maybe a few seconds or even minutes. It would be a waste of time and resources for our applications to stop and wait for an e-mail sending action to complete. Because sending e-mail is time-consuming, a better design is to strip this feature out as an independent WCF workflow service and host that service in IIS7.

Getting ready

We need the SendEmailActivity activity to send an e-mail.

How to do it...

  1. Create a WCF workflow service application:
    Create a WCF workflow service application and name it
    HostingWorkflowServiceInIIS7.

  2. Add SendEmailActivity to the toolbox:
    In the Toolbox tab, right-click and select Choose Items. In the opening dialog, click Browse and navigate to the ActivityLibrary.dll
  3. Click OK. We will find SendEmailActivity in the toolbox:

  4. Create a SendEmail workflow service:
    1. Delete Service1.xamlx, which is created by default, and add a new WCF workflow service to the project. Name it SendEmailService.xamlx. Drag a TransactedReceiveScope activity to the design panel, click the Variables button, and create a variable named emailMessage:
    2. Drag a Receive activity to the Request box of TransactedReceiveScope. Set the OperationName to SendEmail. Click the Content Definition link to create a parameter as shown here:
    3. Assign ISendEmailService to the ServiceContractName property. Check the CanCreateInstance property.
    4. Next, drag SendEmailActivity to the body of TransactedReceiveScope.
    5. Assign the following properties to SendEmailActivity:
    6. The final workflow will look as shown in the following screenshot:

  5. Create a website in IIS7 for this WF service:
    In IIS7 Manager Console, create a website and assign the website's physical path to the project folder of HostingWorkflowServiceInIIS7. Assign it a new port number. By default, an ASP.NET application will run under the built-in network service account (or ApplicationPoolIdentity in IIS7.5). This account has the most limited permissions. For testing, we can shift the application pool's identity to an administrator account.
  6. We should be able to find the following module and handlers in IIS7:

    If we cannot, then we should reinstall .NET framework 4.0 or repair it. Here are the repair commands:

    Repair command for 32-bit:

    .NET Framework 4 Full (32-bit) – silent repair %windir%\Microsoft.NET\Framework\v4.0.30319\SetupCache\Client\ setup.exe /repair /x86 /x64 /ia64 /parameterfolder Client /q /norestart

    Repair command for 64-bit:

    .NET Framework 4 Full (64-bit) – silent repair %windir%\Microsoft.NET\Framework64\v4.0.30319\SetupCache\Client\setup.exe /repair /x86 /x64 /ia64 /parameterfolder Client /q /norestart

  7. Use WCFTestClient.exe to test the WCF service:
    Usually, we can find the WCFTestClient.exe tool in C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE.

    We just need to open our mail. A new mail with subject Hello WF Service indicates that we have created and hosted the WF service successfully.

How it works...

Simply put, once we have set up the IIS7, we need to copy all the workflow service project files and folders to the IIS application folder and the workflow service will just work.

There's more

We can also host a WF4 service in IIS6 once we have installed .NET framework 4.0. Running a WF4 service in IIS6 is not recommended.

Hosting workflow in ASP.NET

In this task, we will create an e-mail sending workflow and run it in an ASP.NET site.

Getting ready

We need an e-mail sending workflow service hosted in IIS7.

How to do it...

Microsoft Windows Workflow Foundation 4.0 Cookbook Over 70 recipes with hands-on, ready to implement solutions for authoring Microsoft Windows Workflow Foundation 4.0 workflows with this book and eBook
Published: September 2010
eBook Price: $29.99
Book Price: $49.99
See more
Select your format and quantity:

Read more about this book

(For more resources on this subject, see here.)

  1. Create an ASP.NET4 web application:
    Create an ASP.NET4 web application and name it HostingWorkflowInASPNET. Because we are going to host WF4 workflow in this website, we have to make sure it is an ASP.NET4 website. To check the version, right-click the project name HostingWorkflowInASPNET and select Properties.
  2. Author a Workflow:
    1. Add an activity to the website and name it Workflow.xaml.
      Author the workflow as follows:

    2. Set the properties for SendEmail1:

    3. Set the parameters for SendEmail1:
    4. Set the properties of SendEmail2. The only difference as compared to SendEmail1 is the DisplayName.

    5. Set the parameters for SendEmail2:

  3. Alter the Default.aspx page:
    Add a Button control to the Default.aspx page:

    <%@ Page Title="Home Page"
    Language="C#"
    MasterPageFile="~/Site.master"
    AutoEventWireup="true"
    CodeBehind="Default.aspx.cs"
    Inherits="HostingWorkflowInASPNET._Default" %>
    <asp:Content ID="HeaderContent" runat="server"
    ContentPlaceHolderID="HeadContent">
    </asp:Content>
    <asp:Content ID="BodyContent" runat="server"
    ContentPlaceHolderID="MainContent">
    <p>
    <asp:Button ID="Button1" runat="server"
    Text="Start a workflow"
    onclick="Button1_Click" />
    </p>
    </asp:Content>

    Add this code to the button event handler in Default.aspx.cs:

    using System;
    using System.Activities;
    using System.Threading;
    namespace HostingWorkflowInASPNET {
    public partial class _Default : System.Web.UI.Page {
    protected void Page_Load(object sender, EventArgs e) {
    }
    protected void Button1_Click(object sender, EventArgs e) {
    AutoResetEvent waitHandler = new
    AutoResetEvent(false);
    WorkflowApplication wfApp =
    new WorkflowApplication(new Workflow());
    wfApp.Unloaded = (workflowApplicationEventArgs) => {
    waitHandler.Set();
    };
    wfApp.Run();
    waitHandler.WaitOne();
    }
    }
    }

  4. Run it:
    Build the website and browse to the default page:

    Click the Start a workflow button to start a workflow. Open your e-mail client. Two mails with subject Hello WF Service indicate we have finished this task successfully.

How it works...

We can treat a WF4 workflow as a managed .NET object and it can run in any .NET framework 4.0 application. If we have experience with WF3/3.5, we may still remember that we had to schedule the workflow instance in an ASP.NET application. In WF4, a WorkflowApplication workflow instance runs in an independent .NET thread. No special workflow schedule is needed.

There's more

As I have stated in the introduction of this chapter, usually we don't run a workflow instance in an ASP.NET page directly; instead, we call a WF4 service in page events. For example, in this task, we can call the WF4 service using pure .NET code by following these steps:

  1. Use Svcutil.exe to generate the proxy code and configuration code. Usually, if we have installed .NET 4.0 framework, we can find this Svcutil.exe in C:\ProgramFiles (x86)\Microsoft SDKs\Windows\v7.0A\Bin or C:\ProgramFiles\Microsoft SDKs\Windows\v7.0A\Bin.
  2. In a command window, navigate to the svcutil.exe folder using the following command:

    cd C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin

  3. Input the following command:

    svcutil.exe /language:cs /out:c:\GeneratedProxy.cs /config:c:\app.
    config http://localhost:8089/SendEmailService.xamlx.

    Press the Enter key, and we will find the GeneratedProxy.cs and app.config files in C:\.

  4. Add GeneratedProxy.cs to our ASP.NET web application.
  5. Open the app.config file and copy the following configuration code into the web.config file of the ASP.NET web application right below the &ltconfiguration> node:

    <system.serviceModel>
    <bindings>
    <basicHttpBinding>
    <binding name="BasicHttpBinding_ISendEmailService"
    closeTimeout="00:01:00"
    openTimeout="00:01:00"
    receiveTimeout="00:10:00" sendTimeout="00:01:00"
    allowCookies="false"
    bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
    maxBufferSize="65536"
    maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
    messageEncoding="Text" textEncoding="utf-8"
    transferMode="Buffered"
    useDefaultWebProxy="true">
    <readerQuotas maxDepth="32"
    maxStringContentLength="8192" maxArrayLength="16384"
    maxBytesPerRead="4096"
    maxNameTableCharCount="16384" />
    <security mode="None">
    <transport clientCredentialType="None"
    proxyCredentialType="None"
    realm="">
    <extendedProtectionPolicy
    policyEnforcement="Never" />
    </transport>
    <message clientCredentialType="UserName"
    algorithmSuite="Default" />
    </security>
    </binding>
    </basicHttpBinding>
    </bindings>
    <client>
    <endpoint address="http://localhost:8089/
    SendEmailService.xamlx"
    binding="basicHttpBinding" bindingConfiguration="B
    asicHttpBinding_ISendEmailService"
    contract="ISendEmailService"
    name="BasicHttpBinding_ISendEmailService" />
    </client>
    </system.serviceModel>

  6. Use the following code to call the workflow service:

    SendEmailServiceClient sesc = new SendEmailServiceClient();
    sesc.SendEmail("message");

Microsoft Windows Workflow Foundation 4.0 Cookbook Over 70 recipes with hands-on, ready to implement solutions for authoring Microsoft Windows Workflow Foundation 4.0 workflows with this book and eBook
Published: September 2010
eBook Price: $29.99
Book Price: $49.99
See more
Select your format and quantity:

Read more about this book

(For more resources on this subject, see here.)

Hosting workflow in WPF

In this task, we will create a workflow running in a WPF application.

How to do it...

  1. Create a WPF project:
    Create a WPF project and name it HostingWorkflowInWPF.
  2. Create a workflow:
    Add a workflow to the project named AdditionWorkflow.xaml and author a workflow like this:

  3. Create a WPF window:
    Open the default created WPF file MainWindow.xaml. Alter its contents to:

    <Window x:Class="HostingWorkflowInWPF.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/
    presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="160" Width="200">
    <Grid Width="180" HorizontalAlignment="Left"
    VerticalAlignment="Top" Height="124">
    <Label Content="x:" Width="20"
    HorizontalAlignment="Left" Name="LabelX"
    Margin="0,2,0,0" VerticalAlignment="Top" />
    <TextBox Name="textBoxX" Width="80"
    Height="20" VerticalAlignment="Top"
    HorizontalAlignment="Left" Margin="52,4,0,0" />
    <Label Content="y:" HorizontalAlignment="Left"
    Margin="0,26,0,0" Name="labelY"
    Width="20" Height="30"
    VerticalAlignment="Top" />
    <TextBox Height="20" HorizontalAlignment="Left"
    Margin="52,28,0,0" Name="textBoxY"
    VerticalAlignment="Top" Width="80" />
    <Button Content="Adding" Height="23"
    HorizontalAlignment="Left" Margin="52,54,0,0"
    Name="buttonAdding" VerticalAlignment="Top"
    Width="75" Click="buttonAdding_Click" />
    <Label Content="result:" Height="28"
    HorizontalAlignment="Left" Margin="0,83,0,0"
    Name="labelResult" VerticalAlignment="Top" />
    <Label Height="28" HorizontalAlignment="Left"
    Margin="52,83,0,0" Name="labelResultValue"
    VerticalAlignment="Top" />
    </Grid>
    </Window>

    We can see this in the WPF window designer:

    Double-click the Adding button, and add code to the button event handler. The final MainWindow.xaml.cs code will be:

    using System.Windows;
    using System.Threading;
    using System.Activities;
    using System;
    namespace HostingWorkflowInWPF {
    public partial class MainWindow : Window {
    public MainWindow() {
    InitializeComponent();
    }
    private void buttonAdding_Click(object sender, RoutedEventArgs e)
    {
    AutoResetEvent waitHandler = new
    AutoResetEvent(false);
    string result = "";
    AdditionWorkflow addwf = new AdditionWorkflow {
    x = new InArgument<Int32>(Int32.
    Parse(textBoxX.Text)),
    y = new InArgument<Int32>(Int32.
    Parse(textBoxY.Text))
    };
    WorkflowApplication wfApp = new
    WorkflowApplication(addwf);
    wfApp.Completed =
    (workflowApplicationCompletedEventArgs) => {
    result = workflowApplicationCompletedEventArgs.
    Outputs["result"].ToString();
    };
    wfApp.Unloaded = (workflowApplicationEventArgs) => {
    waitHandler.Set(); };
    wfApp.Run();
    waitHandler.WaitOne();
    labelResultValue.Content = result;
    }
    }
    }

  4. Run it:
    Set this project as StartUp project. Press Ctrl+F5 to run the workflow without debugging. Now we shall see the following:

How it works...

This task is only for the purpose of concept demonstration. In a real application, it is not a good idea to host a workflow in a WPF application. It would be better to host the workflow in IIS and call it in the WPF application like we did in the previous ASP.NET web application.

Hosting workflow in a Windows Form

In this task we will create a workflow running in a Windows Form application.

How to do it...

  1. Create a Windows Form project:
    Create a Windows Form project and name it HostingWorkflowInWinForm.
  2. Create a workflow:
    Add a workflow to the project and call it AdditionWorkflow.xaml. Author the workflow like this:

  3. Create a Windows Form.
    Open the default created Form1.cs file and alter it to:

    Double-click the Adding button and add code to the button event handler. The final code will be:

    using System;
    using System.Windows.Forms;
    using System.Threading;
    using System.Activities;
    namespace HostingWorkflowInWinForm {
    public partial class Form1 : Form {
    public Form1() {
    InitializeComponent();
    }
    private void buttonAdding_Click(object sender,
    EventArgse) {
    AutoResetEventwaitHandler =
    newAutoResetEvent(false);
    string result = "";
    AdditionWorkflowaddwf =
    new AdditionWorkflow {
    x = new InArgument<Int32>(
    Int32.Parse(textBoxX.Text.ToString())),
    y = new InArgument<Int32>(
    Int32.Parse(textBoxY.Text.ToString()))
    };
    WorkflowApplicationwfApp =
    newWorkflowApplication(addwf);

    wfApp.Completed =
    (workflowApplicationCompletedEventArgs) => {

    result = workflowApplicationCompletedEventArgs.Outputs["result"].
    ToString();
    };
    wfApp.Unloaded = (workflowApplicationEventArgs) => {

    waitHandler.Set();
    };
    wfApp.Run();
    waitHandler.WaitOne();
    labelResultValue.Text = result;
    }
    }
    }

  4. Run it:
    Set this project as StartUp project and press Ctrl+F5 to run this project without debugging. We shall see the following:

How it works...

This task is only for the purpose of concept demonstration. In a real application, it is not a good idea to host a workflow in a Windows Form application. It would be better to host the workflow in IIS and call it from a Win Form application like we did in the previous ASP.NET web application.

Summary

In the above article we have covered:

  • Hosting a workflow service in IIS7
  • Hosting workflow in ASP.NET
  • Hosting workflow in WPF
  • Hosting workflow in a Windows Form

Further resources on this subject:


About the Author :


Andrew Zhu

Andrew Zhu is a technology support engineer at Microsoft (Microsoft Globe Tech Support Center) in Shanghai. Over the past few years, he has helped developers and his customers to develop WF, BizTalk, IIS, and ASP.NET applications.

Books From Packt


Microsoft Dynamics GP 2010 Cookbook
Microsoft Dynamics GP 2010 Cookbook

Microsoft Dynamics NAV 2009 SP1 Programming Cookbook
Microsoft Dynamics NAV 2009 SP1 Programming Cookbook

Microsoft Silverlight 4 and SharePoint 2010 Integration
Microsoft Silverlight 4 and SharePoint 2010 Integration

Microsoft Enterprise Library 5.0
Microsoft Enterprise Library 5.0

NHibernate 3.0 Cookbook
NHibernate 3.0 Cookbook

Refactoring with Microsoft Visual Studio 2010
Refactoring with Microsoft Visual Studio 2010

Microsoft Dynamics AX 2009 Administration
Microsoft Dynamics AX 2009 Administration

Microsoft Windows Communication Foundation 4.0 Cookbook for Developing SOA Applications
Microsoft Windows Communication Foundation 4.0 Cookbook for Developing SOA Applications


Your rating: None Average: 5 (1 vote)
no email was sent by
I followed the steps but no email was sent. The WCFTestService worked. I wrote my own EmailActivity which works in a console application. What else could be wrong?

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
b
1
5
3
B
3
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software