Business process service

PDF
Advanced

Running business processes is one of the purposes of integrating the external application with Creatio. The ProcessEngineService.svc web service that enables running business processes from the outside is implemented for this.

Note. You can find the full list of web service methods in the ProcessEngineService Class Members documentation.

Run business process via web-service
Advanced

Example. Run a demo business processes of creating and reading Creatio contacts from the browser address bar or third-party application via the ProcessEngineService.svc web service.

Example implementation algorithm 

To implement the case:

  1. Create the demo processes of adding new contact and reading all contacts.
  2. Check the operability of the ProcessEngineService.svc web service from the browser address bar.
  3. In the third-party application, create a class and implement logic of interaction with the ProcessEngineService.svc web service in this class.

1. Creating the demo business processes 

Note. Best practices of business process creation in Creatio are provided in the business process guide.

2. Creating the process of adding a new contact 

The business process of adding a new contact has start event, end event and ScriptTask element in which the logic of adding a new contact is implemented. The values of business process properties:

  • Name – "Add New External Contact"
  • Code – "UsrAddNewExternalContact"

Default values may be used for the other properties.

The business process contains two text parameters. The contact details are sent to the process via these parameters:

  • ContactName – contains a name of the new contact
  • ContactPhone – contains a phone number of the new contact.

Logic of adding a new contact is implemented in the ScriptTask element. The values of element properties:

  • Name – "Add contact".
  • Code – "ScriptTaskAddContact".
ScriptTaskAddContact
// Create an instance of the schema of the "Contact" object.
var schema = UserConnection.EntitySchemaManager.GetInstanceByName("Contact");
// Create an instance of a new object.
var entity = schema.CreateEntity(UserConnection);
// Set the default values for the object columns.
entity.SetDefColumnValues();
string contactName = Get<string>("ContactName");
string contactPhone = Get<string>("ContactPhone");
// Set the value of the "Name" column from the process parameter.
entity.SetColumnValue("Name", contactName);
// Set the value of the "Phone" column from the process parameter.
entity.SetColumnValue("Phone", contactPhone);
// Saving a new contact.
entity.Save();
return true;

Save the business process to apply changes.

3. Creating the process of reading contacts 

Business process that generates a list of all contacts also contains one ScriptTask element in which the necessary logic is implemented. The values of business process properties:

  • Name – "Get All Contacts"
  • Code – "UsrGetAllContacts"
  • Force compile – checkbox checked.

Default values may be used for the other properties.

The UsrGetAllContacts process contains the ContactList parameter. The process will get a list of all contacts as a JSON object through this parameter. Parameter type – unlimited length string.

Logic of getting contacts is implemented in the ScriptTask process element. The values of element properties:

  • Name – "Get all contacts".
  • Code – "ScriptTaskGetAllContacts".
ScriptTaskGetAllContacts
// Create an EntitySchemaQuery instance.
EntitySchemaQuery query = new EntitySchemaQuery(UserConnection.EntitySchemaManager, "Contact");
// A flag for required selection of the primary column (Id).
query.PrimaryQueryColumn.IsAlwaysSelect = true;
// Adding columns to the request.
query.AddColumn("Name");
query.AddColumn("Phone");
// Getting the result collection.
var list = query.GetEntityCollection(UserConnection);
// Creating a list of contacts for serialization in JSON.
List<object> contacts = new List<object>();
foreach (var item in list)
{
    var contact = new
    {
        Id = item.GetTypedColumnValue<Guid>("Id"),
        Name = item.GetTypedColumnValue<string>("Name"),
        Phone = item.GetTypedColumnValue<string>("Phone")
    };
    contacts.Add(contact);
}
// Save the serialized JSON collection of contacts to the ContactList parameter.
string contactList = JsonConvert.SerializeObject(contacts);
Set<string>("ContactList", contactList);
return true;

Save the business process to apply changes.

4. Run business processes from the browser address bar 

The call to the service method is possible using an HTTP GET request and you can use a standard browser to start a business process

To launch the process of creation a new contact, enter the following URL in the browser address bar

