Integrating Mobile Client Applications with SharePoint 2010 Workflows

Summary:  Learn to integrate mobile devices with Microsoft SharePoint Server 2010. Learn to create a Windows Presentation Foundation (WPF) application that calls a Windows Communication Foundation (WCF) service to submit data into a SharePoint site and update the status of a custom SharePoint workflow.

Applies to: Business Connectivity Services | Office 2010 | Open XML | SharePoint Designer 2010 | SharePoint Foundation 2010 | SharePoint Online | SharePoint Server 2010 | Visual Studio

Provided by:  MVP ContributorTodd Baginski, SharePoint Server MVP, Aptillon

Contents

  • Integrating Client Applications with Business Processes

  • Introducing the Sample Scenario

  • Building the Mobile WPF Client Application

  • Creating the WCF Service

  • Deploying the Mobile Client Application and Other Components

  • Debugging the Solution Components

  • Conclusion

  • Additional Resources

Click to grab code  Download the sample code

Integrating Client Applications with Business Processes

Recently mobile devices have become more powerful and easy to use. Rugged laptops, netbooks, tablet PCs, and mobile phones are relied upon to provide workers access to the information and applications that they must have to do their jobs. Additionally, developing applications for mobile devices is now easier than ever. As a result, more and more often business scenarios demand integrating client applications together with business processes and workflows. This article is part of a series of articles that describe how to integrate client applications together with business processes and workflows:

Microsoft SharePoint Foundation 2010 and Microsoft SharePoint Server 2010 provide workflow capabilities that enable you to model business processes and integrate them with multiple applications and systems. You can create client applications to extend reach of the workflow and make it available outside the context of SharePoint sites. Creating client applications to access workflows in SharePoint sites requires a client application, networking (services), and integration with SharePoint lists and workflows.

Scenarios

The following scenarios are examples of using mobile devices with SharePoint workflows:

  • An insurance company that uses mobile applications to locate insured assets and file claim reports for customers.

  • A company with underground infrastructure, such as a telephone, electric, or cable company, that uses mobile applications to locate underground infrastructure and mark it to ensure it is not damaged during digging.

  • A water company that uses mobile applications to record how much water each customer uses.

  • A retail company which uses mobile applications as a point of sale application at outdoor events (concerts, sporting events, carnivals, etc).

As the previous scenarios show, the need for rich functionality, data access, and process integration in mobile applications is common. Creating mobile applications that integrate with SharePoint 2010 saves time developing mobile applications that meet these requirements.

This article focuses on integrating client applications together with the SharePoint framework, particularly showing how to read and write data from SharePoint lists to integrate with workflow processes.

Benefits

Extending SharePoint workflows beyond SharePoint sites in a web browser provides several benefits to workflow participants. The benefits include, but are not limited to the following items.

  • Interacting with workflows from a mobile client application (mobile access)

  • Reducing the steps to interact with a workflow

  • Enhancing the workflow process with rich data and functionality

  • Automating parts of the workflow process.

Components

You must create several components to integrate mobile client applications together with SharePoint workflows. These components include the computer that is running SharePoint Server, sites, lists and workflows to store data, define business processes, and define security permissions, the mobile client applications that access the data in the SharePoint lists and workflows, and the services which support communication between the mobile client application and the computer that is running SharePoint Server. The following figure shows these components and how they are related.

Figure 1. Mobile client applications integrated with SharePoint workflows

Flow of events

Introducing the Sample Scenario

Consider a scenario where an insurance company creates a mobile application that integrates with SharePoint sites, lists and workflows. The mobile application lets insurance agents in the field to respond to customer claims, validate the claim, collect more information about the incident, and approve or reject the claim.

This sample scenario is used throughout this article to provide context to the topic at hand and show where a WPF client application is used to integrate with a business process, SharePoint sites, lists and workflow.

Contoso, Inc. is an insurance company that has implemented an automated system using SharePoint Server 2010 and Microsoft Office 2010 to capture insurance incidents and process them. The solution provides the customer the ability to share details of the incident directly with the company, agents, and the repair shop to reach resolution.

