# Web Services API

## Overview

Most runtime and design time workflow operations can be operated via the web services API, such as:

* Retrieving requests and action data and statuses
* Launching new requests and updating request data
* Completing workflow actions
* Managing users, groups, participants, and delegations
* Importing and exporting process definitions.

For more flexibility, all of the API web methods can be called by using POST, GET, or SOAP.

The authentication method is HTTP basic (over HTTPS) or can be customized according to your requirements (SSO, token, etc.) by using your own custom .NET HTTP authentication module.

Impersonation and delegation mode is also supported on selected web methods (e.g. completing an action on behalf of a WorkflowGen user).

## API methods

The API web methods are located in `http://localhost/wfgen/ws/processesruntime.asmx`. See the [WorkflowGen Web Services API Reference Guide](https://docs.workflowgen.com/web-services-api) for more information.

## WorkflowContext

The WorkflowGen web services API uses the WorkflowContext data structure in some important web methods such as:

* `CompleteActivityInstance`
* `GetActivityInstanceContext`
* `StartProcess`

WorkflowContext is an XML data structure used to exchange parameters with WorkflowGen. The XML data structure is based on ADO.NET DataSet object (serialized in XML). As such, the structure is similar to database tables and records.

#### 📌 XML ADO.NET DataSet context example

```markup
<NewDataSet>
    <parameter>
        <name>COMPANY</name>
        <dataType>TEXT</dataType>
        <direction>OUT</direction>
        <textValue>My company</textValue>
    </parameter>
    <parameter>
        <name>AMOUNT</name>
        <dataType>NUMERIC</dataType>
        <direction>OUT</direction>
        <numericValue>1000</numericValue>
    </parameter>
    <parameter>
        <name>APPROVAL_DATE</name>
        <dataType>DATETIME</dataType>
        <direction>OUT</direction>
        <dateTimeValue>2017-02-17T02:07:43Z</dateTimeValue>
    </parameter>
    <parameter>
        <name>ATTACHMENT</name>
        <dataType>FILE</dataType>
        <direction>OUT</direction>
        <fileName>report.xls</fileName>
        <fileDescription>My report</fileDescription>
        <fileSize>202345</fileSize>
        <fileContentType>application/vnd.ms-excel</fileContentType>      
        <fileDateLastModified>2017-02-17T02:07:43Z</fileDateLastModified>
        <fileOriginalPath>C:\myfolder\report.xls</fileOriginalPath>
        <filePath>C:\myfolder\report.xls</filePath>
    </parameter>
</NewDataSet>
```

### Nodes

#### `<NewDataSet>` node

The `<NewDataSet>` node is a Dataset object that contains a set of parameters (parameter nodes) and one session information (session node).

#### `<Parameter>` node

The `<Parameter>` node contains information about the parameter to exchange with WorkflowGen web method:

| **Node**                 | **Description**                                                                                                                                                                                                                    |
| ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `<name>`                 | Name of the parameter defined in the workflow action                                                                                                                                                                               |
| `<dataType>`             | <p><strong>Possible values:</strong></p><ul><li><code>TEXT</code></li><li><code>NUMERIC</code></li><li><code>DATETIME</code></li><li><code>FILE</code></li></ul>                                                                   |
| `<direction>`            | <p><strong>Possible values:</strong></p><ul><li><code>IN</code></li><li><code>OUT</code></li><li><code>INOUT</code></li></ul>                                                                                                      |
| `<textValue>`            | Text value of the parameter                                                                                                                                                                                                        |
| `<numericValue>`         | Numeric value of the parameter                                                                                                                                                                                                     |
| `<dateTimeValue>`        | Datetime value of the parameter in the format `xsd:dateTime` and stored in GMT (see the [Time Zone IDs & GMT Values Mapping appendix](https://docs.workflowgen.com/integration/8.3/appendix-time-zone-ids-and-gmt-values-mapping)) |
| `<fileName>`             | File name                                                                                                                                                                                                                          |
| `<fileDescription>`      | File description                                                                                                                                                                                                                   |
| `<fileSize>`             | File size in bytes                                                                                                                                                                                                                 |
| `<fileDateLastModified>` | Date of last modification to the file in the format `xsd:dateTime`                                                                                                                                                                 |
| `<fileContentType>`      | File MIME type                                                                                                                                                                                                                     |
| `<fileOriginalPath>`     | Original file path (for information only)                                                                                                                                                                                          |
| `<filePath>`             | File path that WorkflowGen uses to retrieve the file                                                                                                                                                                               |

## WorkflowContext creation with WorkflowGen.My

To simplify WorkflowContext creation and modification, you can use WorkflowGen.My and its `WorkflowGen.My.Data.ContextParameters` class:

```
WorkflowGen.My.Data.ContextParameters myWorkflowContextParameters = new WorkflowGen.My.Data.ContextParameters();

WorkflowGen.My.Data.ContextParameter contextParamApproval = new WorkflowGen.My.Data.ContextParameter();

contextParamApproval.Name = "DECISION";

contextParamApproval.Direction = WorkflowGen.My.Data.ContextParameter.Directions.Out;

contextParamApproval.Type = typeof(string);

contextParamApproval.Value = "YES";

myWorkflowContextParameters.Add(contextParamApproval);

myWorkflowContextParameters.Update();

string workflowContext = myWorkflowContextParameters.GetXml();
```

For more detailed examples, see [WorkflowContext creation with WorkflowGen.My](https://docs.workflowgen.com/integration/8.3/workflow-applications#workflowcontext-creation-with-workflowgen.my).

## Invoking a WorkflowGen API using .NET code

Before invoking a WorkflowGen API using .NET code, first verify that you have access to the APIs by doing the following:

1. Open a new web browser.<br>
2. Connect to your web service with your WorkflowGen URL: `http://yourserver:port/wfgen/ws/ProcessesRuntime.asmx`.<br>
3. Authenticate with your WorkflowGen account.<br>
4. The above URL will provide you with a list of available web service APIs.

Use the sample code below to invoke a web service API from within your code. This example demonstrates how to call the `CompleteActivityInstance` API, which is used to complete an open action.

Prior to implementing the code below, do the following:

1. Open your existing web project (or create a new web project) for which you would like to implement the API web service call.<br>
2. Add a web reference to your website by performing the following steps:<br>
   1. In Visual Studio, choose **Website > Add Web Reference...**<br>
   2. Enter the web service URL (`http://yourserver:port/wfgen/ws/ProcessesRuntime.asmx`) and click **Add Reference**. You'll likely be prompted by the server to authenticate your request. Enter the appropriate username, password, and domain (if necessary). Once submitted, you should see the same screen as when you verified your access to the APIs, with a list of available APIs.<br>
   3. You'll be prompted to give the web reference a name. The sample below uses the web reference name `WFG_APIs`.<br>
   4. Click **Add reference**. You should now see the reference within your Solution Explorer.<br>
3. Add the following code, or incorporate the code into your existing code as required:

#### C\#

```csharp
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using WorkflowGen.My.Web.UI.WebForms;
using WorkflowGen.My.Data;
using System.Net;


public partial class _Default : WorkflowPage
{

   private WFG_APIs.RuntimeService wsAPI;

   protected void Page_Load(object sender, EventArgs e)
   {

   }


   protected void Button1_Click(object sender, EventArgs e)
   {

      string workflowContextXml; // string to get the xml context data

      // Create a new WorkflowGen object for context parameters
      WorkflowGen.My.Data.ContextParameters myWorkflowContextParameters = new WorkflowGen.My.Data.ContextParameters();


      // Get the xml context data into variable
      workflowContextXml = myWorkflowContextParameters.GetXml();

      // ID of the request to cancel
      string RequestID = "1374"

      //ID of the activity to cancel (Current Action ID) 
      string ActivityID = "4"

      wsAPI = new WFG_APIs.RuntimeService();

      wsAPI.Credentials = new NetworkCredential("USERNAME", "PASSWORD","");

      try
      {
            wsAPI.CompleteActivityInstance(Convert.ToInt16(RequestID), Convert.ToInt16(ActivityID), workflowContextXml.ToString());
            Response.Write("OK – Action Completed");
      }
      catch (Exception exN)
      {
             Response.Write("Error = " + exN.Message.ToString() + exN.StackTrace.ToString());
      }

   }

}
```

#### 📌 Sample code to complete a request action

```csharp
string workflowContextXml; // string to get the xml context data

// Create a new WorkflowGen object for context parameters
WorkflowGen.My.Data.ContextParameters myWorkflowContextParameters = new WorkflowGen.My.Data.ContextParameters();

// Get the xml context data into variable
workflowContextXml = myWorkflowContextParameters.GetXml();

// ID of the request
int RequestID = 1374

// ID of the activity to complete
int ActivityID = 4

wsAPI = new WFG_APIs.RuntimeService();
wsAPI.Credentials = new NetworkCredential("USERNAME", "PASSWORD","");

try
{

    wsAPI.CompleteActivityInstance(RequestID, ActivityID, workflowContextXml.ToString());

    Response.Write("OK – Action Completed");

}

catch (Exception exN)
{
    Response.Write("Error = " + exN.Message.ToString() + exN.StackTrace.ToString());
}
```

## `StartProcess`

`StartProcess` lets you launch a new request with context parameters from an external application via the web service API using SOAP. This web method lets you launch a new process from another application using HTTP parameters.

### Method definition

* `public int StartProcess(string processName, bool test, string context)`: Returns the created request ID if successful

### Required parameters

| **Parameter** | **Type** | **Description**                                                                                                                               |
| ------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| `processName` | String   | Name of the process to launch                                                                                                                 |
| `test`        | Bool     | <p>Launch process in test mode?</p><ul><li><code>Y</code>: Launch a test version</li><li><code>N</code>: Launch the active version</li></ul>  |
| `context`     | String   | XML structured INOUT parameters to send to the process start (see the [WorkflowContext](#workflowcontext) section above for more information) |

### Optional parameters (`StartProcessHeader`)

| **Parameter**         | **Type** | **Description**                                                                       |
| --------------------- | -------- | ------------------------------------------------------------------------------------- |
| `ImpersonateUsername` | String   | Username of impersonating user                                                        |
| `ProcessId`           | Int      | Process ID (to be used independently without the `processName` and `test` parameters) |
| `ProcessVersion`      | Int      | Process version (to be used `processName` only)                                       |

For an example of usage, download [`SDK_CS_RemoteLaunchSOAP_v6_1.zip`](https://app.box.com/s/mqtdihsyjfdrwokqxqhjppbzpx7b3t10), unzip it, and follow the instructions in the included `setup.txt` file.

### Impersonation

The `StartProcess` web method supports impersonation, so an authorized user can launch a process on behalf of another user with this web method call. This impersonation feature is restricted to allowed users (defined in the `ProcessesRuntimeWebServiceAllowedUsers` entry in the `\wfgen\ws\web.config` file). This feature is useful when an external application doesn't have the user's credentials and wants to instantiate a process on their behalf. For more information, see the [Impersonate username](#impersonate-username) section below and the [Web Services API: StartProcess: Launch a process on behalf of another user](https://discuss.workflowgen.com/t/web-services-api-startprocess-launch-a-process-on-behalf-of-another-user/318) topic on the [WorkflowGen Forum & Knowledge Base](https://discuss.workflowgen.com/).

## Security

If you receive the message `SoapException "Security: You are not authorized to use this web service"`, it's because some WorkflowGen web service methods require an additional configuration setting to be called by a user. In the `\wfgen\ws\web.config` file, you can edit the following key to authorize WorkflowGen administrators to use the secured web methods:

```markup
<add key="ProcessesRuntimeWebServiceAllowedUsers" value="wfgen_admin,MYDOMAIN\myusername" />
```

The value contains a comma separated list of usernames. The username must be prefixed by the domain name according to your authentication method.

The following web service API methods are secured by this setting:

* `RaiseCancelExceptionOnActivityInstance`
* `RaiseCancelExceptionOnActivityInstanceByName`
* `RaiseExceptionOnActivityInstance`
* `RaiseExceptionOnActivityInstanceByName`
* `UpdateProcessInstanceData`
* `StartProcess`, with the `ImpersonateUsername` SOAP or GET/POST parameter

## Performance

By default, the `GetProcessInstanceList` and `GetActivityInstanceList` web methods retrieve all the process data associated to the requests/actions. If you don't need process data values, you only need to add a SOAP header or query string parameter:

`ShowData=False`

If you only need a subset of the associated process data, you can specify the list of process data to be retrieved with the `DataList` SOAP header or query string parameter:

`DataList=AMOUNT,APPROVAL,COMPANY`

This will significantly improve performance.

#### 📌 Example of a query string

```
http://localhost/wfgen/ws/ProcessesRuntime.asmx/GetActivityInstanceList?query=closed&datalist=REQUEST_SUBJECT,FORM_ARCHIVE
```

## Process data

Get associated data of a request and download the associated attachments.

If you are a process supervisor, manager, or administrator, you can use the web API to get the data of a specific request and download the associated attachments using the URLs below, with the request number as the value of `ProcessInstanceId` (these examples use request `17`).

#### If the request is still ongoing:

```
http://mywebserver/wfgen/ws/processesruntime.asmx/GetProcessInstanceList?query=supervisedinprogress&ProcessInstanceId=17&Template=ProcessesRuntime.ProcessInstanceListRss.txt
```

#### If the request is closed:

```
http://mywebserver/wfgen/ws/processesruntime.asmx/GetProcessInstanceList?query=supervisedclosed&ProcessInstanceId=17&Template=ProcessesRuntime.ProcessInstanceListRss.txt
```

Inside the retrieved XML output (RSS, XML, or ATOM, depending on the template you're using; see `\wfgen\ws\App_Data` for the templates), you'll see a specific URL for each data file, which you can download using an HTTP GET/POST or an AJAX call from your web form.

#### 📌 Example

```markup
<wfg:processInstanceRelData>
    <FORM_HTML description="Form" dataType="FILE" fileName="3429158-1.html" fileContentType="text/html" fileSize="9236″>http://mywebserver/wfgen/show.aspx?QUERY=DATASET_FILE_DOWNLOAD&ID_PROCESS=206&ID_RELDATA=2812&ID_DATASET=3429162&NUM_VALUE=1&NO_CHARSET=Y&NO_REDIRECTION=Y</FORM_HTML>
    <FORM_DATA description="Form data" dataType="FILE" fileName="dataOUT.xml" fileContentType="application/xml" fileSize="3646″>http://mywebserver/wfgen/show.aspx?QUERY=DATASET_FILE_DOWNLOAD&ID_PROCESS=206&ID_RELDATA=2813&ID_DATASET=3429163&NUM_VALUE=1&NO_CHARSET=Y&NO_REDIRECTION=Y</FORM_DATA>
    <FORM_ARCHIVE description="Form archive" dataType="FILE" fileName="form_archive.htm" fileContentType="application/octet-stream" fileSize="17805″>http://mywebserver/wfgen/show.aspx?QUERY=DATASET_FILE_DOWNLOAD&ID_PROCESS=206&ID_RELDATA=2814&ID_DATASET=3429164&NUM_VALUE=1&NO_CHARSET=Y&NO_REDIRECTION=Y</FORM_ARCHIVE>
    <FORM_DRAFT description="Form draft" dataType="TEXT" fileName="" fileContentType="" fileSize="">N</FORM_DRAFT>
</wfg:processInstanceRelData>
```

### `UpdateProcessInstanceData`

The `UpdateProcessInstanceData` web method allows you to update the associated data of a request in progress from an external application. It is restricted to allowed users as defined in the `ProcessesRuntimeWebServiceAllowedUsers` entry in the `\wfgen\ws\web.config` file.

Only requests in progress can be updated. If a process data to update is locked by another user (such as when a user is filling in a web form that will update one of the process data), the web method triggers a SOAP exception.

#### Parameters

The web method parameters (SOAP or GET/POST) are:

* `processInstanceId`

  📌 **Example:** `12345` <br>

* `activityInstanceId`

  📌 **Example:** `2`

* `workflowContext`

  📌 **Example:**

  ```
  MYTEXTDATAHello
    MYNUMDATA1000
  ```

  Here, `MYTEXTDATA` and `MYNUMDATA` are the process data names to update.

#### Usage

By updating process data associated to requests in progress, you might impact the ongoing workflow with side effects such as loops or stuck requests, so you should be careful when updating process data used in conditions.

If you need more security and traceability, we recommend using workflow actions to update process data (for more information, see [Workflow Design: Update a process data from an external application](https://discuss.workflowgen.com/t/workflow-design-update-a-process-data-from-an-external-application/393) on the [WorkflowGen Forum & Knowledge Base](https://discuss.workflowgen.com)).

## Impersonate username

All user context-based API web methods support impersonation, so an authorized user can call a web method on behalf of another user.

### Security

The impersonation feature is restricted to allowed users as defined in the `ProcessesRuntimeWebServiceAllowedUsers` entry in the `\wfgen\ws\web.config` file.

### Usage

There are two ways to set the `ImpersonateUsername` value:

* As a querystring parameter; in this example, a list of `todo` actions for `jsmith`:

  ```html
  http://myserver/wfgen/ws/ProcessesRuntime.asmx/GetActivityInstanceList?query=todo&impersonateusername=jsmith
  ```
* As a SOAP header parameter; in this example, to complete an action on behalf of `jsmith`:

  ```
  // Settings and parameters
  CompleteActivityInstanceHeader myCompleteActivityInstanceHeader = new CompleteActivityInstanceHeader();

  myCompleteActivityInstanceHeader.ImpersonateUsername="jsmith";

  // Set NetworkCredentials with the credentials of the current connected user
  RuntimeService myRuntimeService = new RuntimeService();
  myRuntimeService.CompleteActivityInstanceHeaderValue = myCompleteActivityInstanceHeader;
  myRuntimeService.Credentials = CredentialCache.DefaultCredentials;

  // Call the Web Service API method
  myRuntimeService.CompleteActivityInstance(1,2,wfgContext);
  ```