URL to start the process of creating a new contact
http[s]://<Creatio_application_address>/0/ServiceModel/ProcessEngineService.svc/UsrAddNewExternalContact/Execute?ContactName=John Johanson&ContactPhone=+1 111 111 1111

After executing the request, a new contact will be added to Creatio.

Attention. A new contact will be created after each successful request to the service. If you run a number of queries with the same parameters, multiple duplicate contacts will be created.

To launch the process of reading all contacts, enter the following URL in the browser address bar.

URL to start reading all contacts
http[s]://<Creatio_application_address>/0/ServiceModel/ProcessEngineService.svc/UsrGetAllContacts/Execute?ResultParameterName=ContactList

After executing the request, a JSON object with collection of contacts will be displayed in the browser window.

5. Run business processes from the third-party application 

Before making requests to ProcessEngineService.svc, a third party application must be authenticated. Use the AuthService.svc authentication service for this. Console application created according to the example can be used for the case below.

Attention. Full source code of the console application used for running business processes via the ProcessEngineService.svc service is available by a link.

To generate requests to the ProcessEngineService.svc service, add a string field that contains base service URL to the Program class source code:

Base ProcessEngineService.svc URL
private const string processServiceUri = baseUri + @"/0/ServiceModel/ProcessEngineService.svc/";

To run the business process of adding a new contact, add the following method to the source code of the Program class.

GET method to run the business process
public static void AddContact(string contactName, string contactPhone)
{
    // Generating the URL request.
    string requestString = string.Format(processServiceUri +
            "UsrAddNewExternalContact/Execute?ContactName={0}&ContactPhone={1}",
                             contactName, contactPhone);
    // Generating Http request.
    HttpWebRequest request = HttpWebRequest.Create(requestString) as HttpWebRequest;
    request.Method = "GET";
    request.CookieContainer = AuthCookie;
    // Execute the request and analyze the Http response.
    using (var response = request.GetResponse())
    {
        // Because the service returns an empty string, 
        // you can display the http response properties.
        Console.WriteLine(response.ContentLength);
        Console.WriteLine(response.Headers.Count);
    }
}

Add a method of starting the process of reading contacts:

GetAllContacts listing
public static void GetAllContacts()
{
    // Generating the URL request.
    string requestString = processServiceUri +
                       "UsrGetAllContacts/Execute?ResultParameterName=ContactList";
    HttpWebRequest request = HttpWebRequest.Create(requestString) as HttpWebRequest;
    request.Method = "GET";
    request.CookieContainer = AuthCookie;
    // Generating Http request.
    using (var response = request.GetResponse())
    {
        // Executing the request and output the result.
        using (var reader = new StreamReader(response.GetResponseStream()))
        {
            string responseText = reader.ReadToEnd();
            Console.WriteLine(responseText);
        }
    }
}

The added methods can be called in the main program method after successful authentication.

Authentication example
static void Main(string[] args)
{
    if (!TryLogin("Supervisor", "Supervisor"))
    {
        Console.WriteLine("Wrong login or password. Application will be terminated.");
    }
    else
    {
        try
        {
            // Calling methods for starting business processes.
            AddContact("John Johanson", "+1 111 111 1111");
            GetAllContacts();
        }
        catch (Exception)
        {
            // Exception Handling.
            throw;
        }
    };
    Console.WriteLine("Press ENTER to exit...");
    Console.ReadLine();
}
Result of executing the application
Launch the process from a client module
Advanced

To launch a process from the JavaScript code client schema:

  1. Add the ProcessModuleUtilities module as a dependency to the module of the page that was used for calling the service. This module provides a convenient interface for executing queries to the ProcessEngineService.svc sevice.
  2. Call the executeProcess(args) method of the ProcessModuleUtilities module by passing the args object over to it as a parameter with the following properties (table 1):

Table 1. Properties of the args object

 

 

Property Details
sysProcessName The name of the called process (not required if the sysProcessId property is defined).
sysProcessId The unique identifier of the called process (not required if the sysProcessName property is defined).
parameters

The object whose properties are the same as the properties of the called process incoming parameters.

Case description 