Personas

  • Don Funk, Driver (Car Accident Victim) a customer of Contoso, Inc.

  • April Regan, Customer Service Agent at Contoso, Inc.

  • Rob Young, Insurance Agent at Contoso, Inc.

  • Jeff Ford, Body Shop Manager and a partner with Contoso, Inc.

Flow of Events

Figure 2. Flow of events

Workflow Diagram

A large thunderstorm moved through Don Funk’s neighborhood. The high winds knocked down a tree and it landed on Don’s car. Don takes pictures of the damage with his camera phone and sends his insurance company the pictures along with a report of the incident by using his mobile phone to submit his claim.

At the insurance company the submission is received and added to a task list. A customer service agent, April, receives notification, reviews the data to ensure all the required information is present, and passes the incident along to the customer’s agent, Rob Young.

A task is created for Rob Young to investigate the claim and either approve it or reject it. Rob Young reviews the incident report and then meets with Don to perform an inspection and get more information about the incident. He then concludes there is no fraud involved, approves the claim and submits a request for estimates on the repair. The task assigned to Rob is updated and the workflow assigns a new task to a repair shop manager Jeff Ford to submit a bid for the repair work.

When Jeff is notified that Contoso, Inc. has a new request for bid he accesses the Contoso, Inc. extranet and fills out a bid form. Jeff wins the bid for work and schedules a time with Don to perform the work on Don’s car.

Upon completing the repairs, Jeff bills Contoso.

Workflow Details

Figure 3 shows the part of the Microsoft Visual Studio 2010 workflow applicable to this article.

Figure 3. Workflow diagram

Incidents List

As the diagram indicates, a task is created for the insurance agent (Rob Young in the scenario) by the createInsAgentTask activity. Then the logToHistoryListActivity activity creates a list item in the workflow history list to indicate the task was assigned to the insurance agent. Finally, two email messages are sent to notify the customer (Don Funk) and the insurance agent (Rob Young) that the claim was processed and is pending investigation and approval.

Figure 4. Task assigned to insurance agent in the incident task list

Incident Tasks List

The incidents list holds the list item associated with the workflow. At this point the status of the workflow indicates an agent is assigned to process the claim.

Figure 5. Current workflow status in the incidents list

Incident Dashboard

At this point the insurance agent, Rob Young, uses the WPF client application to investigate the claim and approve it.

Building the Mobile WPF Client Application

The mobile client application used in the scenario is a Windows Presentation Framework (WPF) application that is created with Visual Studio 2010. The mobile client application lets insurance agents in the field respond to customer claims, validate the claim, collect more information about the incident, and approve or reject the claim. This section describes how to make a WPF client application, configure it to interface with a WCF service, and integrate it with SharePoint workflows.

You must have the following items to build the components.

  • Windows Server 2008 R2 server that has SharePoint Server 2010 installed

  • Visual Studio 2010

  • Visual Studio 2010 SharePoint project templates

Note

The sample code for this article includes all of the source code for the applications and services that implement the sample scenario described previously. The step-by-step instructions in this article describe how to create the specific parts of the sample scenario applications and services.

Click to grab code  Download code

Creating the WPF Application

The WPF Application in the code sample is named Contoso.AgentApp. The Contoso.AgentApp project is part of the Contoso.Solution solution. The Contoso.AgentApp application contains a rich set of functionality, much of which is inapplicable to this article.

This section describes how to create a WPF Application with Visual Studio 2010, and describes how to implement the components discussed in this article.

To create a WPF application in Visual Studio 2010

  1. Start Visual Studio 2010.

  2. On the File menu, point to New, and then click Project.

  3. In the New Project dialog box, in the Recent Templates pane, expand Visual C#, and then click Windows.

  4. To the right side of the Recent Templates pane, click WPF Application to use the WPF Application project template.

    Figure 6. WPF Application project template in Visual Studio 2010

    Silverlight Application Template

  5. In the Name box, type the name that you want to use for your project, such as Contoso.AgentAppSample.

  6. In the Location box, type the location where you want to place the project.

  7. Click OK to create the solution.

