Partager via


Task 2: Create the Default Page

This task describes how to add the Default.aspx page. This page has two sections: the upper section allows the user to enter new loan requests (starting new workflow instances); the lower section allows the user to send messages to running workflows.

The upper section of the page consists of two textbox controls and a button; the button executes code that creates a new workflow instance, passing in the contents of the textboxes as parameters. After the new workflow is started, it enters tracking data to the database to record that it has begun. The workflow then waits for input from the application; this causes the workflow runtime to unload and persist the workflow.

The lower section of the page lists workflows that the workflow runtime knows about, using a tracking query. If running or completed workflows are found, they are listed in a datagrid control, along with buttons to accept or reject the requests (sending messages to the corresponding workflow).

Note

There is a small delay for tracking data to reach the database, due to batching; this delay is usually longer than it takes for the page to process. As a result, new workflows and changes to workflow status do not show up in the datagrid control immediately; press the Refresh button after a few seconds to refresh the page and get the latest workflow information.

To add the Default page to the Web site

  1. Right-click the Web site in Solution Explorer, and select Add New Item… Select Web Form, and click Add. This adds the default Web page to the site.

  2. Replace the code in the Default.aspx file with the following. This code includes the Web controls used to create and interact with workflows, as well as layout and formatting information.

    <%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" EnableViewState="false" %>
    <!--
    //---------------------------------------------------------------------
    //  This file is part of the Windows Workflow Foundation SDK Code Samples.
    // 
    //  Copyright (C) Microsoft Corporation.  All rights reserved.
    // 
    //This source code is intended only as a supplement to Microsoft
    //Development Tools and/or on-line documentation.  See these other
    //materials for detailed information regarding Microsoft code samples.
    // 
    //THIS CODE AND INFORMATION ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY
    //KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
    //IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
    //PARTICULAR PURPOSE.
    //---------------------------------------------------------------------
    //-->
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head id="Head1" runat="server">
        <title>Untitled Page</title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
        <!-- <snippet_ASPNETTEST> -->
        <asp:Label runat="server" ID="LabelConsole" ForeColor="Red" />
        <!-- </snippet_ASPNETTEST> -->
        <h1>Request New Loan</h1>
        <table>
          <tr>
            <td>Applicant Name:</td>
            <td><asp:TextBox ID="TextApplicantName" runat="server" /></td>
          </tr>
          <tr>
            <td>Loan Amount:</td>
            <td><asp:TextBox ID="TextLoanAmount" runat="server" /></td>
          </tr>
          <tr>
            <td colspan="2" align="center"><asp:Button ID="ButtonRequestLoan" runat="server" text="Submit Request" OnClick="ButtonRequestLoan_Click" /></td>
          </tr>
        </table>
    
        <hr />
        <h1>Approve Loan Requests</h1>
        <asp:DataGrid ID="DataGridLoanRequests" AutoGenerateColumns="False" runat="server" OnItemCommand="DataGridLoanRequests_ItemCommand" >
            <Columns>
                <asp:BoundColumn DataField="Workflow ID" HeaderText="Workflow ID"></asp:BoundColumn>
                <asp:BoundColumn DataField="Applicant Name" HeaderText="Applicant Name"></asp:BoundColumn>
                <asp:BoundColumn DataField="Loan Amount" HeaderText="Loan Amount"></asp:BoundColumn>
                <asp:BoundColumn DataField="Loan Status" HeaderText="Loan Status"></asp:BoundColumn>
                <asp:ButtonColumn ButtonType="PushButton" Text="Approve" CommandName="Approved"></asp:ButtonColumn>
                <asp:ButtonColumn ButtonType="PushButton" Text="Reject" CommandName="Rejected"></asp:ButtonColumn>
            </Columns>
        </asp:DataGrid>
        <asp:Label ID="LabelNoRequests" Visible="false" ForeColor="Red" runat="server" >No loan requests found.</asp:Label>
        <p />
        <asp:Button ID="ButtonRefresh" Text="Refresh" runat="server" />
        </div>
        </form>
    </body>
    </html>
    
  3. Replace the code in the Default.aspx.cs or Default.aspx.vb file with the following. The default code file contains functionality for starting workflows, displaying information about the workflows, and interacting with running workflows.

    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Data;
    using System.Data.SqlClient;
    using System.Web.UI.WebControls;
    using System.Workflow.Activities;
    using System.Workflow.Runtime;
    using System.Workflow.Runtime.Hosting;
    using System.Workflow.Runtime.Tracking;
    
    using WorkflowLibrary;
    
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //List existing loan requests
    
            // Obtain Workflow Runtime from application object
            WorkflowRuntime workflowRuntime = (WorkflowRuntime)Application["WorkflowRuntime"];
    
            // Obtain list of workflows
            String connectionString = ConfigurationManager.ConnectionStrings["LocalConnection"].ConnectionString;
            SqlTrackingQuery trackingQuery = new SqlTrackingQuery(connectionString);
            SqlTrackingQueryOptions options = new SqlTrackingQueryOptions();
            IList<SqlTrackingWorkflowInstance> workflows;
            try
            {
                workflows = trackingQuery.GetWorkflows(options);
            }
            catch (SqlException ex)
            {
                LabelConsole.Text = String.Format("A SQL exception occurred.  Details:<br>{0}", ex.Message);
                return;
            }
    
            if (workflows.Count == 0)
            {
                LabelNoRequests.Visible = true;
                return;
            }
            else
                LabelNoRequests.Visible = false;
    
            // Create data view to bind datagrid
            DataTable workflowData = new DataTable();
            workflowData.Columns.Add("Workflow ID");
            workflowData.Columns.Add("Applicant Name");
            workflowData.Columns.Add("Loan Amount");
            workflowData.Columns.Add("Loan Status");
    
            foreach (SqlTrackingWorkflowInstance workflow in workflows)
            {
                // Figure out loan info based on tracking data
                String loanStatus = "Pending";
                String applicantName = "";
                String loanAmount = "";
                try
                {
                    foreach (UserTrackingRecord trackingData in workflow.UserEvents)
                    {
                        String data = (String)trackingData.UserData;
                        LoanEventTrackingData key = (LoanEventTrackingData)(Enum.Parse(typeof(LoanEventTrackingData), trackingData.UserDataKey));
                        switch (key)
                        {
                            case LoanEventTrackingData.ApplicantName:
                                applicantName = data;
                                break;
                            case LoanEventTrackingData.LoanAmount:
                                loanAmount = data;
                                break;
                            case LoanEventTrackingData.Approved:
                                loanStatus = data;
                                break;
                        }
                    }
                    workflowData.Rows.Add(
                        new object[] {
                        workflow.WorkflowInstanceId.ToString(),
                        applicantName,
                        loanAmount,
                        loanStatus });
                }
                catch (InvalidOperationException ex)
                {
                    LabelConsole.Text = String.Format("There was a problem getting tracking information for a workflow.  Details:<br>{0}", ex.Message);
                }
            }
            DataView workflowDataView = new DataView(workflowData);
            DataGridLoanRequests.DataSource = workflowDataView;
            DataGridLoanRequests.DataBind();
        }
        protected void ButtonRequestLoan_Click(object sender, EventArgs e)
        {
            // Obtain Workflow Runtime from application object
            WorkflowRuntime workflowRuntime = (WorkflowRuntime)Application["WorkflowRuntime"];
    
            // Obtatin scheduler service from Workflow Runtime
            ManualWorkflowSchedulerService schedulerService = workflowRuntime.GetService<ManualWorkflowSchedulerService>();
    
            // Create parameter collection from website
            Dictionary<String, Object> parameters = new Dictionary<string, object>();
            parameters.Add("ApplicantName", TextApplicantName.Text);
            parameters.Add("LoanAmount", TextLoanAmount.Text);
    
            // Create and start new workflow
            WorkflowInstance workflowInstance = workflowRuntime.CreateWorkflow(typeof(LoanApprovalWorkflow), parameters);
            workflowInstance.Start();
            schedulerService.RunWorkflow(workflowInstance.InstanceId);
        }
        protected void DataGridLoanRequests_ItemCommand(object source, DataGridCommandEventArgs e)
        {
            // Obtain Workflow Runtime from application object
            WorkflowRuntime workflowRuntime = (WorkflowRuntime)Application["WorkflowRuntime"];
    
            // Obtain communication service 
            WorkflowLibrary.LoanEventService eventService = workflowRuntime.GetService<LoanEventService>();
    
            // Obtain scheduler service
            ManualWorkflowSchedulerService schedulerService = workflowRuntime.GetService<ManualWorkflowSchedulerService>();
    
            // Obtain workflow ID from datagrid
            Guid workflowId = new Guid(e.Item.Cells[0].Text);
    
            // Call event
            try
            {
                eventService.RaiseApproved(e.CommandName, workflowId);
            }
            catch (EventDeliveryFailedException)
            {
                LabelConsole.Text = "That loan has already been approved or rejected.";
                return;
            }
    
            // Manually resume workflow
            schedulerService.RunWorkflow(workflowId);
    
        }
    }
    

See Also

Concepts

Querying SqlTrackingService Data With SqlTrackingQuery

Copyright © 2007 by Microsoft Corporation. All rights reserved.
Last Published: 2010-03-04