Add an action that will launch the “Conducting a meeting” business process to the account edit page. Pass the primary contact of the account as a parameter to the business process.

Source code 

You can download the package with case implementation using the following link.

Case implementation algorithm 

1. Creating the “Conducting a meeting” custom business process 

The case uses the “Conduct a meeting” business process described in the “Designing a linear process” and “How to work with emails” sections (fig. 1).

Fig. 1. Creating the “Conducting a meeting” source business process

After you create the business process, add the ProcessSchemaContactParameter incoming parameter to it. Specify “Unique identifier” in the Data type field of the parameter properties (fig. 2).

Fig. 2. Adding the incoming parameter

In the properties of the Call customer action (which is the first business process action), populate the Contact field with the business process incoming parameter (fig. 3).

Fig. 3. Passing the parameter to the process element

2. Creating the replacing edit page of the account and adding the action. 

Adding action to the edit page is covered in the “Add an action to the edit page” article.

Add the CallProcessCaption localizable string with an action caption (for example, “Schedule a meeting”) to the replacing module schema of the edit page and the account section schema.

Add the ProcessModuleUtilities module as a dependency to declaring the edit page module.

The source codes of the section schema and the section edit page are below.

3. Adding the necessary methods to schemas 

Use the executeProcess() method of the ProcessModuleUtilities module to launch the process. As a parameter, pass the object with the following properties: the created business process name, the object with initialized incoming process parameters.

In the below source code, it is implemented in the callCustomProcess() method. The isAccountPrimaryContactSet() method of verifying the availability of the primary contact and the getActions() method of adding action menu options are also implemented.

The source code of the edit page replacing module:

define("AccountPageV2", ["ProcessModuleUtilities"], function(ProcessModuleUtilities) {
    return {
        // Name of the edit page object schema.
        entitySchemaName: "Account",
        // Methods of the edit page view model.
        methods: {
            // Verifies if the [Primary contact] page field is populated.
            isAccountPrimaryContactSet: function() {
                return this.get("PrimaryContact") ? true : false;
            },
            // Overriding the base virtual method that returns edit page action collection.
            getActions: function() {
                // Parent method implementation is called to receive
                // the collection of initialized actions of the base page.
                var actionMenuItems = this.callParent(arguments);
                // Adding a separator line.
                actionMenuItems.addItem(this.getActionsMenuItem({
                    Type: "Terrasoft.MenuSeparator",
                    Caption: ""
                }));
                // Adding the [Conducting a meeting] menu option to the edit page action list.
                actionMenuItems.addItem(this.getActionsMenuItem({
                    // Binding the caption of the menu option to localizable string of the schema.
                    "Caption": { bindTo: "Resources.Strings.CallProcessCaption" },
                    // Binding the action handler method.
                    "Tag": "callCustomProcess",
                    // Binding the visibility property of the menu option to the value, which returns the isAccountPrimaryContactSet() method.
                    "Visible": { bindTo: "isAccountPrimaryContactSet" }
                }));
                return actionMenuItems;
            },
            // Action handler method.
            callCustomProcess: function() {
                // Receiving the identifier of the account primary contact.
                var contactParameter = this.get("PrimaryContact");
                // The object that will be transferred to the executeProcess() method as an argument.
                var args = {
                    // The name of the process that needs to be launched.
                    sysProcessName: "UsrCustomProcess",
                    // The object with the ContactParameter incoming parameter value for the CustomProcess process.
                    parameters: {
                        ProcessSchemaContactParameter: contactParameter.value
                    }
                };
                // Launch of the custom business process.
                ProcessModuleUtilities.executeProcess(args);
            }
        }
    };
});

Add the isAccountPrimaryContactSet() method implementation to the section schema for the correct action display in the menu when displaying the page with the vertical list in the combined mode.

The source code of the section schema replacing module:

define("AccountSectionV2", [], function() {
    return {
        // Name of the section schema.
        entitySchemaName: "Account",
        methods: {
            // Verifies if the [Primary contact] field of the selected record is populated.
            isAccountPrimaryContactSet: function() {
                // Defining the active record.
                var activeRowId = this.get("ActiveRow");
                if (!activeRowId) {
                    return false;
                }
                // Receiving the data collection of the section record list view.
                // Receiving the model of the selected account by the set value of the primary column.
                var selectedAccount = this.get("GridData").get(activeRowId);
                if (selectedAccount) {
                    // Receiving the model property — availability of the primary contact.
                    var selectedPrimaryContact = selectedAccount.get("PrimaryContact");
                    // The method returns true if the primary contact is established. Otherwise, it returns false.
                    return selectedPrimaryContact ? true : false;
                }
                return false;
            }
        }
    };
});

After you save the schemas and update the application page with clearing the cache, the new Schedule a meeting action will appear in the account page action menu (fig. 4). This action is available only if there exists a primary contact for the active list record. When executing the action, the “Conducting a meeting” custom business process will be launched. The primary contact of the account will be passed to the business process parameter (fig. 5)

Fig. 4. Launch of the business process by action on the edit page
Fig. 5. Result of the business process launch. Passing the parameter from the account edit page to the business process
ProcessEngineService.svc web-service
Advanced
// Request string.
GET Creatio_application_address/0/ServiceModel/ProcessEngineService.svc/ProcessSchemaName/Execute?ResultParameterName=resultParameterName&inputParameter=inputParameterValue

// Request headers.
ForceUseSession: true
BPMCSRF: authentication_cookie_value
// Status code.
Status: code

// Response body.

    "[
        {\"Id\":\"object1_id\",\"object1 field1\":\"object1 field_value1\",\"object1 field2\":\"object1 field_value2\"},
        {\"Id\":\"object2_id\",\"object2 field1\":\"object2 field_value1\",\"object2 field2\":\"object2 field_value2\"},
        ...
        {},
    ]"

Request string 

GET required

Request method to launch business process.

Creatio_application_address required

Creatio application address.

ServiceModel required

Path to ProcessEngineService.svc service. Immutable part of the request.

ProcessEngineService.svc required

Business process web-service address. Immutable part of the request.

ProcessSchemaName required

You can find the name of the business process schema in the Configuration section.

Execute required

Business Process launch Web-service method. Immutable part of the request.

ResultParameterName required

Variable for the process parameter code. The immutable part of the request.

resultParameterName required

The code of the process parameter that stores the result of the process execution. If this parameter is not specified, the web service will run the business process without waiting for the result of its execution. If the parameter code is not available in the process being called, the web service will return a null value.

inputParameter required

The incoming parameter codes of the business process. If you pass several incoming parameters, use a “&” character to combine them.

inputParameterValue required

The incoming parameter values of the business process.

Request headers 

ForceUseSession true required

The ForceUseSession header accounts for using the existing session. You do not need to use AuthService.svc in your request to the authentication service.

BPMCSRF authentication_cookie_value required

Authentication cookie.

Response body 

[]

Object collection.

{}

Instances of the object collection.

Id

Name of Id field.

object1_id, object2_id, ...

Collection object instance identifier.

object1 field1, object1 field2, ..., object2 field1, object2 field2, ...

Names of the field1, field2, ... of the object1, object2, ... collection object instances.

object1 field_value1, object1 field_value2, ..., object2 field_value1, object2 field_value2, ...

Values of the field1, field2, ... of the object1, object2, ... collection object instances.

Executing a separate element of the business process 

To execute a separate element of the business process, call the ExecProcElByUId web service method.

Request string
GET Creatio_application_address/0/ServiceModel/ProcessEngineService.svc/ExecProcElByUId/ProcessElementUID
GET required

Request method to launch business process.

Creatio_application_address required

Creatio application address.

ServiceModel required

Path to ProcessEngineService.svc service. Immutable part of the request.

ProcessEngineService.svc required

Business process web-service address. Immutable part of the request.

ExecProcElByUId required

Web service method to execute a separate element of the business process. You can only execute an element of the process that has been run. If the ExecProcElByUId process element has already been completed when calling the method, this element will not be executed. Immutable part of the request.

ProcessElementUID required

Id of the executed element of the process.