Registering the WCF Service

The client application uses a WCF service to interact with SharePoint sites, lists, and workflows. To use the WCF service, you must add a service reference to the WPF application.

Note

Before you can add the service reference, you must create the WCF service. Follow the steps in the Creating the WCF Service section to create the custom WCF service before you add the WCF service reference to the WPF application.

This section describes how to add service references to the WPF application.

To add the service reference

  1. In Solution Explorer, select the Contoso.AgentAppSample Project.

  2. In Solution Explorer, right-click the References node, and then select Add Service Reference.

  3. In the address box, type the URL to the WCF service that you created earlier.

  4. Click Go.

  5. In the Namespace box, type a friendly namespace for the service.

    Figure 7. Adding a service reference

    Creating the web site project

  6. Click OK.

    The service reference is added to the client application for the WCF service.

    Figure 8. WCF service reference

    Silverlight application with references

Interacting with Workflows

When the insurance agent approves the claim and finishes his task, the WPF application does not actually move the workflow to the next step. Instead, it indirectly triggers the workflow to move on to the next step by updating current the workflow task.

To call WCF services from WPF applications

  1. In Solution Explorer, double-click the MainWindow.xaml.cs file.

  2. Add the following using statement to register the WCF service reference namespace.

    using Contoso.AgentAppSample.ContosoIncidentService;
    
  3. In the MainWindow class, add the following line of code to create an instance of the ContosoIncidentsClient class.

    ContosoIncidentsClient contosoService;
    
  4. In Solution Explorer, right-click the project node and select Build.

    Note

    The ContosoIncidentsClient class is automatically generated by Visual Studio 2010 when you add the WCF service reference to the project. The ContosoIncidentsClient class acts as a proxy to the WCF service.

  5. In Solution Explorer, double-click the MainWindow.xaml file.

  6. Open the Toolbox and drag a Button control to the design surface.

  7. Right-click the Button control and select Properties.

  8. In the Properties window, click the Events button.

  9. Double-click the box next to the Click event to generate the Click event handler for the button.

  10. Add the following code to the Click event handler for the button. This code demonstrates how the WPF application calls into the WCF service to update the current workflow task. The button1_Click method is fired when button in the client application is clicked.

    private void button1_Click(object sender, RoutedEventArgs e)
    {
         string incidentID = 1;
         string returnValue =
              contosoService.UpdateSharePointWorkflowTask(webUrl, listName,
              "Incident - " + incidentID, "Rob Young");
         MessageBox.Show("Claim Approved Successfully");
    }
    

Note

In the code sample, the Btn_Approve_Click method is fired when the agent clicks a button in the client application to approve the claim. The identifier associated with the incident that the workflow task is related to and associated with the user who is assigned the workflow task, allows the individual workflow task to be located.

The UpdateSharePointWorkflowTask method in the contosoService class passes in the parameters necessary to update the workflow task as described previously in the article.

Creating the WCF Service

The WCF service is the key component that allows the client application to interact with the workflow tasks. The service is flexible enough to interface with multiple SharePoint web applications on the server farm. This section describes how to create WCF services that can interface with multiple SharePoint web applications on the same server farm and how you can use it to update workflow tasks.

Separate Internet Information Services (IIS) Website

To ensure that the service can interface with multiple SharePoint web applications on the server farm, you must deploy to a separate IIS website on the computer that is running SharePoint Server. Deploying the WCF service outside the context of SharePoint web applications also insulates the WCF service from issues which may occur when service packs or hot fixes are applied to the server farm.

The application pool associated with the WCF service uses the same identity as the SharePoint web application. This ensures the WCF service has the necessary permissions to access the SharePoint object model.

Figure 9. WCF Service IIS website

Figure 9

In the code sample, the WCF service is named Contoso.Service. The Contoso.Service project is part of the Contoso.Solution solution. The Contoso.Service WCF Service contains many methods to support the components in the sample scenario, most of which are inapplicable to this article.

This section describes how to create a WCF service by using Visual Studio 2010 and create a method to update the status of a SharePoint workflow task.

To create the WCF service

  1. Start Visual Studio 2010.

  2. On the File menu, point to New, and then click Project.

  3. In the New Project dialog box, in the Recent Templates pane, expand Visual C#, and then click WCF.

  4. To the right side of the Recent Templates pane, click WCF Service Application.

    Figure 10. WCF service application project template in Visual Studio 2010

    ClientAccessPolicy.xml

  5. In the Name box, type the name that you want to use for your project, such as Contoso.Service.

  6. In the Location box, type the location where you want to place the project.

  7. Click OK to create the solution.

To add references to the Microsoft.SharePoint.dll

  1. In Solution Explorer, right-click References and then click Add Reference.

  2. Click the .NET tab.

  3. In the list, scroll down until you find Microsoft.SharePoint.

  4. Select Microsoft.SharePoint.

  5. Click OK.

Updating Workflow Tasks

The WPF application does not directly move the workflow from one step to another. Instead, it indirectly triggers the workflow to move on to the next step by updating the current workflow task. The workflow engine then reacts to the changes in the workflow tasks and moves the workflow from one step to another.

The UpdateSharePointWorkflowTask method in the WCF service updates the current workflow task. The UpdateSharePointWorkflowTask method uses the four parameters described in the following table.

Table 1. UpdateSharePointWorkflowTask method parameters

Property

Description

webUrl

SharePoint site where the workflow is running and the tasks are stored.

listName

SharePoint list where the workflow tasks are stored.

listItemName

List item that corresponds to the workflow task to update.

AssignedTo

User to whom the workflow task is currently assigned.

To create the UpdateSharePointWorkflowTask method and associated ServiceContract in the WCF service

  1. In Solution Explorer, right-click the IService1.cs file, and select Delete.

  2. Click OK

  3. In Solution Explorer, right-click the IService1.svc file and select Delete.

  4. Click OK.

  5. In Solution Explorer, right-click the Contoso.Service project.

  6. Select Add, and then click New Item.

  7. To the right side of the Recent Templates pane, click WCF Service.

  8. In the Name box, type ContosoIncidents.svc

  9. Click Add.

  10. In Solution Explorer, double-click the ContosoIncidents.svc.cs file.

  11. Add the following using statements to the file.

    Using System.Collections;
    Using Microsoft.SharePoint;
    Using Microsoft.SharePoint.Workflow;
    
  12. Add the following code to the ContosoIncidents class.

    public string UpdateSharePointWorkflowTask(string webUrl, string listName, string listItemName, string AssignedTo)
    {
         string returnValue = "Failed";
         try
         {
              using (SPSite oSite = new SPSite(webUrl))
              {
                   using (SPWeb oWeb = oSite.RootWeb)
                   {
                        SPList oList = oWeb.Lists[listName];
                        SPListItem workFlowItem = null;
                        string assignedTo = null;
                        string pctComplete = null;
                        string status = null;
    
                        foreach (SPListItem oItem in oList.Items)
                        {
                             if (oItem.Title.Equals(listItemName))
                             {
                                  workFlowItem = oItem;
                                  break;
                             }
                        }
    
                        if (workFlowItem != null)
                        {
                             foreach (SPWorkflowTask oTask in 
                                  workFlowItem.Tasks)
                             {
                                  assignedTo = 
                                       oTask["Assigned To"].ToString();
                                  pctComplete = 
                                       oTask["% Complete"].ToString();
                                  status = oTask["Status"].ToString();
    
                                  if (assignedTo.Contains(AssignedTo))
                                  {
                                       if (pctComplete != "1")
                                       {
                                            Hashtable ht = new Hashtable();
                                            ht["Status"] = "Completed";
                                            ht["% Complete"] = "1";
                                            oSite.AllowUnsafeUpdates = 
                                                 true;
                                            SPWorkflowTask.AlterTask((oTask 
                                                 as SPListItem), ht, true);
                                            oTask.Update();
                                            oSite.AllowUnsafeUpdates = 
                                                 false;
                                            returnValue = "Success";
                                       }
                                  }
                             }
                        }
                        else
                        {
                             returnValue = "Task to update was not found.";
                        }
                   }
              }
         }
         catch (Exception ex)
         {
              returnValue = ex.Message;
         }
         return returnValue;
    }
    

    The UpdateSharePointWorkflowTask method locates the list item that corresponds to the workflow task to update for the specified user. Then, it updates the status and percent complete columns to indicate the task is completed.

  13. In Solution Explorer, double-click the IContosoIncidents.cs file.

  14. Add the following code to the IContosoIncidents interface.

    [OperationContract]
    String UpdateSharePointWorkflowTask(string webUrl, string listName, string listItemName, string AssignedTo);
    

The tasks list that holds the workflow task resembles Figure 11 after the workflow task update is finished. Notice the Status and % Complete columns are updated. The workflow recognized the task assigned to the insurance agent is complete and created the task associated with the next step in the workflow.

Figure 11. Updated workflow task in the incident task list

Restarting the site

When the WCF service updates the workflow task, the workflow responds to the updated task, updates the workflow status, and logs the events to the workflow history list. Then, the workflow moves on to the next step, as shown in Figure 3.

In the code sample, the workflow is named Contoso.Workflow. The Contoso.Workflow project is part of the Contoso.Solution solution. The Contoso.Workflow project contains many activities which support the sample scenario, most of which are inapplicable to this article.

This section describes how to create SharePoint workflows with Visual Studio 2010 and create a complete activity to update the status of a SharePoint workflow.

To create the workflow

  1. Start Visual Studio 2010.

  2. On the File menu, point to New, and then click Project.

  3. In the New Project dialog box, in the Recent Templates pane, expand Visual C#, expand SharePoint, and then click 2010.

  4. To the right side of the Recent Templates pane, click Sequential Workflow.

  5. In the Name box, type the name that you want to use for your project, such as Contoso.Workflow.

  6. In the Location box, type the location where you want to place the project.

  7. Click OK to create the solution.

  8. In the SharePoint Customization Wizard, type the URL to the site where you want to deploy and debug the workflow.

    Figure 12. SharePoint Customization Wizard solution settings

    Testing print results

  9. Click Next.

  10. In the SharePoint Customization Wizard, type a name for the workflow, and select the List Workflow radio button.

    Figure 13. SharePoint customization workflow settings

    Default right-click menu

  11. In the SharePoint Customization Wizard, select the list, history list, and task list to associate with the workflow.

  12. In the code sample, the Contoso.Workflow project uses the settings as shown in Figure 14. These lists are not available on the system unless you run the installer to create the samples sites and lists that support the demo scenario.

    Figure 14. SharePoint customization workflow list settings

    Popup visibility on right-click

  13. Click Next.

  14. Click Finish. SharePoint workflows created in Visual Studio 2010 may be deployed only as a server farm solution.

  15. As previously mentioned, the sample code contains the full workflow associated with the sample scenario. This section describes how to make the complete task activity applicable to this article. The complete task is highlighted in Figure 15.

    Figure 15. Complete task workflow activity in the sample scenario workflow

    Adding a Web Part

To create the samples sites and lists to support the demo

  1. In Solution Explorer, double-click the Workflow1.cs file.

  2. From the Toolbox, drag a CompleteTask activity to the design surface.

    Figure 16. Adding a complete task workflow activity to the workflow

    Adding a Web Part

  3. Double-click the CompleteTask activity.

  4. Add the following code to the completeTask1_MethodInvoking method.

         insAgentTaskProperties.PercentComplete = 100;
         SPListItem item = workflowProperties.Item;
         item["Status"] = "Claim Approved";
         item.SystemUpdate(false);
         workflowHistoryComments = "Insurance agent has reviewed the claim
          and has approved the claims request which completes their task - "      + insAgentTaskProperties.Title + ".";
    

Note

In the code sample, the method that corresponds to this series of steps is called the completeInsAgentTask_MethodInvoking method.

The list that holds the workflow items resembles Figure 17 after the workflow status update is finished. Notice the Status column is updated to indicate the claim was approved by the insurance agent.

Figure 17. Updated workflow status in the incidents list

Typing the path

Deploying the Mobile Client Application and Other Components

After the WPF client application is created, you must deploy it to the desktops in the organization and deploy the WCF service to the server farm. This section discusses how to package and deploy these components in an automated, repeatable, and consistent manner.

Deploying the Solution with ClickOnce

You can use ClickOnce deployment packages to package and deploy WPF client applications.

To create ClickOnce deployment packages

  1. In Visual Studio 2010, in Solution Explorer, right-click the WPF project, and then select Properties.

  2. Select the Publish tab.

    Figure 18. Publish tab in Visual Studio 2010

    Editing the Silverlight Web Part

  3. Click Publish Wizard to start the wizard that generates the ClickOnce deployment package.

  4. Type a location to publish the application.

    Figure 19. Setting the publish location in the Publish Wizard

    Configuring the Silverlight Web Part properties

  5. Click Next.

  6. Click Next.

  7. Click Next.

  8. Click Finish.

    When the publish process is complete, the following files are copied to the publish location. Running setup.exe installs the WPF application on a client device.

    Figure 20. Files generated by the Publish Wizard

    Silverlight application in a Web Part

    Note

    For more information about ClickOnce deployment packages, see Additional Resources.

Packaging the WCF Service with Visual Studio 2010

You can also package the WCF service by using Visual Studio 2010.

To configure packaging options for the WCF service

  1. In Visual Studio 2010, in Solution Explorer, right-click the WCF service project, and then select Properties.

  2. Select the Package/Publish Web tab.

    Figure 21. Package/Publish Web tab in Visual Studio 2010

    Figure 21

  3. Note the package creation location.

To generate the package after you set package configuration options

  1. In Visual Studio 2010, in Solution Explorer, right-click the WCF service project.

  2. Select Build Deployment Package.

    Figure 22. Building deployment packages in Visual Studio 2010

    Figure 22

Examining the output window shows the steps Visual Studio 2010 takes to generate the deployment package and where the file is generated.

Figure 23. Visual Studio 2010 output window showing WCF service application package generation

Figure 23

The package generated by Visual Studio 2010 creates an IIS website and deploys the associated code and resources. However, it does not create a web application or assign the application pool to the web application. To completely automate the deployment process, you can use managed code to create the IIS website, the associated web application, and assign the appropriate application pool to the web application. The following batch file deploys the WCF service to a computer that is running SharePoint Server and calls into a custom console application as needed to completely automate the process.

[command]
rem Set the path to the console application that creates the IIS web site and web application.
set Installerengine=InstallerEngine\Contoso.InstallerEngine.exe

rem Set the path where the IIS web site should be created.
set IISWebSitePhysicalPath=C:\SP2010Demo

rem Create the directory for the IIS web site.
md "C:\SP2010Demo\Contoso.Service"

rem Create the IIS web site.
"%Installerengine%" createiiswebsite "Contoso Service" "9999" "%IISWebSitePhysicalPath%"

rem Set the location to the package for the WCF service generated by Visual Studio 2010.
set ServicePackage=5_Service\Package\Contoso.Service.zip

rem Set the location for the web application in the IIS web site.
set Service_IISWebApplication="%IISWebSitePhysicalPath%\Contoso.Service"

rem Set the location to the msdeploy.exe.
set MSDeployTool=%ProgramFiles%\IIS\Microsoft Web Deploy\msdeploy.exe

rem Set the name for the application pool.
set ApplicationPoolName=Contosoo Service Application Pool

rem Deploy the deployment package for the WCF service.
"%MSDeployTool%" -source:package="%ServicePackage%" -dest:auto,includeAcls=false -verb:sync -disableLink:ContentExtension 

rem Add the web application to the IIS web site.
"%Installerengine%" addapplication "Contoso Service" "%Service_IISWebApplication%" "%ApplicationPoolName%"

The batch file calls into a console application and executes the CreateWebsite method to create an IIS website to host the WCF service. The string array of arguments contains the name, port, and directory values that were used to create the new IIS website. This method uses the ServerManager class and Sites class in the Microsoft.Web.Administration namespace.

The batch file makes an additional call to the console application and executes the AddApplicationToSite method to create a web application in the IIS web site that hosts the WCF service. The string array of arguments contains the name of the IIS website to add the web application to, the directory to create for the web application and the name of the application pool to assign to the web application. This method uses the ServerManager class, Sites class, and Application class in the Microsoft.Web.Administration namespace.

The installer application for the code sample is named Contoso.InstallerEngine. The Contoso.InstallerEngine project is part of the Contoso.Solution solution. The Contoso.InstallerEngine project contains many methods that support the installation of the sample scenario, most of which are inapplicable to this article.

Creating Console Application Installer Engines to Automate the WCF Service Deployment

This section describes how to create a console application installer engine to automate the deployment of the WCF service to mobile clients.

To create the console application

  1. Start Microsoft Visual Studio 2010.

  2. On the File menu, point to New, and then click Project.

  3. In the New Project dialog box, in the Recent Templates pane, select Visual C#.

  4. To the right side of the Recent Templates pane, click Console Application.

  5. In the Name box, type the name that you want to use for your project, such as Contoso.InstallerEngine.

  6. In the Location box, type the location where you want to place the project.

  7. Click OK to create the solution.

To add references to the System.Web.Administration.dll

  1. In Solution Explorer, right-click References, and then click Add Reference.

  2. Click the Browse tab.

  3. Browse to the following assembly, and select it: C:\Windows\System32\inetsrv\Microsoft.Web.Administration.dll

  4. Click OK

  5. In Solution Explorer, right-click project node, and select Properties.

  6. In the Application tab, configure the Target framework to .NET Framework 3.5

  7. Click Yes.

To add the methods to create the IIS website and add an application pool to the site

  1. In Solution Explorer, double-click the Program.cs file.

  2. Replace the contents of the Program.cs file with the following code.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Configuration;
    using System.IO;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            internal enum InstallerCommands
            {
                createiiswebsite,
                addapplication
            }
    
            static void Main(string[] args)
            {
                if (args.Length > 0)
                {
                    try
                    {
                        InstallerCommands currentCommand = (InstallerCommands)Enum.Parse(typeof(InstallerCommands), args[0]);
                        switch (currentCommand)
                        {
                            case InstallerCommands.createiiswebsite:
                                ProvisionIISWebSite.CreateWebsite(args);
                                break;
                            case InstallerCommands.addapplication:
                                ProvisionIISWebSite.AddApplicationToSite(args);
                                break;
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Error:");
                        Console.WriteLine(ex.Message);
                    }
                }
                else
                {
                    Console.WriteLine("No valid operations detected, type help for list of operations.");
                }
            }       
        }
    }
    
  3. In Solution Explorer, right-click the Contoso.InstallerEngine project.

  4. Select Add, and then click Class.

  5. In the Name box, type Helper.cs.

  6. Click Add.

  7. Replace the contents of the Helper.cs file with the following code.

    using System;
    using System.Text;
    
    namespace ConsoleApplication1
    {
        internal static class Helper
        {
    
            internal static string GetArgumentValue(string[] arguments, string parmName, int index)
            {
                if (arguments.Length > index)
                {
                    return (arguments[index].ToString());
                }
                else
                {
                    throw new ArgumentException("Invalid argument: \"" + parmName + "\".");
                }
            }
    
        }
    }
    
  8. In Solution Explorer, right-click the Contoso.InstallerEngine project.

  9. Select Add, and then click Class.

  10. In the Name box, type ProvisionIISWebSite.cs.

  11. Click Add.

  12. Replace the contents of the ProvisionIISWebSite.cs file with the following code.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Microsoft.Web.Administration;
    
    namespace ConsoleApplication1
    {
        internal static class ProvisionIISWebSite
        {
            internal static void CreateWebsite(string[] args)
            {
                string siteName, port, homeDirectory;
                siteName = Helper.GetArgumentValue(args, "sitename", 1);
                port = Helper.GetArgumentValue(args, "port", 2);
                homeDirectory = Helper.GetArgumentValue(args, "homeDirectory", 3);
    
                ServerManager iisManager = new ServerManager();
                if (iisManager.Sites[siteName] == null)
                {
                    iisManager.Sites.Add(siteName, "http", "*:" + port + ":", homeDirectory);
                    iisManager.CommitChanges();
                    Console.WriteLine("Completed.");
                }
                else
                {
                    Console.WriteLine("Website already exists.");
                }
            }
    
            internal static void AddApplicationToSite(string[] args)
            {
                string siteName, appDirectory, appPoolName;
                siteName = Helper.GetArgumentValue(args, "sitename", 1);
                appDirectory = Helper.GetArgumentValue(args, "appdirectory", 2);
                appPoolName = Helper.GetArgumentValue(args, "apppoolname", 3);
                string[] appArry = appDirectory.Split(@"\".ToCharArray());
                string applicationName = "/" + appArry[appArry.Length - 1];
                ServerManager iisManager = new ServerManager();
                if (iisManager.Sites[siteName] != null)
                {
                    Application app;
                    if (iisManager.Sites[siteName].Applications[applicationName] == null)
                    {
                        app = iisManager.Sites[siteName].Applications.Add(applicationName, appDirectory);
                        app.ApplicationPoolName = appPoolName;
                        iisManager.CommitChanges();
                        Console.WriteLine("Completed.");
                    }
                    else
                    {
                        app = iisManager.Sites[siteName].Applications[applicationName];
                        app.ApplicationPoolName = appPoolName;
                        iisManager.CommitChanges();
                        Console.WriteLine("Updated existing application.");
                    }
                }
                else
                {
                    Console.WriteLine("No such website exists.");
                }
            }
    
        }
    }
    

Debugging the Solution Components

You can use Visual Studio 2010 to debug the WPF client application, the WCF service, and the SharePoint workflow. To debug the WPF application, set a breakpoint in the WPF application code, ensure it is the startup project, and press F5 to start debugging. Visual Studio 2010 automatically attaches to the process for the WPF application and breaks on the breakpoint in the code.

To debug the WCF service application, set a breakpoint in the WCF service code. While debugging the WPF application, press F11 to step into the code in the WCF service application. Visual Studio 2010 automatically attaches to the process and breaks on the breakpoint set in the WCF service.

To debug the SharePoint workflow, set a breakpoint in the workflow code and attach Visual Studio 2010 to the SharePoint Timer Service (OWSTIMER.EXE), and then perform an action to cause the workflow code to be invoked. Visual Studio 2010 breaks on the breakpoint that you set in the workflow code.

Conclusion

Mobile and client applications are more prevalent in the workplace than ever. Creating client applications that integrate with SharePoint sites is a common development task. The WPF application that is created in this article discusses how mobile applications can integrate with SharePoint workflows.

Figure 24. WPF application integrated with SharePoint workflow

Figure 24

The complete sample code that accompanies this article includes a more robust version of the WPF application that integrates with the SharePoint workflow.

Figure 25. WPF application integrated with SharePoint workflow

Figure 25

Using WPF applications, WCF services, and SharePoint 2010to provide rich client applications, data storage, and workflow integration capabilities saves time when you compare it to developing custom components. This article described how to create and deploy WCF services and use them to access multiple SharePoint web applications on the same server farm. It also discussed how to update workflow tasks to trigger workflow processes. Further, it demonstrated how Visual Studio 2010 provides an easy way to package and deploy WPF client applications and how Visual Studio 2010 provides an easy way to package WCF services. Finally, it showed how to use batch files and managed code to automate the deployment of WCF services to server farms.

Additional Resources

For more information, see the following resources: