K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... ·...

56
© SourceCode Technology Holdings, Inc. All Rights Reserved. K2 Workflow APIs and Services - Runtime This learning module discusses the available APIs and services that are used to interact programmatically with K2 workflows at runtime. Contents Module Overview .................................................................................................................................. 4 Available Workflow Runtime APIs and Services................................................................................... 6 Workflow Client API .............................................................................................................................. 9 Workflow API objects: high-level overview ......................................................................................... 10 The Connection object ........................................................................................................................ 11 Opening a connection to the K2 Server .............................................................................................. 12 Starting a new workflow instance ....................................................................................................... 14 Retrieving the user’s Worklist ............................................................................................................. 16 Opening and Completing a WorklistItem ............................................................................................ 18 The WorklistItem object ...................................................................................................................... 20 The ProcessInstance object................................................................................................................ 22 The ActivityInstanceDestination object ............................................................................................... 24 Reading the connected User’s information ......................................................................................... 26 Other common Connection Methods .................................................................................................. 27 Common Workflow API calls: Summary ............................................................................................. 29 LAB 1: Using the K2 Workflow Client API ........................................................................................... 30 The Workflow Web Service (.asmx) ................................................................................................... 32 Workflow WCF services ...................................................................................................................... 34 LAB 2: Using the workflow WCF (SOAP) service ............................................................................... 38 Workflow REST Services .................................................................................................................... 39 LAB 3: Using the workflow REST service ........................................................................................... 43 WCF and REST services: Endpoints and Paths ................................................................................. 44 .NET API vs. WCF vs. REST services ................................................................................................ 46 The Workflow Management API ......................................................................................................... 47 Common Workflow Management Methods ......................................................................................... 49 Workflow Management API calls: Summary....................................................................................... 50 LAB 4: Using the K2 Workflow Management API ............................................................................... 52 Other common Workflow APIs ............................................................................................................ 54 REVIEW .............................................................................................................................................. 55 Additional Resources .......................................................................................................................... 56 300.NRT Version: 2 Revision: 1

Transcript of K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... ·...

Page 1: K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... · 2017-11-17 · 300.NRT-K2 Workflow APIs and Services - Runtime Module Overview ©

© SourceCode Technology Holdings, Inc. All Rights Reserved.

K2 Workflow APIs and Services - Runtime

This learning module discusses the available APIs and services that are used to interact programmatically with K2 workflows at runtime.

Contents

Module Overview .................................................................................................................................. 4

Available Workflow Runtime APIs and Services ................................................................................... 6

Workflow Client API .............................................................................................................................. 9

Workflow API objects: high-level overview ......................................................................................... 10

The Connection object ........................................................................................................................ 11

Opening a connection to the K2 Server .............................................................................................. 12

Starting a new workflow instance ....................................................................................................... 14

Retrieving the user’s Worklist ............................................................................................................. 16

Opening and Completing a WorklistItem ............................................................................................ 18

The WorklistItem object ...................................................................................................................... 20

The ProcessInstance object ................................................................................................................ 22

The ActivityInstanceDestination object ............................................................................................... 24

Reading the connected User’s information ......................................................................................... 26

Other common Connection Methods .................................................................................................. 27

Common Workflow API calls: Summary ............................................................................................. 29

LAB 1: Using the K2 Workflow Client API ........................................................................................... 30

The Workflow Web Service (.asmx) ................................................................................................... 32

Workflow WCF services ...................................................................................................................... 34

LAB 2: Using the workflow WCF (SOAP) service ............................................................................... 38

Workflow REST Services .................................................................................................................... 39

LAB 3: Using the workflow REST service ........................................................................................... 43

WCF and REST services: Endpoints and Paths ................................................................................. 44

.NET API vs. WCF vs. REST services ................................................................................................ 46

The Workflow Management API ......................................................................................................... 47

Common Workflow Management Methods ......................................................................................... 49

Workflow Management API calls: Summary ....................................................................................... 50

LAB 4: Using the K2 Workflow Management API ............................................................................... 52

Other common Workflow APIs ............................................................................................................ 54

REVIEW .............................................................................................................................................. 55

Additional Resources .......................................................................................................................... 56

300.NRT

Version: 2 Revision: 1

Page 2: K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... · 2017-11-17 · 300.NRT-K2 Workflow APIs and Services - Runtime Module Overview ©

300.NRT-K2 Workflow APIs and Services - Runtime

© SourceCode Technology Holdings, Inc. All Rights Reserved Page 2

The information contained in this document and its associated resources, including uniform resource locators and identifiers, is subject to change

without notice.

Unless explicitly stated otherwise, the people, organizations, companies, places, domain names, e-mail addresses, products, logos, and events

depicted are fictitious and no association with any actual people, organizations, companies, places, domain names, e-mail addresses, products,

logos, and events is intended, or should be inferred under any circumstance.

SourceCode may have patents, patent applications, trademarks, copyrights, and/or other intellectual property rights covering all or part of the

subject matter in this document and its associated resources. Except as expressly permitted by license agreement with SourceCode Technology

Holdings, Inc. the furnishing of this document and associated resources, does not grant any license whatsoever to these patents, trademarks,

copyrights, and/or other intellectual property.

This document and its associated resources are the sole property of SourceCode Technology Holdings, Inc. and SourceCode reserves all rights

related to the information contained herein. Without limiting rights under copyright, no part of this document or its associated resources, may be

reproduced, stored or introduced into a retrieval system, or transmitted in any form or by any means, without the prior written consent of

SourceCode Technology Holdings, Inc.

Copyright © 2011. SourceCode Technology Holdings, Inc. All rights reserved. SourceCode software products are protected by one or more U.S.

Patents. Other patents pending. SourceCode, K2, K2 blackpearl, K2 blackpoint, K2 connect, the four squares logo and K2 logotype are

registered trademarks or trademarks of SourceCode Technology Holdings, Inc. in the United States and/or other countries

The names of actual companies and products mentioned herein may be the trademarks of their respective owners.

Questions, Comments or Feedback about this training module?

Please E-mail [email protected] with your comments or feedback. We appreciate any feedback that helps us to

improve the quality of our learning material.

Page 3: K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... · 2017-11-17 · 300.NRT-K2 Workflow APIs and Services - Runtime Module Overview ©

300.NRT-K2 Workflow APIs and Services - Runtime

© SourceCode Technology Holdings, Inc. All Rights Reserved Page 3

Conventions The following table documents the conventions used throughout this module:

Convention Description

Bold Text With Border Represents commands, controls, items, menus, options, parameters, and file

and folder paths. For example, in an instruction to click on the OK button; look

for a control on the page with OK as its name. When you see text represented like this, you should see a control, window or field on the user interface with the same name.

Fixed-pitch font Represents text (or code) that must be entered exactly as shown. When you see text represented in this style, you should be typing this text into a textbox, control, code window or other UI component.

[Italic text in Square Brackets]

Represents variables or values to be selected from the K2 Context browser

Fixed-pitch italic

font

Represents additional instructions, explanations or a description of expected behavior in Demonstrations and Lab Exercises

<ALL CAPITALS> Represents a key to be pressed on the keyboard. For example, <CTRL> represents the Control key on the keyboard.

Represents a best practice. Best practices are the recommended approach or guidance for specific scenarios. When you see the Best Practice icon, consider how this practice impacts your requirements or how you can implement this practice in your environment.

Represents important information. Important information is highlighted in order to draw attention to a key piece of information, and typically serves as a warning or point you should bear in mind when using the K2 platform in your K2 solutions.

Represents a note. Notes explain a topic or provide additional information, and can provide a summary or explanatory point about a topic.

Explains a concept, or a provides an explanation for a step in an exercise

Represents a hint, tip or available tools and resources that can help you during the design and development cycles of a K2 solution.

Denotes technical information. This information is not vital in terms of meeting the goals of the learning module, but may be of interest to technical users.

Represents trivia. The text included next to this icon is for interest only – think of it as a quick break from learning about K2.

Estimated time to complete a task, step or exercise

Page 4: K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... · 2017-11-17 · 300.NRT-K2 Workflow APIs and Services - Runtime Module Overview ©

300.NRT-K2 Workflow APIs and Services - Runtime Module Overview

© SourceCode Technology Holdings, Inc. All Rights Reserved Page 4

Module Overview This learning module describes the various Application Programming Interfaces (API’s) and Services that can be used to interact programmatically with K2 workflows at runtime. These API’s and Services are typically used by developers when writing code to start workflows, retrieve K2 worklists and worklist items, complete worklist items, administer workflows and more. This module does not cover all possible workflow runtime interactions: instead, we will cover the most commonly-used interfaces and methods.

Target Audience This module is intended for technical roles like .NET developers, programmers, SharePoint developers and solution

architects. This module is not suitable for non-technical roles or participants that do not have experience with writing

.NET code.

Outcomes At the end of this module, participants will have a good understanding of the available APIs and Services used to

interact programmatically with K2 workflows at runtime. They will understand how to create custom code to retrieve

K2 tasks, start workflows, complete worklist items and administer K2 workflows. Participants will also understand the

basic principles behind interacting with K2 workflows programmatically.

Complexity This Module Level Definition

100 Introduction to the topic or overview and assumes little or no expertise with the topic being covered. Typically

level 100 modules cover concepts, functions, features and benefits.

200 Covers intermediate learning materials, assumes 100-level knowledge, and provides specific details about the

topic and a complete understanding of the features. 200-level training may discuss case studies that cover a breadth of common scenarios or explain how to use more advanced features.

300 Covers advanced learning materials and assumes 200-level knowledge, and an in-depth understanding of product features in a real-world environment. 300-level training provides a detailed technical subset of product technologies that illustrate specific aspects of the product that are key to improving performance or interoperability and include architecture, performance, migration, development and deployment.

400 Expert learning materials and assumes a deep level of technical knowledge and experience, as well as a detailed, thorough understanding of the topic. 400-level courses are essentially expert-to-expert sessions and the 400-level training content provides the means for customers to push products to maximum performance, achieve the broadest possible interoperability and create applications using the most advanced features.

Prerequisites and Required Knowledge This module requires that the participant has completed the following learning modules (or already has equivalent

functional knowledge of K2)

100.SEA Workflow Fundamentals

100.IAH Building Workflow Solutions with K2 Studio – Fundamentals

This learning module also refers to (or uses) other technologies. Because the purpose of this module is not to

instruct you on these other technologies, you should be familiar with the technologies, systems or approaches listed

below (to the required level of proficiency) in order to successfully complete this learning module.

Skill or Technology Proficiency

.NET Development with Visual Studio Intermediate-level experience writing .NET code with Visual Studio 2008 or 2010

Experience with referencing .NET assemblies, asmx web services and WCF services in .NET projects

SOA Architecture and Services (optional) Using .asmx, WCF and REST services to create applications

Web Development Intermediate-level experience creating ASP.NET interfaces

Page 5: K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... · 2017-11-17 · 300.NRT-K2 Workflow APIs and Services - Runtime Module Overview ©

300.NRT-K2 Workflow APIs and Services - Runtime Module Overview

© SourceCode Technology Holdings, Inc. All Rights Reserved Page 5

Compatibility This learning module is compatible with the following K2 products and versions

Product Version Notes

K2 blackpearl 4.6.x or later

Virtual Environment Prerequisites This learning module has prerequisites which need to be configured to support the lab exercises. Follow the

instructions below to set up the prerequisites for this learning module.

This script should be executed in the Virtual Server environment which accompanies this learning module.

Step Instructions

Step 1: Install the prerequisites for this training module in the Virtual Server environment

A script is provided that will create all the prerequisites for this module.

Tasks:

Log on to the virtual environment with the following credentials: 1.

Username: Denallix\Administrator

Password: K2pass!

Copy the file K2 Learning-300.NRT.exe provided with this learning module to any 2.

location in the Virtual Server environment. You may download the .exe file from the

K2 Learning Module Installers (Download) shortcut on the VPC desktop, or

directly from the following URL: ftp://K2LearningInstallers:[email protected]/K2 Learning-

300.NRT.exe

Ask your instructor for help, if needed.

Double-click the file K2 Learning-300.NRT.exe to start the extract process. You 3.

should extract the files to

C:\K2 Learning (this value should be set correctly by default)

After the extract process has completed, double-click the file 4.

C:\K2 Learning\300.NRT\Setup\SetupPreRequisites.bat to install and deploy the

prerequisites for this training module. The installation process may take up to 5 minutes to complete

Once you see the success message (Completed setting up prerequisites for 5.

learning module…) close the command window.

.

Page 6: K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... · 2017-11-17 · 300.NRT-K2 Workflow APIs and Services - Runtime Module Overview ©

300.NRT-K2 Workflow APIs and Services - Runtime Available Workflow Runtime APIs and Services

© SourceCode Technology Holdings, Inc. All Rights Reserved Page 6

Available Workflow Runtime APIs and Services

There are several APIs and services that developers can use to interact with K2 workflows programmatically at

runtime. The most commonly-used APIs and services are listed below – we will look at each of these in more detail

in the subsequent topics and exercises of this learning module.

Technology Available interfaces Typical use

.NET APIs SourceCode.Workflow.Client.dll Start workflows, retrieve worklist items, complete workflow tasks

SourceCode.Workflow.Management.dll Administer running workflows, set workflow permissions, manage workflow versions

SmartObject ADO Provider and SmartObject client dll

If a workflow has been exposed as a K2 SmartObject, the workflow methods will be exposed as SmartObject methods and can be accessed with the SmartObject APIs*

.asmx Web Services

http://[servername]/K2Services/ws.asmx?wsdl

Start workflows; retrieve worklist items, complete workflow tasks. This service is intended as a legacy-protocol interface. It has been superseded by the WCF and REST services, but it is still available for applications that require an .asmx-based service interface.

WCF Services

http://[servername]/K2Services/WCF.svc Start workflows, retrieve worklist items, complete workflow tasks

http://[servername]/K2Services/SyncWCF.svc

Synchronous service to start workflows, retrieve worklist items, complete workflow tasks, mostly used for batch-processing

http://[servername]:[port]/SmartObjectServices/wcf/[smartobject]

If a workflow has been exposed as a K2 SmartObject, the workflow methods will be exposed as SmartObject methods and can be accessed through the K2 SmartObject WCF services*

The WCF services are intended for use by .NET applications that require a service-based interface for integration. SOA-centric enterprise platforms and applications are ideally suited for this interface.

Available Workflow Runtime APIs and Services .NET APIs

SourceCode.Workflow.Client.dll

SourceCode.Workflow.Management.dll

SmartObject ADO provider and SmartObject client dll*

.asmx Web Services http://[servername]/K2Services/ws.asmx?wsdl

Intended for legacy compatibility

WCF Services http://[servername]/K2Services/WCF.svc and SyncWCF.svc

K2 SmartObject WCF services*

http://[servername]:[port]/SmartObjectServices/wcf/[smartobject]

REST Services http://[servername]/K2Services/REST.svc and SyncRest.svc

K2 SmartObject REST services*

http://[servername]:[port]/SmartObjectServices/rest/[smartobject]

*If the workflow is exposed as a SmartObject. See module 300.YOK for more on using these APIs

Page 7: K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... · 2017-11-17 · 300.NRT-K2 Workflow APIs and Services - Runtime Module Overview ©

300.NRT-K2 Workflow APIs and Services - Runtime Available Workflow Runtime APIs and Services

© SourceCode Technology Holdings, Inc. All Rights Reserved Page 7

Technology Available interfaces Typical use

REST Services

http://[servername]/K2Services/REST.svc Start workflows, retrieve worklist items, complete workflow tasks

http://[servername]/K2Services/SyncREST.svc

Synchronous service to start workflows, retrieve worklist items, complete workflow tasks, mostly used for batch-processing

http://[servername]:[port]/SmartObjectServices/rest/[smartobject]

If a workflow has been exposed as a K2 SmartObject, the workflow methods will be exposed as SmartObject methods and can be accessed through the K2 SmartObject REST services*

The REST services are intended for use by applications that require a REST-based interface for integration. Modern applications (especially lightweight clients like Smartphone applications and JavaScript-heavy web pages are ideally suited for REST-based integration since the technology is very lightweight and is easily consumed by any technology that understands common web protocols.

*Note:

If the workflow was deployed with the Generate workflow SmartObjects option selected as shown below, the

workflow will be exposed a K2 SmartObject with methods and properties. It is not necessary to enable this setting to

interact programmatically with a workflow, but if it was enabled, the workflow is also exposed through the normal K2

SmartObject APIs and Services. For more on the SmartObject APIs and services, please refer to the K2 learning

module 300.YOK K2 SmartObject APIs and Services - Runtime

Setting the option to generate SmartObjects for a workflow when it is deployed

Page 8: K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... · 2017-11-17 · 300.NRT-K2 Workflow APIs and Services - Runtime Module Overview ©

300.NRT-K2 Workflow APIs and Services - Runtime Available Workflow Runtime APIs and Services

© SourceCode Technology Holdings, Inc. All Rights Reserved Page 8

The resulting Workflow SmartObjects

Page 9: K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... · 2017-11-17 · 300.NRT-K2 Workflow APIs and Services - Runtime Module Overview ©

300.NRT-K2 Workflow APIs and Services - Runtime Workflow Client API

© SourceCode Technology Holdings, Inc. All Rights Reserved Page 9

Workflow Client API

The workflow Client API refers to the .NET assembly SourceCode.Workflow.Client.dll. This assembly exposes

several classes and methods that are used by developers when interacting programmatically with a deployed

workflow.

The Workflow.Client assembly is installed in the GAC of the K2 server and on developer workstations when the K2

Studio/K2 for Visual Studio or K2 Core components are installed. On a machine with K2 Server, K2 Workspace or

the K2 developer tools you can find the assembly at the following location:

[Program Files Directory]\K2 blackpearl\Bin\SourceCode.Workflow.Client.dll

In addition to the Sourcecode.Workflow.Client assembly it is sometimes necessary to copy the assembly SourceCode.HostClientAPI.dll as well, since this assembly is used to construct more advanced K2 connection strings. We recommended that the copied SourceCode.[…] assemblies be updated whenever the K2 installation is updated, since the client assembly may contain enhancements and additions. You should have a maintenance procedure in place if you are using the workflow client assembly on another machine. Most organizations use a SOA-based approach nowadays to limit the impact of updating the K2 platform on the applications that use the platform.

In practice, the SourceCode.Workflow.Client assembly is often used to create custom task lists, to start workflows or

complete workflow tasks (knows as worklist items) from custom user interfaces like ASP.NET web pages, and to

create alternative interfaces or tools to allow users to maintain their out-of-office status and worklist items. The

workflow client is also often used to create automated testing code or applications that are executed against a

workflow definition to verify that the workflow is behaving as expected.

To help you explore the API, we have provided a sample application with sample code for the most common workflow client methods. Please refer to the project K2Learning.Samples.WorkflowRuntime.WorkflowClientAPI in the solution that accompanies this module, located at C:\K2 Learning\300.NRT\SampleProject \WorkflowRuntime.SampleProjects.sln

Workflow Client API*

SourceCode.Workflow.Client.dll

Runtime interaction with workflows, worklists and worklist items

This is the API behind the K2 worklist

Common use cases

Start workflow programmatically

Create custom worklists

Open and complete K2 tasks (worklist items) using a custom User Interface

Manage own worklist items (redirect, sleep, delegate etc.)

Manage own Out-of-Office status

Automated testing of workflows

*Sample code for the Workflow Client API is provided in the project

K2Learning.Samples.WorkflowRuntime.WorkflowClientAPI

provided with this learning module.

Open the solution located at

C:\K2 Learning\300.NRT\SampleProject\WorkflowRuntime.SampleProjects.sln

Page 10: K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... · 2017-11-17 · 300.NRT-K2 Workflow APIs and Services - Runtime Module Overview ©

300.NRT-K2 Workflow APIs and Services - Runtime Workflow API objects: high-level overview

© SourceCode Technology Holdings, Inc. All Rights Reserved Page 10

Workflow API objects: high-level overview

The key to using the workflow runtime APIs is to have a good high-level understanding of the main objects that are

available. The diagram in the slide for this topic illustrates the relationship between the main objects, and the table

below briefly summarizes these objects.

The workflow WCF and REST services use very similar objects, so it is worthwhile to complete the next series of topics and the exercise to become familiar with the workflow runtime objects, even if you do not intend to use the Workflow.Client.dll assembly.

Object

High-level description

Connection The connection is the main entry point to the K2 server and most methods are exposed once a connection object is instantiated. Users cannot interact with the K2 server until a connection has been opened.

ProcessInstance A Process Instance is a representation of the workflow as a .NET object, and is usually instantiated by creating a new process instance or reading a worklist item.

The process instance is essentially the run-time instance of a workflow definition.

Worklist The Worklist is a collection of Worklist Items (K2 Tasks) that are assigned to a user. After establishing a connection under a certain user’s credentials the Worklist will represent all the current tasks for that user.

WorklistItem A worklistItem refers to a single K2 task and is associated with a specific Client Event in a particular workflow. A Worklist Item always exists in the context of a process instance. When the user completes their worklist item, the workflow usually continues based on the decision that the user indicated in that task.

ServerItem A server item is a special kind of "worklist item". Think of it as an ownerless worklist item. This is usually used when the K2 server needs to wait for an external system to complete a task. Since there is no user involvement for this task, it does not make sense to assign the task to a user.

WorklistCriteria Worklist Criteria are used to build up a filter-and-sorting object before retrieving a user’s worklist. This is useful when users can potentially have very large worklists and you want to limit the amount of data that has to go across the wire.

Workflow API objects: high-level overview

Connection

ProcessInstance

Worklist

WorklistItem

ServerItem

WorklistCriteria

SourceCode.WorkFlow.Client

These objects are similar in the WCF and REST services

The following slides describe the objects in more detail

Page 11: K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... · 2017-11-17 · 300.NRT-K2 Workflow APIs and Services - Runtime Module Overview ©

300.NRT-K2 Workflow APIs and Services - Runtime The Connection object

© SourceCode Technology Holdings, Inc. All Rights Reserved Page 11

The Connection object

The Connection object is the entry point for subsequent calls to the K2 server. You cannot perform any operations

on the K2 server without having a Connection object instantiated and a connection opened. Under the covers, the

Connection object uses RPC calls to the K2 server to execute methods with a proprietary message format. By

default, communication to the K2 server when using the Workflow Client API is via Port 5252, although you may

have selected a different port when installing K2.

If you are using the Workflow Client dll in a client application, beware of any firewall rules that may block communication on port 5252. If you need to interact with K2 from applications behind a firewall, you should consider using the WCF workflow web service instead, since that service typically uses port 80 (HTTP) or 443 (HTTPS) for communication. When using the service-based APIs, it is not necessary to instantiate or open a connection since the service will manage the connection internally.

You would typically instantiate the Connection object with the new keyword, open the connection and then perform

one or more actions before closing the connection. The next topic discusses opening a connection in more detail,

and then we’ll look at some of the methods you can call on the connection once it has been opened.

Page 12: K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... · 2017-11-17 · 300.NRT-K2 Workflow APIs and Services - Runtime Module Overview ©

300.NRT-K2 Workflow APIs and Services - Runtime Opening a connection to the K2 Server

© SourceCode Technology Holdings, Inc. All Rights Reserved Page 12

Opening a connection to the K2 Server

The simplest way to open a connection is just to specify the K2 server name, in which case the connection to K2 will

be established as the current Windows user account (so-called "Integrated authentication"). The code snippet below

shows how to open and close a K2 connection in the simplest possible way, using the current user’s Active

Directory credentials and opening a connection on the default 5252 port.

//instantiate the connection object

SourceCode.Workflow.Client.Connection K2Conn = new

SourceCode.Workflow.Client.Connection();

//simple open using only a server name.

K2Conn.Open("localhost");

//next, do some work with the connection (see following topics for more)

//Close the connection when you're done with it

K2Conn.Close();

If you need to build up a more advanced connection (for example a different security provider, username or port)

you can import the SourceCode.Hosting.Client namespace from the SourceCode.HostClientAPI.dll

assembly and instantiate a ConnectionStringBuilder object to construct a more advanced connection string.

This is especially important when you need to pass through alternative security credentials or are using a custom

security provider to authenticate a non-Active Directory user account. The code snippet below illustrates how to

build up a custom connection string and then open the connection to the K2 server.

//creating a more advanced connection with the connection string builder

SourceCode.Hosting.Client.BaseAPI.SCConnectionStringBuilder K2ConnStringBuilder = new

SourceCode.Hosting.Client.BaseAPI.SCConnectionStringBuilder();

K2ConnStringBuilder.Host = "localhost"; //K2 server name or the name of the DNS entry

pointing to the K2 Farm

K2ConnStringBuilder.Authenticate = true; //specify whether to authenticate the user's

credentials against the security provider. This is usually set to true

K2ConnStringBuilder.UserID = "administrator"; //a specific username

K2ConnStringBuilder.Password = "K2pass!"; //the user's password, unencrypted

Opening a connection to the K2 Server* Connection object is the entry point to other method calls

Instantiation:

Open() Method: Establishes a connection to the K2 Server

Commonly-used Overloads

K2Conn.Open("servername");

K2Conn.Open(K2ConnectionString);(Use the SourceCode.Hosting.Client.BaseAPI

namespace to build up a connection string with the

SCConnectionStringBuilder class)

Once you have an open connection, the other objects can be

instantiated and other methods can be called

IMPORTANT: Remember to close the connection once you

are done with it, or wrap the Connection object into a using statement

K2Conn.Close();

using (Connection K2Conn = new Connection()) {…}

Connection

Open

CreateProcessInstance

StartProcessInstance

OpenWorklist

ImpersonateUser

OpenWorklistItem

OpenServerItem

Connection K2Conn = new Connection();

*see K2ConnectionSamples method for some sample code

Page 13: K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... · 2017-11-17 · 300.NRT-K2 Workflow APIs and Services - Runtime Module Overview ©

300.NRT-K2 Workflow APIs and Services - Runtime Opening a connection to the K2 Server

© SourceCode Technology Holdings, Inc. All Rights Reserved Page 13

K2ConnStringBuilder.Port = 5252; //if K2 was configured to run on a non-standard

port, you can specify the port number here

K2ConnStringBuilder.IsPrimaryLogin = true; //this is normally set to true, unless you

are using cached security credentials

K2ConnStringBuilder.SecurityLabelName = "K2"; //if using a different security

provider, specify the label of the security provider here

//opening a K2 connection with the advanced connection string

K2Conn.Open(K2ConnStringBuilder.ToString());

//now do something with the connection

//closing a connection: you must always close the K2 connection when you are done

with it

K2Conn.Close();

You should always close the K2 connection when you have finished the necessary calls to the K2 server. This helps to free up resources on the K2 server and will make your code perform better.

Two mechanisms you may use to do this is to wrap the Connection object into a using

statement, or to call the connection.Close() method in a finally block to ensure that the

connection is always closed.

Page 14: K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... · 2017-11-17 · 300.NRT-K2 Workflow APIs and Services - Runtime Module Overview ©

300.NRT-K2 Workflow APIs and Services - Runtime Starting a new workflow instance

© SourceCode Technology Holdings, Inc. All Rights Reserved Page 14

Starting a new workflow instance

There are three major steps to start a workflow programmatically, after you have opened a connection to the K2

server:

1) Instantiate an object that represents an instance of a specific workflow definition

2) Set the Folio, datafield values and other properties of the workflow instance

3) Start the workflow instance

Each step has its own overloads, but for the purposes of this exercise we will just look at the most commonly-used

methods. The snippet below illustrates how you may perform the three major steps in code:

//Step 1: instantiate the process instance

ProcessInstance K2Proc = K2Conn.CreateProcessInstance(@"projectname\workflowname");

//specify the full name of the workflow

//Step 2: now that we have the process as an object in memory; we can set some

properties before starting the process

K2Proc.Folio = "ProcessFolio";

K2Proc.Priority = 1;

//datafields should be accessed by name. Be aware of data types when setting values,

and ensure that the data field names are spelled correctly!

K2Proc.DataFields["String DataField"].Value = "somevalue";

K2Proc.DataFields["Integer Datafield"].Value = 1;

K2Proc.DataFields["Date Datafield"].Value = DateTime.Now;

//XML fields are set using an XML-formatted string

XmlDocument xmlDoc= new XmlDocument(); //TODO: set up the XML document as required,

or construct a valid XML string somehow

K2Proc.XmlFields["XML DataField"].Value = xmlDoc.ToString();

//Step 3: once you have set all the necessary values, start the process

K2Conn.StartProcessInstance(K2Proc);

Notice that the datafields in a process object are NOT strongly-typed. You will need to read and write datafields by passing the name of the field as a string-indexed value.

Starting a new workflow instance*

CreateProcessInstance(“ProcName”) method:

Returns a single instance of a process/workflow based

on the process definition

Must pass the name of the process as a parameter

ProcessInstance K2Proc = K2Conn.CreateProcessInstance(“processfullname");

Once you have the ProcessInstance, you can set the Folio,

Datafields and Priority of the processK2Proc.Folio = “FolioValue”;

StartProcessInstance(ProcInst) method:

Starts the Process Instance

Commonly-used Overloads

K2Conn.StartProcessInstance(K2Proc)

K2Conn.StartProcessInstance(K2Proc, bSync)

Connection

Open

CreateProcessInstance

StartProcessInstance

OpenWorklist

ImpersonateUser

OpenWorklistItem

OpenServerItem

*see StartWorkflowSamples method for some sample code

Page 15: K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... · 2017-11-17 · 300.NRT-K2 Workflow APIs and Services - Runtime Module Overview ©

300.NRT-K2 Workflow APIs and Services - Runtime Starting a new workflow instance

© SourceCode Technology Holdings, Inc. All Rights Reserved Page 15

The Sync overload

You may notice that the StartProcessInstance method has an overload method that accepts a parameter

called Sync.

This setting effectively determines how quickly K2 will respond with a success message after the workflow has

started, and is most commonly used in screen-flow or automated testing scenarios. If you start a workflow

Synchronously (in other words, the Sync parameter’s value is True), K2 will not respond with a success message

until the next wait-state in the workflow is reached. A wait-state could be something like an Activity with a client

event or an activity with a start rule. Essentially, this parameter tells K2 to perform all the activities and events in the

workflow until the workflow is waiting for something or someone. Only once this wait-state is reached the method will

return to the calling application. When starting a workflow is this manner, you are ensured that all the intermediate

workflow activities and events leading up to the wait state have been completed.

This Synchronous-style of execution is mostly used in screen-flow applications or automated testing, because you

want to be sure that the first client event is created before the StartProcessInstance call returns. When the call

returns, you would normally search through the user’s worklist for the resulting task and then perform the next

action.

In the majority of cases you will want to start a workflow asynchronously because you do not need to wait for

activities or events to complete. This is the default behavior, unless you specifically override by setting the Sync

parameter to true

Starting workflows synchronously (Sync=true) is slower than starting workflows

asynchronously (Sync=false), and you should not use the Synchronous-style execution

unless there is a specific reason to do so. Remember that K2 is not designed to be a short-lived application-level workflow engine. While you CAN use it as such with Synchronous execution, it is not the recommended use.

Page 16: K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... · 2017-11-17 · 300.NRT-K2 Workflow APIs and Services - Runtime Module Overview ©

300.NRT-K2 Workflow APIs and Services - Runtime Retrieving the user’s Worklist

© SourceCode Technology Holdings, Inc. All Rights Reserved Page 16

Retrieving the user’s Worklist

Another common requirement is to create a customized K2 worklist or to retrieve all tasks for a user. The

OpenWorklist method is the most-commonly used approach to retrieve tasks for a particular user. The

OpenWorklist method returns a Worklist object, which is contains a collection of WorklistItem.

The code snippet below shows how to retrieve a user’s worklist in the simplest possible way (after you have opened

a connection to the K2 server):

//retrieve the entire worklist for the current user

Worklist K2WList = K2Conn.OpenWorklist();

int numberOfTasks = K2WList.TotalCount;

//once you have retrieved the worklist, you can iterate over the worklist items in

the worklist

foreach (WorklistItem K2WLItem in K2WList)

{

//do something with the worklist

}

Using WorklistCriteria It is quite possible that a user may have hundreds or even thousands of tasks on their worklist and you want to limit

the number of tasks returned, or you may want to locate tasks based on a specific set of search criteria. To limit the

number of worklist items returned by the OpenWorklist method, you can instantiate and set up a

WorklistCriteria object to build up a combination of filter and/or sorting statements, and then pass this object

to the Openworklist method.

The code snippet below shows a simple example of a worklist criteria object where we want to retrieve all workflows

where the Folder name is K2Learning, the process Priority is 1 and we want to return the worklist sorted by the

Process start date, descending.

//instantiate a WorklistCriteria object

WorklistCriteria K2Crit = new WorklistCriteria();

//you can set up various combinations of filters and sorts in the criteria object.

Refer to the product documentation for more samples

Retrieving the user’s Worklist* OpenWorklist method:

Returns the Worklist for a user

The Worklist is a collection of Worklist Items (tasks)

Commonly-used Overloads

Worklist K2WList = K2Conn.OpenWorklist();

WorklistCriteria K2Crit = new WorklistCriteria();//set up the criteria and then call

Worklist K2WList = K2Conn.OpenWorklist(K2Crit);

Use WorklistCriteria to reduce the size of the returned worklist

You can iterate over the collection of worklist items

foreach (WorklistItem K2WLItem in K2WList){//do something with the K2WLItem}

WARNING: Retrieving the worklist can be an expensive operation. Use

WorklistCriteria and do not call OpenWorklist recursively

Connection

Open

CreateProcessInstance

StartProcessInstance

OpenWorklist

ImpersonateUser

OpenWorklistItem

OpenServerItem

*see OpenWorklistSamples method for some sample code

Page 17: K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... · 2017-11-17 · 300.NRT-K2 Workflow APIs and Services - Runtime Module Overview ©

300.NRT-K2 Workflow APIs and Services - Runtime Retrieving the user’s Worklist

© SourceCode Technology Holdings, Inc. All Rights Reserved Page 17

//here, we are filtering for all workflows for the project K2Learning where the

priority equals 1. We want to sort the task list by workflow start date

K2Crit.AddFilterField(WCField.ProcessFolder, WCCompare.Equal, "K2Learning");

K2Crit.AddFilterField(WCLogical.And, WCField.ProcessPriority, WCCompare.Equal, 1);

K2Crit.AddSortField(WCField.ProcessStartDate, WCSortOrder.Descending);

//retrieve the worklist with the criteria

Worklist K2WList = K2Conn.OpenWorklist(K2Crit);

Returning the worklist can be an "expensive" operation and we recommend using

WorklistCriteria to limit the number of worklist items returned.

You should not retrieve the entire worklist recursively, since this can negatively impact the performance of the K2 server as well.

Page 18: K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... · 2017-11-17 · 300.NRT-K2 Workflow APIs and Services - Runtime Module Overview ©

300.NRT-K2 Workflow APIs and Services - Runtime Opening and Completing a WorklistItem

© SourceCode Technology Holdings, Inc. All Rights Reserved Page 18

Opening and Completing a WorklistItem

In a workflow, Client Events must be completed by a user before the workflow can continue. These Client Events

are always associated with a K2 WorklistItem at runtime.

Remember that the OpenWorklist method only returns a collection of worklist items. If you wanted to open a user

task, update some data and complete the task, you will need to use the WorklistItem object.

You can locate a worklist item in two ways: the first (more efficient) way is to use the task’s Serial Number and call

the OpenWorklistItem(serialNumber) method. This will return a WorklistItem object which you can then

use to update and complete the user task. The alternative approach (not recommended due to performance) is to

return the user’s worklist with WorkListCriteria and then locate the specific task you are looking for by iterating

over the worklist items.

The Serial Number for a task is normally appended to the Client Event URL as a query string parameter. When

using the Client Event wizard in a workflow, you should see where K2 appends the serialnumber for the task to the

Web Page URL:

Appending the Serial Number in a client event

The code snippet illustrates how to open, update and the complete a worklist item, assuming you had the Serial

Number already

//to open a worklist item you require at least the item's serial number

//opening a worklist item without any overrides will automatically set the item's

status to "Opened" by the connected user.

WorklistItem K2WListItem = K2Conn.OpenWorklistItem(serialnumber);

//once you have opened the item, you can read data from the item or update data in

the workflow

string oldFolio = K2WListItem.ProcessInstance.Folio;

Opening and Completing a WorklistItem* OpenWorklistItem() Method

Obtain a handle to a specific Worklist Item based on the item’s serial number

Serial number is usually passed as a query string

parameter

Format: [ProcessInstanceID]_[ActivityDestinationInstanceID]

Can also be obtained by iterating through the Worklist object

Commonly-used Overloads

WorklistItem K2WLItem = K2Conn.OpenWorklistItem(serialnumber);

K2WLItem = K2Conn.OpenWorklistItem(serialnumber,"ASP", bAlloc, bIgnoreStatus);

You can update the workflow or data after opening the task

K2WLItem.ProcessInstance.Folio = "newFolio";

To complete a worklist item, execute one of the available actions

K2WLItem.Actions["ActionName"].Execute();

Connection

Open

CreateProcessInstance

StartProcessInstance

OpenWorklist

ImpersonateUser

OpenWorklistItem

OpenServerItem

*see OpenWorklistItemSamples method for some sample code

Page 19: K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... · 2017-11-17 · 300.NRT-K2 Workflow APIs and Services - Runtime Module Overview ©

300.NRT-K2 Workflow APIs and Services - Runtime Opening and Completing a WorklistItem

© SourceCode Technology Holdings, Inc. All Rights Reserved Page 19

K2WListItem.ProcessInstance.Folio = "NewFolio";

K2WListItem.ProcessInstance.DataFields["String DataField"].Value = "updatedvalue";

//to update the worklist item and finish the task, you must call the Action.Execute

method

//the workflow will then continue executing according to the action selected

//warning: you must select one of the available actions for the current task,

otherwise an error will be reported

K2WListItem.Actions["Approve"].Execute();

The worklist item is completed by executing one of the available Actions for the task. These values are string-based, so be sure to select a valid input for the Execute method. In most cases, you would iterate over the collection of available actions so that the user interface always has valid values that the user can select from. The example below shows how

to read the list of available actions once you have retrieved the WorklistItem:

//to get the available actions for the task, query the Actions

collection

foreach (SourceCode.Workflow.Client.Action action in

K2WListItem.Actions)

{

//do something with the actions. Normally, you would output the

available actions into a drop-down list or perhaps generate new button

controls for each available action

}

In the next topic, we will look a little deeper into the WorklistItem object.

Page 20: K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... · 2017-11-17 · 300.NRT-K2 Workflow APIs and Services - Runtime Module Overview ©

300.NRT-K2 Workflow APIs and Services - Runtime The WorklistItem object

© SourceCode Technology Holdings, Inc. All Rights Reserved Page 20

The WorklistItem object

As discussed in the previous topic, the WorklistItem object is the mechanism used to open and complete Client

Event tasks in a workflow instance. Each WorkList Item has a unique serial number, and any user who attempts to

open and complete a worklist item will need to "own" the serial number for that task. If they do not, K2 will report an

error along the lines of "worklist item nnn_mmm not found for domain\user". This error indicates that the connected

user does not have permission to open the task, or the task may already have been completed.

The table below lists the most common properties and methods for a worklist item.

Properties Property High-level description

Actions This is a collection of the available Actions that the current user can take on the item. The Actions are defined in the workflow design, and may be security-trimmed if you have set Action-level permissions for the client event in the K2 workspace.

Status This property represents the status of the worklist item. By default, when an item is Opened by a user the status changes to "Allocated", but this behavior can be overridden with the appropriate overload method.

The possible statuses for a worklist item are: 0 = Available. The item has not been opened yet. 1 = Open. The item was previously opened by the current user. 2 = Allocated. The item was opened by another user. 3 = Sleep. The item was set to "sleep" for a specified amount of time. 4 = Completed. The item was already completed by this or another user. Depending on the Slot configuration for the activity, it may be possible for multiple users to open the same task, but in the majority of cases, once a single user has opened the task, the task Status is "Open" for that user and "Allocated" for everyone else.

SerialNumber A unique serial number for each instance of the task. A serial number consists of the Process Instance ID and the Activity Destination Instance Id:

ProcInstId_ActInstDestId

The WorklistItem object Properties:

Actions: Collection of Actions (as defined in K2 Designer) that user

can take on the item.

Status: the current status of the item

SerialNumber: a unique ID for the task

ProcessInstance: The workflow instance associated with the

task

ActivityInstanceDestination: The Slot associated with the

task

EventInstance: The workflow Event associated with the

task

Methods:

Open: Change the Status of the Item to Open and allocate

a destination slot

Redirect: Moves the item to another user’s Worklist

Delegate: Allows delegated user to see and action the item,

but original destination can still see and action the item

GotoActivity: Moves a Process Instance to another activity

Release: Will “undo” the Open call, releasing the slot back to the group

Sleep: Changes the items status to Sleep

SerialNumber[RO]

ActivtyInstDest [RO]

ProcessInstance [RO]

EventInstance [RO]

Status [RO]

Data [RO]

ID [RO]

WorklistItem Properties

Actions[RO]

Page 21: K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... · 2017-11-17 · 300.NRT-K2 Workflow APIs and Services - Runtime Module Overview ©

300.NRT-K2 Workflow APIs and Services - Runtime The WorklistItem object

© SourceCode Technology Holdings, Inc. All Rights Reserved Page 21

Property High-level description

ProcessInstance This object represents the runtime workflow instance of the workflow associated with the task. See the topic for more detail on this object.

ActivityInstanceDestination This object represents a "copy" of the activity that was created for the current destination. Depending on the configuration of the activity and destination rule, there may be multiple activity instance destinations for each user that the task has been assigned to.

See the topic for more information on this object.

EventInstance This object represents the Client Event associated with the worklist item. Most often, you would use this object to read the configured properties of the event such as the priority, description or meta data for the event.

Methods Property High-level description

Open This is the method used to Open (or "assign") the task to the current user. The overrides allow you to open the task without assigning it, or to open the task and

ignore the status of the task. If the task is allocated to another user, you may get

an error when executing the open method, hence the override.

Redirect Use this method to redirect the current task to another user. Redirect will remove the task from the current user’s task list and it will only be available to the new user.

Delegate Use this method to create a "copy" of the task for another user. Both the current user and then new user will be able to open and complete the task, but if either of them does, the task will be removed from the user user’s task list.

GotoActivity Forces the workflow instance to go to a specific activity. The ExpireAll parameter

in one of the overloads is mostly used when parallel activities exist. If the

ExpireAll value is True, all the existing activities will be expired and the workflow

will go to the specified activity. If the value is false, only the current activity will be expired.

Note: when you call this method, K2 will not execute the succeeding rule or any lines that come out of the activity: the workflow will go directly to the specified activity.

Release Use this method to release the task back to the group, changing its status from

Allocated back to Available for all users. Most often, this method is used when

the user decides they do not want to complete the task and want to make it available for the original set of users again.

Sleep Use this method to set the worklist item status to Sleep temporarily. By default,

sleeping items are not displayed on the user’s worklist, and K2 will automatically "wake" the item when the specified interval has passed.

Hint: If you want to "wake" and item manually, execute the Release() method for

the worklist item

Page 22: K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... · 2017-11-17 · 300.NRT-K2 Workflow APIs and Services - Runtime Module Overview ©

300.NRT-K2 Workflow APIs and Services - Runtime The ProcessInstance object

© SourceCode Technology Holdings, Inc. All Rights Reserved Page 22

The ProcessInstance object

The ProcessInstance object represents an instance of a specific workflow definition at runtime. Each process

instance is distinct and unique, and is identified with a integer-based identifier commonly called the

ProcessInstanceId. K2 will also automatically populate some of the read-only properties for the process instance

(such as the Start Date and Originator) when the workflow is started.

The ProcessInstance object exposes some information that was captured as part of the workflow design, such

as the expected duration, process name, comments and so on. Some of these properties are read-only (such as the

process name and description) while other values can be modified while the workflow is active (such as the process

folio, datafield values and process priority).

As a rule of thumb, remember that only the user who currently has a task in the workflow will be able to modify

anything in the workflow. So when a user is starting a new workflow, the code can set the datafield values for the

process instance, but after the workflow has started, if that user does not have a task in the workflow they cannot

update the data or status of the workflow. Think of this as a mechanism that protects the integrity of a workflow at

runtime.

The ProcessInstance object itself is instantiated either by the CreateProcessInstance() method, and this is

used to set or read properties form the workflow before it is started. After the workflow has started, you can access

the ProcessInstance object by reading the ProcessInstance property of a WorklistItem or a

ServerItem. For the most common uses of the workflow runtime APIs, those are the only ways to get a hold of the

process instance which implies that the connected user account must have permission to access the process

instance.

The ProcessInstance object

Object gets instantiated by the following methods:

CreateProcessInstance method

K2Conn.CreateProcessInstance("HR\LeaveRequest");

ProcessInstance property of WorklistItem object

K2WItem = K2Conn.OpenWorklistItem(serialNo);

K2Proc = K2WItem.ProcessInstance;

ProcessInstance property of ServerItem object

K2SItem = K2Conn.OpenServerItem(serialNo);

K2Proc = K2SItem.ProcessInstance;

DataFields:

The Collection of Data Fields for this Process Instance.

K2Proc.DataFields["FieldName"].Value;Value

XMLFields:

The Collection of XML Fields for this Process Instance

K2Proc.XMLFields["FieldName"].Value;

Folio:

Sets or Gets the ‘Friendly’ name of the Process instance.

K2Proc.Folio = "User Friendly Unique ID";

ProcessInstance Properties

DataFields [RO]

XML Fields [RO]

Folio

ID [RO]

Full Name [RO]

ExpectedDuration

Priority

StartDate [RO]

Status [RO]

Page 23: K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... · 2017-11-17 · 300.NRT-K2 Workflow APIs and Services - Runtime Module Overview ©

300.NRT-K2 Workflow APIs and Services - Runtime The ProcessInstance object

© SourceCode Technology Holdings, Inc. All Rights Reserved Page 23

Opening a ProcessInstance from a worklist item

The ProcessInstance object is the gateway to the process-level datafields, and remember that you need to

access these datafields with a string name, as in the example below:

WorklistItem K2WListItem = K2Conn.OpenWorklistItem("serialnumber");

K2WListItem.ProcessInstance.Folio = "NewFolio";

K2WListItem.ProcessInstance.DataFields["String DataField"].Value = "updatedvalue";

Page 24: K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... · 2017-11-17 · 300.NRT-K2 Workflow APIs and Services - Runtime Module Overview ©

300.NRT-K2 Workflow APIs and Services - Runtime The ActivityInstanceDestination object

© SourceCode Technology Holdings, Inc. All Rights Reserved Page 24

The ActivityInstanceDestination object

The ActivityInstanceDestination object is effectively an "instance" of a user task. When there is only a

single destination user for a particular task, there is only one ActivityInstanceDestination for that task, but if there are

multiple destination users for a task, there is usually multiple instances of the same task, one for each user. Each

Activity instance destination is separate from the others.

In the multi-user scenario, the concept of "Slots" becomes important. By default K2 creates a single slot for an

activity, and when the first user opens the worklist item that "slot" is taken and the task cannot be opened by the

other users in the group. If the Advanced Destination Rule was run, there may be multiple "Slots" for the same

activity, in which case it is possible for more than one user to open the same task, since each user has a separate

ActivityInstanceDestination. The screenshot below shows an advanced destination rule with 5 slots:

Setting the number of slots at design-time

Represents a worklist “slot”

Mostly used when multiple users will participate in the same client event

Instantiated by the ActivityInstanceDestination

Property of the WorkListItem

K2ActInst = K2WItem. ActivityInstanceDestination;

The properties for the ActivityInstanceDestination

are similar to the properties of the

ProcessInstance Object.

Activity-level DataFields and XMLFields are saved

per-slot (unless the “Shared” option is selected

in the workflow design)

ActivityInstanceDestination

DataFields [RO]

XML Fields [RO]

ActInstID [RO]

Name [RO]

ExpectedDuration

Priority

StartDate [RO]

ProcInstID [RO]

The ActivityInstanceDestination object

Page 25: K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... · 2017-11-17 · 300.NRT-K2 Workflow APIs and Services - Runtime Module Overview ©

300.NRT-K2 Workflow APIs and Services - Runtime The ActivityInstanceDestination object

© SourceCode Technology Holdings, Inc. All Rights Reserved Page 25

Consider the screenshot example above: in this case, we have specified that there should be 5 slots of the task.

This means that at runtime, there can be a maximum of 5 OpenWorklistItem() calls for the same task, and each

call would return a unique ActivityInstanceDestination object for the current slot.

The screenshot below shows an example of accessing the ActivityInstanceDestination object:

The ActivityInstanceDestination object

In the above screenshot, notice that there is an accessor for the DataFields collection. This represents the collection

of datafields that have been defined on the ACTIVITY-level, and normally each "Slot" of the activity has its own

collection of datafields. This is how you can gather data from several users in the same workflow step: each Slot has

a separate collection of datafields and each user’s input is kept separate. (Note: unless the Shared option is

checked, in which case the datafield is shared between all the worklist slots)

An Activity-Level datafield

The Serial Number for a task is actually made up as follows: ProcessIstanceId_ActivityInstanceDestinationId

Page 26: K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... · 2017-11-17 · 300.NRT-K2 Workflow APIs and Services - Runtime Module Overview ©

300.NRT-K2 Workflow APIs and Services - Runtime Reading the connected User’s information

© SourceCode Technology Holdings, Inc. All Rights Reserved Page 26

Reading the connected User’s information

Remember that a K2 connection is always made in the context of a valid user account, and you may need to query

the User object to determine which user is connected or read more properties from the connected user. The

collection of data returned is provided by the relevant user manager for the currently-connected user: in the majority

of cases this would be an Active Directory user with data read from Active Directory, but if it was user account

defined in the SQL user manager or a custom security provider, that provider is responsible for returning the user

information.

Accessing the User Object

In the WCF and REST services, the WhoAmI() method in the Core endpoint returns the

connected user, while the Identity endpoint exposes methods to read the current user’s

information or to search for users.

Reading the connected User’s information

Connection.User property

Returns a User Object

Represents the authenticated user for the

current K2 connection

Exposes read-only information about the user

All information is read from the underlying

security provider

o Active Directory

o SQL User Manager

o Custom Security Provider

Note: In the WCF/REST services, WhoAmI() performs a similar function

Connection

User

Description

Email

FQN

Manager

ManagedGroups

Name

ManagedUsers

Page 27: K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... · 2017-11-17 · 300.NRT-K2 Workflow APIs and Services - Runtime Module Overview ©

300.NRT-K2 Workflow APIs and Services - Runtime Other common Connection Methods

© SourceCode Technology Holdings, Inc. All Rights Reserved Page 27

Other common Connection Methods

The other methods sometimes used in the workflow client API are OpenServerItem and ImpersonateUser.

Let’s look at each in turn.

OpenServerItem() This method is used to complete an asynchronous server event. Asynchronous Server Events provide a mechanism

for "pausing" a workflow and wait for an external application to programmatically finish the server event before the

workflow resumes. They behave similarly to client events, the difference being that asynchronous server events

expect "machine" input from an external system or application, whereas a client event expects "user" input by one or

more destination users.

There are three parts to implementing an asynchronous server event:

1) In a workflow, use a default server event and set the event to execute asynchronously:

K2.Synchronous = false;

string serialNo = K2.SerialNumber;

//TODO: pass the server item serial number to the other system

2) Pass the serial number through to the other system

string serialNo = K2.SerialNumber;

3) When the other system is ready to finish the task, use the workflow client API in custom code and call the

OpenServerItem() method, passing in the serial number that was sent in step 2.

K2Conn.Open("localhost");

ServerItem svrItem = K2Conn.OpenServerItem("serialnumber");

//TODO: do something with the server item

svrItem.Finish();

For security purposes, the account that is executing the OpenServerItem() method requires the Server Event

permission on the workflow definition, as shown below:

Other common Connection Methods OpenServerItem Method

Used in asynchronous server events to open a server task

o The connected account requires the “Server Event”

permission on the workflow

o Include this line in a custom workflow server event to set a

the event as an asynchronous task

K2.Synchronous = False;string SerialNo = K2.SerialNumber

o To complete the task from the calling application, use this code:

K2SvrItem = K2Conn.OpenServerItem(serialNo)

o See http://help.k2.com/en/kb000272.aspx for more

ImpersonateUser Method*

Allows a connection to impersonate a specific user

o The connected account requires “Impersonate” permission

on the K2 server

o Impersonating a specific user after the initial connection:

K2Conn.ImpersonateUser("securityLabel:username")

Connection

Open

CreateProcessInstance

StartProcessInstance

OpenWorklist

ImpersonateUser

OpenWorklistItem

OpenServerItem

*see ImpersonateSamples method for some sample code

Page 28: K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... · 2017-11-17 · 300.NRT-K2 Workflow APIs and Services - Runtime Module Overview ©

300.NRT-K2 Workflow APIs and Services - Runtime Other common Connection Methods

© SourceCode Technology Holdings, Inc. All Rights Reserved Page 28

Assigning the Server Event permission

For more information about asynchronous server times, please refer to the K2 knowledge base article http://help.k2.com/en/kb000272.aspx

ImpersonateUser() Sometimes, you may need to impersonate another user after establishing the initial connection to K2. This is

especially useful in situations where you are not able to obtain the original user’s Active Directory credentials, but

still need to "connect" to K2 as that user so that you can complete a worklist item that was assigned to them.

This is where the ImpersonateUser() method comes into play: it effectively allows you to switch to another

user’s security context, perform some tasks on the K2 server and then switch back to the original connected user’s

context. The code snippet below illustrates this approach:

//you must first establish a connection with the current credentials (or specific

credentials) before you can impersonate

K2Conn.Open("localhost");

//once you have connected to K2, you can impersonate another user, If the connected

account has the "Impersonate" permission on the K2 environment

K2Conn.ImpersonateUser("securityLabelName:username"); //example:

K2Conn.ImpersonateUser("K2:domain\username");

//now that you have impersonated a user, you can perform actions on behalf of that

user. Here we will retrieve that user's worklist

Worklist K2WL = K2Conn.OpenWorklist();

//TODO do something with the impersonated user's worklist

//when you are done impersonating, you can revert to the original user account

K2Conn.RevertUser();

For security purposes, only those user accounts with the Impersonate permission on the K2 environment will be

able to call the ImpersonateUser() method. The screenshot shows where this permission is set.

Assigning Impersonate permissions

Page 29: K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... · 2017-11-17 · 300.NRT-K2 Workflow APIs and Services - Runtime Module Overview ©

300.NRT-K2 Workflow APIs and Services - Runtime Common Workflow API calls: Summary

© SourceCode Technology Holdings, Inc. All Rights Reserved Page 29

Common Workflow API calls: Summary

In summary, there are a few high-level steps to use the Workflow Client API to interact with workflows

programmatically at runtime:

1. Create a new Instance of the Connection Object.

2. Use the SCConnectionStringBuilder object to create a connection string, if required

3. Open the Connection to the K2 blackpearl Server.

4. Perform an action by executing a method, e.g.:

i. Starting a new workflow

a) Instantiate a workflow with CreateProcessInstance()

b) Set Process Data Field values and/or Folio

c) Start the workflow with StartProcessInstance(procInstObject)

ii. Reading the user’s worklist

a) Create new instance of the WorklistCriteria object

b) Return the worklist with OpenWorklist(WorklistCriteria)

c) Iterate over the worklist items

iii. Completing a user’s task

a) Open the task with a serial number

OpenWorklistItem("serialnumber");

b) Update Process Data Field values and/or Folio

c) Complete the task by executing an Action

K2WListItem.Actions["Action"].Execute();

5. Close the connection to the K2 blackpearl Server.

If you are using the workflow services, you do not need to manage the connection state, but the steps I, ii and iii are effectively the same

Common Workflow API calls: Summary1. Create a new Instance of the Connection Object.

2. Use the SCConnectionStringBuilder object to create a connection string, if required

3. Open the Connection to the K2 blackpearl Server.

4. Perform an action by executing a method, e.g.:

1. Starting a new workflow

a) Instantiate a workflow with CreateProcessInstance()

b) Set Process Data Field values and/or Folio

c) Start the workflow with StartProcessInstance(procInstObject)

2. Reading the user’s worklist

a) Create new instance of the WorklistCriteria object

b) Return the worklist with OpenWorklist(WorklistCriteria)

c) Iterate over the worklist items

3. Completing a user’s task

a) Open the task with a serial numberOpenWorklistItem("serialnumber");

b) Update Process Data Field values and/or Folio

c) Complete the task by executing an ActionK2WListItem.Actions[“Action"].Execute();

3. Close the Connection to the K2 blackpearl Server.

Page 30: K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... · 2017-11-17 · 300.NRT-K2 Workflow APIs and Services - Runtime Module Overview ©

300.NRT-K2 Workflow APIs and Services - Runtime LAB 1: Using the K2 Workflow Client API

© SourceCode Technology Holdings, Inc. All Rights Reserved Page 30

LAB 1: Using the K2 Workflow Client API

Objective The objective of this lab exercise is to familiarize you with the K2 workflow client API and the most common use of

this API. This exercise will cover the following specific actions:

Programmatically starting a workflow instance

Retrieving a user’s K2 worklist (tasks)

Opening and completing a worklist item (task) programmatically

Duration This lab exercise should take around 25 minutes to complete.

Context For the purposes of this exercise, we will use a simple leave application and approval workflow. The workflow has

already been created and deployed to the K2 server: you will just be creating the user interfaces to interact with the

workflow. To save time, we have also pre-created the User Interfaces as skeletons with most of the UI components

already added; you will just write the code that actually interacts with the K2 APIs.

LAB 1: Using the K2 Workflow Client API

In this lab

exercise, you will

use the K2

Workflow Client

API to start a

new workflow,

retrieve a user’s

worklist and

complete a

worklist item.

To save time, the

workflow and

skeleton UIs

have already

been created.

25 minutes

Page 31: K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... · 2017-11-17 · 300.NRT-K2 Workflow APIs and Services - Runtime Module Overview ©

300.NRT-K2 Workflow APIs and Services - Runtime LAB 1: Using the K2 Workflow Client API

© SourceCode Technology Holdings, Inc. All Rights Reserved Page 31

The screenshot below shows the basic layout of the leave approval workflow:

Page 32: K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... · 2017-11-17 · 300.NRT-K2 Workflow APIs and Services - Runtime Module Overview ©

300.NRT-K2 Workflow APIs and Services - Runtime The Workflow Web Service (.asmx)

© SourceCode Technology Holdings, Inc. All Rights Reserved Page 32

The Workflow Web Service (.asmx)

Sometimes it is not possible or pragmatic to reference the .NET-based Workflow Client dll in your code, or perhaps

your organization prefers to use a SOA-based architecture for applications. For these environments, K2 provides

several services that you can consume in custom code. The first service we will discuss is an .asmx web service

which exposes some of the most common workflow client functionality such as starting a workflow, retrieving

worklist items and completing K2 tasks.

This service is located on the K2 workspace or K2 server (depending on the installation of your K2 environment),

and is accessed through a URL like http://K2ServerName/K2Services/ws.asmx

The .asmx service is intended for support of legacy protocols or platform that cannot consume WCF-based services. It is not as extensive as the WCF/REST based services that we will look at in the following topics.

For reference, we have provided code samples below and in a sample project that you can refer to if you need to

know how to interact with this web service.

Starting a new workflow with the .asmx web service

WorkflowRuntimeAsmxService.WSSoapClient client = new WSSoapClient();

//NOTE: you have to set up credentials for the service call.

client.ClientCredentials.Windows.AllowedImpersonationLevel =

System.Security.Principal.TokenImpersonationLevel.Delegation;

//instantiate a process instance

ProcessInstance K2ProcInst = new ProcessInstance();

//you set the workflow to start by setting the process name value

K2ProcInst.FullName = @"K2Learning\300NRT Code Test Workflow";

//set up the process instance's values (Folio and Data fields)

K2ProcInst.Folio = "some folio value";

//get the defined datafields for the workflow

DataField[] K2Datafields = K2ProcInst.DataField;

//set up the data fields. In this case we will set each field's value to the same

value

foreach (DataField K2DataField in K2Datafields)

{

The Workflow Web Service (.asmx)* Classic WSDL web service

Exposes certain workflow client functionality

Located at http://[servername]/K2Services/ws.asmx

Typical uses

Start a Workflow instance (see StartWorkflowSample*)

Open Worklist (see WorklistSample*)

Open and complete Worklist Items (see WorklistItemSample*)

Legacy support

Only intended for use by legacy protocols and certain non-.NET

consumers

Not as extensive as the .NET API or WCF/REST services

To browse the service in the VPC, go to

http://k2.denallix.com/K2Services/ws.asmx*Sample code for the Workflow .asmx Web Service is provided in the project

K2Learning.Samples.WorkflowRuntime.WorkflowServicesAsmx with this learning module.

Open the solution located at

C:\K2 Learning\300.NRT\SampleProject\WorkflowRuntime.SampleProjects.sln

Page 33: K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... · 2017-11-17 · 300.NRT-K2 Workflow APIs and Services - Runtime Module Overview ©

300.NRT-K2 Workflow APIs and Services - Runtime The Workflow Web Service (.asmx)

© SourceCode Technology Holdings, Inc. All Rights Reserved Page 33

K2DataField.Value = "some field value";

}

//after setting up the workflow, start the new workflow instance

client.StartNewProcessInstance(ref K2ProcInst,false);

Retrieving the worklist with the .asmx web service

WorkflowRuntimeAsmxService.WSSoapClient client = new WSSoapClient();

client.ClientCredentials.Windows.AllowedImpersonationLevel =

System.Security.Principal.TokenImpersonationLevel.Delegation;

//retrieve the worklist for the connected user

WorklistItem[] K2worklist = client.OpenWorklist(false);

//iterate over each worklist item

foreach (WorklistItem K2WLItem in K2worklist)

{

//do somethign with each worklist item

}

Opening and completing worklist item using the .asmx web service

WorkflowRuntimeAsmxService.WSSoapClient client = new WSSoapClient();

//NOTE: you have to set up credentials for the service call.

client.ClientCredentials.Windows.AllowedImpersonationLevel =

System.Security.Principal.TokenImpersonationLevel.Delegation;

//open a worklist item with a specific serial number

WorklistItem K2WorklistItem = client.OpenWorklistItem("serialNumber", false);

//update some properties of the worklist item/workflow

K2WorklistItem.ProcessInstance.Folio = "updated Folio value";

//get the defined datafields for the workflow

DataField[] K2Datafields = K2WorklistItem.ProcessInstance.DataField;

//set up the data fields. IN this case we will set each field's value to the same

value

foreach (DataField K2DataField in K2Datafields)

{

K2DataField.Value = "some updated field value";

}

//complete the worklist item

client.ExecuteActionByWorklistItem(K2WorklistItem,"selectedAction",false);

//you can also complete the worklist item without setting data with the

ExecuteActionBySerial method call

client.ExecuteActionBySerial("serialNumber", "selectedAction", false);

Page 34: K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... · 2017-11-17 · 300.NRT-K2 Workflow APIs and Services - Runtime Module Overview ©

300.NRT-K2 Workflow APIs and Services - Runtime Workflow WCF services

© SourceCode Technology Holdings, Inc. All Rights Reserved Page 34

Workflow WCF services

To demonstrate or browse to the WCF, SyncWCF, REST and SyncREST services on the virtual server environment, run the batch file C:\K2 Learning\300.NRT\Services Configuration\InstallServicesConfigFile.bat

which will update the existing web.config file for the K2 services with a custom version which will expose all these services via HTTP

Workflow WCF services (1/2) Platform-independent access to K2 workflow runtime operations

Mostly used for .NET solutions with server-side processing

Supports SOAP and ATOM formats

HTTP and HTTPS compatible

Supports standard and custom K2 Security providers

Service is configured using configuration files (K2HostServer.configand web.config)

Workflow-specific WCF Services located at:

http://[servername]/K2Services/WCF.svc

http://[servername]/K2Services/SyncWCF.svc (Sync services are optimized for low bandwidth/batch processing)

SmartObject WCF Services

Expose Workflow SmartObjects as WCF (SOAP) service endpoints

See module 300.YOK K2 SmartObject APIs and Services - Runtime

Workflow WCF services (2/2) The Objects exposed closely match the objects we discussed in the

Workflow Client dll lessons

WCF Service Typical uses

Start a Workflow instance (see StartWorkflowSample*)

Open Worklist (see WorklistSample*)

Open and complete Worklist Items (see WorklistItemSample*)

SyncWCF Service Typical Uses

Batch-processing of Worklist Items

To explore the services in the VPC, go to

http://k2.denallix.com/K2Services/WCF.svc?wsdl

http://k2.denallix.com/K2Services/SyncWCF.svc?wsdl

See product documentation for more informationDeveloper Reference > Services Reference > K2 Services > WCF Services

*Sample code for the Workflow WCF Service is provided in the project

K2Learning.Samples.WorkflowRuntime.WorkflowServicesWCF with this learning module.

Open the solution located at

C:\K2 Learning\300.NRT\SampleProject\WorkflowRuntime.SampleProjects.sln

Page 35: K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... · 2017-11-17 · 300.NRT-K2 Workflow APIs and Services - Runtime Module Overview ©

300.NRT-K2 Workflow APIs and Services - Runtime Workflow WCF services

© SourceCode Technology Holdings, Inc. All Rights Reserved Page 35

K2 provides a Windows Communication Foundation (WCF)-based service that utilizes SOAP-based messaging to

interact with a workflow from custom .NET applications. This allows developers to interact with a workflow at

runtime through a web service without requiring a reference to any SourceCode client .dlls.

The WCF services are normally used in custom .NET code in solutions that have some server-side processing

(such as ASP.NET applications) or applications that run on some flavor of the .NET framework. This service

supports both SOAP and ATOM formats, and can be configured to be accessible though HTTP, HTTPS or both.

For authentication, the service supports all standard and custom K2 security providers.

The WCF service is configured by editing the web.config file for the K2 Services website (by default this file is

located at [Program Files]\K2 blackpearl\WebServices\K2Services\web.config). Various

configuration options will determine which service endpoints will be available and the security mechanism that will

be used to authenticate users (refer to the K2 product documentation for details).

There are two implementations of the WCF service: the standard service allows for common workflow interaction

like starting a workflow, retrieving a worklist and completing tasks, while the Sync-version of the service is a lighter-

weight implementation intended for lightweight client applications such as Smartphone apps and batch processing

of multiple tasks at once.

The services are available from the K2 Workspace server (which may or may not be the same as the K2 server,

depending on how your K2 environment was installed), and are accessed through URLs similar to the following:

http://k2server/K2Services/WCF.svc?wsdl

http://k2server/K2Services/SyncWCF.svc?wsdl

The WCF and SyncWCF services have different endpoints with different purposes, and these are listed below:

WCF Service Endpoints

Process Start workflows

Worklist Get user’s worklist

Update and complete worklist items

Identity Get User Information

Search for users

Core WhoAmI: checks current user, verify connection and network infrastructure

SyncWCF Service Endpoints

Identity Get User Information

Search for users

Core WhoAmI: checks current user, verify connection and network infrastructure

Task Batch and single processing of worklist items

Lightweight output of worklist items

In the next exercise, you will discover how to interact with these services and we have also provided some code

samples, but for reference the code snippets below illustrate how you may interact with the WCF services

Page 36: K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... · 2017-11-17 · 300.NRT-K2 Workflow APIs and Services - Runtime Module Overview ©

300.NRT-K2 Workflow APIs and Services - Runtime Workflow WCF services

© SourceCode Technology Holdings, Inc. All Rights Reserved Page 36

Starting a new workflow with the WCF web service

WorkflowRuntimeWCFService.ProcessNavigationServiceClient SvcWorklist = new

WorkflowRuntimeWCFService.ProcessNavigationServiceClient();

//instantiate a process instance object and set the properties/values

WorkflowRuntimeWCFService.ProcessInstance K2ProcInst = new ProcessInstance();

K2ProcInst.FullName = @"project\workflowname";

K2ProcInst.Folio = "some Folio value";

//to set datafields, is a List<> collection and then convert it to an array

//set up the collection of datafields

List<DataField> dataFieldsCollection = new List<DataField>();

//string field example

dataFieldsCollection.Add(new DataField() { Name = "FieldName", Value =

"FieldValue"});

//dates require special massaging, otherwise you get XMLAny errors. In this sample

we’ll take the current date

//note the use of the XmlConvert function. You may need to do this with other

datafields, too.

dataFieldsCollection.Add(new DataField() { Name = "FieldName", Value =

XmlConvert.ToString(DateTime.Now,XmlDateTimeSerializationMode.Local)});

//pass the collection to datafields into the workflow

K2ProcInst.DataField = dataFieldsCollection.ToArray();

//start the workflow (setting one datafield parameter to true since we added

datafields to the process instance)

SvcWorklist.StartNewProcessInstance(K2ProcInst, false, false, false, true, false);

Retrieving the worklist with the WCF web service

WorkflowRuntimeWCFService.WorklistNavigationServiceClient SvcWorklist = new

WorkflowRuntimeWCFService.WorklistNavigationServiceClient();

WorklistItem[] K2WorklistItems = SvcWorklist.OpenWorklist(false, false, false,

false);

//iterate over the collection of worklist items

foreach (WorklistItem K2WorklistItem in K2WorklistItems)

{

//DO somethign with the worklist item

}

Opening and completing worklist item using the WCF web service

WorkflowRuntimeWCFService.WorklistNavigationServiceClient SvcWorklist = new

WorkflowRuntimeWCFService.WorklistNavigationServiceClient();

WorklistItem K2WorklistItem = SvcWorklist.OpenWorklistItem("serialNumber", true,

true, true, true, true);

//get some data from the worklist item

string Folio = K2WorklistItem.ProcessInstance.Folio;

//iterate over the colleciton of datafields for the process instance

foreach (DataField dataField in K2WorklistItem.ProcessInstance.DataField)

{

//do something with the datafield

}

//get the possible actions for the worklist item

WorkflowRuntimeWCFService.Action[] K2Actions = K2WorklistItem.Action;

//setting the value for a specific datafield before completing the worklist item

DataField someDataField = (DataField)K2WorklistItem.ProcessInstance.DataField.Where(x

=> x.Name == "DataFieldName").First();

//set the value. Remember to use XML convert for fields like dates, rich text and so

on

someDataField.Value = "new datafield value";

//complete the worklist items

SvcWorklist.ExecuteActionByWorklistItem(K2WorklistItem, "Selected Action", false);

Page 37: K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... · 2017-11-17 · 300.NRT-K2 Workflow APIs and Services - Runtime Module Overview ©

300.NRT-K2 Workflow APIs and Services - Runtime Workflow WCF services

© SourceCode Technology Holdings, Inc. All Rights Reserved Page 37

The SmartObject WCF services When a workflow has been exposed as a collection of K2 SmartObjects (see screenshot below), developers can

also interact with the workflow using the available SmartObject WCF-based services. These services are described

in more detail in the K2 learning module 300.YOK K2 SmartObject APIs and Services - Runtime

Exposing a K2 workflow as K2 SmartObjects

The resulting SmartObjects when a workflow is exposed as K2 SmartObjects

Page 38: K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... · 2017-11-17 · 300.NRT-K2 Workflow APIs and Services - Runtime Module Overview ©

300.NRT-K2 Workflow APIs and Services - Runtime LAB 2: Using the workflow WCF (SOAP) service

© SourceCode Technology Holdings, Inc. All Rights Reserved Page 38

LAB 2: Using the workflow WCF (SOAP) service

Objective The objective of this lab exercise is to familiarize you with the K2 workflow WCF-based SOAP web service, and the

most common use of this service. In this exercise, we will cover the following specific actions:

Programmatically starting a workflow instance

Retrieving a user’s K2 worklist (tasks)

Opening and completing a worklist item (task) programmatically

Duration This lab exercise should take around 25 minutes to complete.

Context For the purposes of this exercise, we will recreate the same solution that we completed in Lab 1, but this time we

will use the SOAP WCF service instead of the .NET API to interact with the workflow. Everything else will remain the

same: we will use the same workflow and the same controls and layouts for the user interfaces, so it’s not

necessary to review the workflow.

The only significant difference (apart from the API, of course) is that we will specify a different URL for the approval

page when starting the workflow, so that the approver is directed to the SOAP-based web page instead of the API-

based web page.

LAB 2: Using the workflow WCF service

In this lab

exercise, you will

use the WCF

service to start a

new workflow,

retrieve a user’s

worklist and

complete a

worklist item.

To save time, the

workflow and

skeleton UIs have

already been

created.

15 minutes

Note: On the provided VPC, the WCF (SOAP) service is located at:

http://k2.denallix.com/K2Services/WCF.svc

Page 39: K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... · 2017-11-17 · 300.NRT-K2 Workflow APIs and Services - Runtime Module Overview ©

300.NRT-K2 Workflow APIs and Services - Runtime Workflow REST Services

© SourceCode Technology Holdings, Inc. All Rights Reserved Page 39

Workflow REST Services

In addition to the WCF-based web services, K2 also provides REST-based services that can be consumed by

almost any technology that is capable of interacting with the standard HTTP verbs such as GET and PUT.

The REST services are normally used in custom applications that may or may not include server-side processing

(such as applications that leverage jQuery to perform client-side processing). The REST services expose the same

endpoints as the WCF services, are configured the same way and support the same security and authentication

mechanisms.

Platform-independent access to certain K2 workflow runtime operations

Mostly used for solutions with client-side processing (e.g. jQuery)

REST supports XML, ATOM and JSON formats

HTTP and HTTPS compatible

Accessed with named Resources/Paths (URI-based resources with

GET/POST HTTP verbs)

Supports standard and custom K2 Security providers

Configured using configuration files (K2HostServer.config and

web.config)

Workflow-specific REST Services located at

http://[servername]/K2Services/REST.svc/[service path]

http://[servername]/K2Services/SyncREST.svc/[service path] (Sync services are optimized for low bandwidth/batch processing)

SmartObject Services

Expose Workflow SmartObjects as REST service endpoints

See module 300.YOK K2 SmartObject APIs and Services (Runtime)

Workflow REST Services (1/2)

Workflow REST services (2/2) The Objects exposed closely match the objects we discussed in the

Workflow Client dll lessons

REST Service Typical uses

Start a Workflow instance (see StartWorkflowSample.htm*)

Open Worklist (see WorklistSampleLinq*)

Open and complete Worklist Items (see WorklistItemSample.htm*)

SyncREST Service Typical Uses

Batch-processing of Worklist Items

To explore the services in the VPC, configure web.config for REST HTTP

access and then go to

http://k2.denallix.com/K2Services/REST.svc

http://k2.denallix.com/K2Services/SyncREST.svc

See product documentation for more informationDeveloper Reference > Services Reference > K2 Services > REST Services

*Sample code for the Workflow REST Service is provided in the project

K2Learning.Samples.WorkflowRuntime.WorkflowServicesREST with this learning module.

Open the solution located at

C:\K2 Learning\300.NRT\SampleProject\WorkflowRuntime.SampleProjects.sln

Page 40: K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... · 2017-11-17 · 300.NRT-K2 Workflow APIs and Services - Runtime Module Overview ©

300.NRT-K2 Workflow APIs and Services - Runtime Workflow REST Services

© SourceCode Technology Holdings, Inc. All Rights Reserved Page 40

Just like the WCF service, there are two implementations of the REST service: the standard service allows for

common workflow interaction like starting a workflow, retrieving a worklist and completing tasks, while the Sync-

version of the service is a lighter-weight implementation intended for lightweight client applications and batch

processing.

The services are available from the K2 Workspace server (which may or may not be the same as the K2 server,

depending on how your K2 environment was installed), and are accessed through URLs similar to the following:

http://[servername]/K2Services/REST.svc/[service path]

http://[servername]/K2Services/SyncREST.svc/[service path]

The Workflow REST services are not necessarily enabled by default in a new K2 installation. You may need to edit the web.config file located on your K2 server (default location is noted below) C:\Program Files (x86)\K2 blackpearl\WebServices\K2Services\web.config

to enable the Workflow REST services.

Notice the service paths: since REST services are based on named resources (URIs), each workflow has a dedicated path for the methods you may want to execute. For example, when starting a workflow instance, you would send a HTTP GET request to the URL http://k2server/k2services/REST.svc/Process/Definitions(WorkflowName)/StartInstance?

The exact path for the resource depends on the naming of the workflow you are trying to reach. The K2

documentation has more information on this topic in the following location: Developer Reference > Services

Reference > K2 SmartObject Services > REST Services > URIs_for_REST

As with the WCF service, the REST services have different "endpoints", and the endpoints perform the same

functions. (In the REST services the "endpoints" are actually exposed as named resources (URIs)

The example below shows how the REST URI is built up – in this example, we want to start an instance of the

K2Learning\300NRT Code Test Workflow with a Folio value of myFolio

REST Service Paths

Process Start workflows

Worklist Get user’s worklist

Update and complete worklist items

Identity Get User Information

Search for users

Core WhoAmI: checks current user, verify connection and network infrastructure

SyncREST Service Paths

Identity Get User Information

Search for users

Page 41: K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... · 2017-11-17 · 300.NRT-K2 Workflow APIs and Services - Runtime Module Overview ©

300.NRT-K2 Workflow APIs and Services - Runtime Workflow REST Services

© SourceCode Technology Holdings, Inc. All Rights Reserved Page 41

Core WhoAmI: checks current user, verify connection and network infrastructure

Task Batch and single processing of worklist items

Lightweight output of worklist items

In the next exercise, you will discover how to interact with these services and we have also provided some code

samples, but for reference the code snippets below illustrate how you may interact with the REST services.

Starting a new workflow with the REST web service using javascript

<script type="text/javascript" language ="javascript">

function startProcess(folio)

{

var currentTime = new Date()

var month = currentTime.getMonth() + 1

var day = currentTime.getDate()

var hours = currentTime.getHours()

var minutes = currentTime.getMinutes()

var secs = currentTime.getSeconds()

var date = month + "" + day + "" + hours + "" + minutes + "" + secs;

folio = folio + "_" + date;

$.ajax

({

url:

'http://k2.denallix.com/k2services/REST.svc/Process/Definitions(K2Learning_B_300NRT%2

0Code%20Test%20Workflow)/StartInstance?folio=' + folio,

method: 'GET',

contentType: "application/json; charset=utf-8",

dataType: "JSON",

async: true,

beforeSend: function (XMLHttpRequest)

{

XMLHttpRequest.setRequestHeader("Accept", "application/json");

},

crossDomain: false,

error: //handleError,

success: //handle Success

});

}

</script>

Retrieving a worklist item with the REST web service and javascript

function getK2WorklistBySN(SN)

{

$.ajax({

url: 'http://k2.denallix.com/k2services/REST.svc/Worklist/Items(' + SN +

')?piDataField=true&actXmlField=true&$format=json',

method: 'GET',

contentType: "application/json; charset=utf-8",

dataType: "JSON",

async: true,

beforeSend: function (XMLHttpRequest) {

XMLHttpRequest.setRequestHeader("Accept", "application/json");

},

crossDomain: false,

error: //handle errorWorklist,

success: //handlegetK2WorklistBySN

});

}

Page 42: K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... · 2017-11-17 · 300.NRT-K2 Workflow APIs and Services - Runtime Module Overview ©

300.NRT-K2 Workflow APIs and Services - Runtime Workflow REST Services

© SourceCode Technology Holdings, Inc. All Rights Reserved Page 42

Completing worklist item using the REST service and javascript

function actionK2WorklistItem(SN, k2Action) {

$.ajax

({

url: 'http://k2.denallix.com/k2services/REST.svc/Worklist/Items(' + SN +

')/Actions(' + k2Action + ')/Execute?$format=json',

method: 'GET',

contentType: "application/json; charset=utf-8",

dataType: "JSON",

async: true,

beforeSend: function (XMLHttpRequest)

{

XMLHttpRequest.setRequestHeader("Accept", "application/json");

},

crossDomain: false,

error: //handle errorWorklist

success: //handleactionK2WorklistItem

});

}

The SmartObject REST services K2 also exposes the SmartObject services as REST services, just like the WCF SmartObject services. Again, when

a workflow has been exposed as a collection of K2 SmartObjects, developers can also interact with the workflow

using the available SmartObject REST-based services. These services are described in more detail in the K2

learning module 300.YOK K2 SmartObject APIs and Services - Runtime

Page 43: K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... · 2017-11-17 · 300.NRT-K2 Workflow APIs and Services - Runtime Module Overview ©

300.NRT-K2 Workflow APIs and Services - Runtime LAB 3: Using the workflow REST service

© SourceCode Technology Holdings, Inc. All Rights Reserved Page 43

LAB 3: Using the workflow REST service

Objective The objective of this lab exercise is to familiarize you with the K2 workflow WCF-based REST web service. Since

javascript is a little tricker and more time-consuming to write than pure ASP.NET code, we will only be creating a

single interface (a custom worklist) in this sample.

Duration This lab exercise should take around 15 minutes to complete.

Context For the purposes of this exercise, we will only be creating a custom worklist page that leverages the REST workflow

service. Note that we will edit the web.config file for the workflow services to enable HTTP access for the REST

service.

Credit to Ruben D’Arco for his blog post at http://cyclops.nettrends.nl/blog/2011/04/k2-and-jquery-creating-a-simple-

worklist which we have re-used here to demonstrate the use of the REST workflow service

LAB 3: Using the workflow REST service

In this lab exercise

you will just be

building a custom

worklist HTML

page that uses

JavaScript and the

REST service to

retrieve the

current user’s

worklist

15 minutes

Note: On the provided VPC, the REST service is located at:

http://k2.denallix.com/K2Services/REST.svc/[Endpoint]

Page 44: K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... · 2017-11-17 · 300.NRT-K2 Workflow APIs and Services - Runtime Module Overview ©

300.NRT-K2 Workflow APIs and Services - Runtime WCF and REST services: Endpoints and Paths

© SourceCode Technology Holdings, Inc. All Rights Reserved Page 44

WCF and REST services: Endpoints and Paths

We mentioned before that the WCF and REST services are exposed as different resources: the WCF services use

Endpoints while the REST services use URI paths. These endpoints/paths are separated according to their

functions, and the table below lists these functions.

Endpoint WCF/REST SyncWCF/SyncRest

Process Start workflows (not available)

Worklist Get user’s worklist

Update and complete worklist items

(not available)

Identity Get User Information

Search for users

Get User Information

Search for Users

Core WhoAmI: checks current user, verify

connection and network

infrastructure

WhoAmI: checks current user, verify

connection and network infrastructure

Task (not available) Batch and single processing of worklist items

Lightweight output of worklist items

You can decide which of these endpoints should be exposed by editing the web.config file for the K2Services

website, and enabling or disabling the endpoints in the services section. In the example below, we have disabled the

REST-based Process service by commenting out the Process endpoint, highlighted in red:

WCF and REST services: Endpoints/PathsEndpoint WCF/REST SyncWCF/SyncRest

Process Start workflows (not available)

Worklist Get user’s worklist

Update and complete worklist

items

(not available)

Identity Get User Information

Search for users

Get User Information

Search for Users

Core WhoAmI: checks current user,

verify connection and network

infrastructure

WhoAmI: checks current user, verify

connection and network infrastructure

Task (not available) Batch and single processing of

worklist items

Lightweight output of worklist items

In the REST Services, the service endpoints are exposed as URI paths, e.g. http://k2.denallix.com/K2Services/REST.svc/Identity/Users?

The available endpoints are determined by configuration in the web.config file

Page 45: K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... · 2017-11-17 · 300.NRT-K2 Workflow APIs and Services - Runtime Module Overview ©

300.NRT-K2 Workflow APIs and Services - Runtime WCF and REST services: Endpoints and Paths

© SourceCode Technology Holdings, Inc. All Rights Reserved Page 45

Disabling an endpoint by commenting the endpoint out in the web.config file

Page 46: K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... · 2017-11-17 · 300.NRT-K2 Workflow APIs and Services - Runtime Module Overview ©

300.NRT-K2 Workflow APIs and Services - Runtime .NET API vs. WCF vs. REST services

© SourceCode Technology Holdings, Inc. All Rights Reserved Page 46

.NET API vs. WCF vs. REST services

All these available APIs can be confusing, but fundamentally they expose very similar functionality. The API/Service

you decide to use depends largely on what the application is intended to do, where and how the application will be

used, and the organization’s approach to SOA. To help you select the appropriate technology, the table below

compares the main aspects of each API/Service:

.NET API WCF/SyncWCF REST/SyncREST

Interface .NET classes and methods Data Contracts (Classes) and

Service Contracts (Methods)

Named Resources/Paths (URI based

access with GET/POST HTTP verbs)

Port/Protocol RPC (port 5252 by default) HTTP or HTTPS (port 80 and 443

by default)

HTTP/HTTPS (port 80 and 443 by

default)

Data Format .NET objects .NET objects (serialized over the

wire)

XML, ATOM and JSON

Referencing

the service

Must add a .dll reference to

the client application

Must add a service reference to the

client application

No reference required

Developer

notes

Easiest to code against and

most comprehensive but

most technology-restrictive

.NET over HTTP/HTTPS, most

common objects/methods are

exposed, .NET code is easy with

Intellisense

Harder to code against but less

technology-restrictive, REST is a

modern approach to SOA

Security Security based on network

credentials

Security based on WS-Security

and SSL

Security based on WS-Security and

SSL

Typical use Tools, utilities, automated

testing code, thick-client

applications, web

applications inside the

firewall

Web-based or thick-client .NET

applications inside or outside the

firewall, applications requiring

higher security and reliable

messaging

Thin-client applications outside the

firewall, lightweight applications for

mobile devices, non-.NET consumers

.NET API vs. WCF vs. REST services.NET API WCF/SyncWCF REST/SyncREST

Interface .NET classes and methods Data Contracts (Classes) and

Service Contracts (Methods)

Named Resources/Paths

(URI based access with

GET/POST HTTP verbs)

Port/Protocol RPC (port 5252 by default) HTTP or HTTPS HTTP/HTTPS

Data Format .NET objects .NET objects (serialized over the

wire)

XML, ATOM and JSON

Referencing

the service

Must add a .dll reference to

the client application

Must add a service reference to

the client application

No reference required

Developer

notes

Easiest to code against and

most comprehensive but

most technology-restrictive

.NET over HTTP/HTTPS, most

common objects/methods are

exposed, .NET code is easy with

Intellisense

Harder to code against but

less technology-restrictive,

REST is a modern approach

to SOA

Security Security based on network

credentials

Security based on WS-Security

and SSL

Security based on WS-

Security and SSL

Typical use Tools, utilities, automated

testing code, thick-client

applications, web

applications inside the

firewall

Web-based or thick-client .NET

applications inside or outside the

firewall, applications requiring

higher security and reliable

messaging

Thin-client applications

outside the firewall,

lightweight applications for

mobile devices, non-.NET

consumers

Page 47: K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... · 2017-11-17 · 300.NRT-K2 Workflow APIs and Services - Runtime Module Overview ©

300.NRT-K2 Workflow APIs and Services - Runtime The Workflow Management API

© SourceCode Technology Holdings, Inc. All Rights Reserved Page 47

The Workflow Management API

The workflow Management API refers to the .NET assembly SourceCode.Workflow.Management.dll. This assembly

exposes several classes and methods that are used to administer K2 workflows and the K2 environment.

Essentially, this API allows developers to perform similar administration functions as the ones exposed on the K2

workspace and K2 process portals’ Management console pages.

The K2 Management Console in K2 workspace.

The SourceCode.Workflow.Management API provides programmatic access to similar functionality

In practice, the SourceCode.Workflow.Management assembly is often used to manage processes, automate Error

reporting and Error repair, to manage other users’ worklist items and Out-of-Office statuses, to manage active

process instances and perform workflow version migration for in-flight workflows.

The Workflow Management API*

SourceCode.Workflow.Management.dll

Management and Administration of K2 Workflows and the K2 Server

Exposes similar functions as the K2 Workspace’s Management Console

Common use cases

Manage workflow permissions

Automation of error reporting and error repair

Manage other users’ worklist items

Manage process instances (Stop, Start, Redirect, Delete etc)

Live Instance Management (migrate running workflows to a different version)

Note: The user account executing the code requires Admin rights on the K2

environment and Admin rights on the workflow being managed

*Sample code for the Workflow Management API is provided in the project

K2Learning.Samples.WorkflowRuntime.WorkflowManagementAPI

provided with this learning module.

Open the solution located at

C:\K2 Learning\300.NRT\SampleProject\WorkflowRuntime.SampleProjects.sln

Page 48: K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... · 2017-11-17 · 300.NRT-K2 Workflow APIs and Services - Runtime Module Overview ©

300.NRT-K2 Workflow APIs and Services - Runtime The Workflow Management API

© SourceCode Technology Holdings, Inc. All Rights Reserved Page 48

The SourceCode.Workflow.Management.dll assembly is deployed to the GAC of the K2 server, and it is also

installed on developer workstations when the K2 Studio/K2 for Visual Studio development tools are installed. On a

machine with K2 Server, K2 Workspace or the K2 developer tools, the Workflow.Management assembly is available

from the following location:

[Program Files Directory]\K2 blackpearl\Bin\SourceCode.Workflow.Management.dll

You will also need to reference the SourceCode.HostClientAPI.dll assembly, since this assembly is used to

construct a connection string to the K2 server. You can find this assembly at

[Program Files Directory]\K2 blackpearl\Bin\SourceCode.HostClientAPI.dll

The Workflow.Management API is not exposed as a WCF or Web service: it is only available as a .NET .dll.

Security requirements Most methods in the management API require the executing user account to hold Admin rights on K2 server and

potentially Admin rights on the workflow being administered. You can give the account the required rights using K2

workspace or a K2 process portal.

Assigning Server rights in the K2 Workspace

Assigning Process rights in K2 Workspace

Page 49: K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... · 2017-11-17 · 300.NRT-K2 Workflow APIs and Services - Runtime Module Overview ©

300.NRT-K2 Workflow APIs and Services - Runtime Common Workflow Management Methods

© SourceCode Technology Holdings, Inc. All Rights Reserved Page 49

Common Workflow Management Methods

The workflow management assembly is often used to create custom applications, utilities or scripts that perform

automated administration tasks.

We have provided a sample project with examples of some of the more common methods in this API. Please refer

to the project K2Learning.Samples.WorkflowRuntime.WorkflowManagementAPI in the solution that accompanies

this module, located at C:\K2 Learning\300.NRT\SampleProject\K2Learning\WorkflowRuntime.SampleProjects.sln

You can use the text in the slide screenshot to help you explore the sample code.

Common Workflow Management Methods

Manage workflow permissions

see SetWorkflowPermissions*

Automation of error reporting and error repair

see ListErrors* and RepairErrors*

Manage other users’ worklist items

see ManageWorklistItems*

Manage Out-of-Office on behalf of users

see ListOutOfOfficeUsers*

Manage process instances (Stop, Start, Redirect, Delete etc)

see ManageProcessInstances*

Live Instance Management

(migrate running workflows to a different version)

see LiveInstanceManagementSample*

*Note: due to time constraints we will not discuss each method. Instead, see a sample of this

method in the sample project as noted, and refer to product documentation for more information

Page 50: K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... · 2017-11-17 · 300.NRT-K2 Workflow APIs and Services - Runtime Module Overview ©

300.NRT-K2 Workflow APIs and Services - Runtime Workflow Management API calls: Summary

© SourceCode Technology Holdings, Inc. All Rights Reserved Page 50

Workflow Management API calls: Summary

There are some high-level steps required to use the workflow management API effectively, and they are listed below

with code snippets.

1. Set up Security

Ensure that the executing user account has Admin permissions on the K2 environment. If the code will be

managing workflows, ensure that the user account has Admin rights for the workflow as well.

2. Instantiate the object

Instantiate a WorkflowManagementServer object

WorkflowManagementServer K2Mgmt = new WorkflowManagementServer();

3. Create a Connection String

Build up a connection string with the SCConnectionStringBuilder object

SourceCode.Hosting.Client.BaseAPI.SCConnectionStringBuilder builder =

new SourceCode.Hosting.Client.BaseAPI.SCConnectionStringBuilder();

builder.Integrated = true; //use the current user's security credentials

builder.IsPrimaryLogin = true;

builder.Authenticate = true;

builder.EncryptedPassword = false;

builder.Host = "localhost";

builder.Port = 5555; //you must use port 5555 when connecting with the management

API

builder.SecurityLabelName = "K2"; //this sample uses the Active Directory security

provider

4. Open the Connection

Open the WorkflowManagementServer object’s connection

K2Mgmt.Open(builder.ToString());

Workflow Management API calls: Summary

1. Ensure the connected user account has Admin permissions on K2

2. Ensure that the user account has Admin permissions on the workflow definition, if required

3. Instantiate a WorkflowManagementServer object

4. Build up a connection string with the SCConnectionStringBuilderobject

5. Open the WorkflowManagementServer object’s connection

6. Perform the required action by calling a method of the WorkflowManagementServer object

7. Close the WorkflowManagementServer object’s connection

Page 51: K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... · 2017-11-17 · 300.NRT-K2 Workflow APIs and Services - Runtime Module Overview ©

300.NRT-K2 Workflow APIs and Services - Runtime Workflow Management API calls: Summary

© SourceCode Technology Holdings, Inc. All Rights Reserved Page 51

5. Perform tasks

Perform the required action by calling a method of the WorkflowManagementServer object

6. Clean up You should Close the WorkflowManagementServer object’s connection when you are done executing methods.

K2Mgmt.Connection.Close();

Page 52: K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... · 2017-11-17 · 300.NRT-K2 Workflow APIs and Services - Runtime Module Overview ©

300.NRT-K2 Workflow APIs and Services - Runtime LAB 4: Using the K2 Workflow Management API

© SourceCode Technology Holdings, Inc. All Rights Reserved Page 52

LAB 4: Using the K2 Workflow Management API

Objective The objective of this lab exercise is to familiarize you with the K2 workflow management API. This is an extensive

API with many different methods, and we won’t be able to discuss all the available methods. Instead, this exercise

will only cover the following specific actions

Programmatically retrieving a list of workflows in error status

Programmatically repairing a workflow in error status

Programmatically forcing a workflow to go to another activity

Duration This lab exercise should take around 20 minutes to complete.

Context For the purposes of this exercise, we will create a windows console application to allow a K2 administrator to loop

through all the workflows that are in error status and decide for each whether they want to:

1) Repair the workflow error

2) Force the workflow to go to the "End" activity

3) Ignore the error

To support this exercise, a sample workflow that will throw an error has already been deployed and three instances

of this workflow have been started. You will use the console application to manage these three instances.

For reference, the supporting workflow is shown in the image below. The first activity, "Activity that will error" will

throw an error the first time that the activity is hit – if you repair the error, the workflow will continue. The "End"

activity is just an empty event that does nothing. For this exercise, we want to allow the workflow administrator to

LAB 4: Using the

SourceCode.Workflow.Management API

In this lab exercise

you will create a

simple console

application to list

all errors on the

K2 server. For

each error, the

user will be

prompted whether

they want to Retry

the error, force the

workflow to go to

the “End” activity

or Ignore the error

15 minutes

Page 53: K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... · 2017-11-17 · 300.NRT-K2 Workflow APIs and Services - Runtime Module Overview ©

300.NRT-K2 Workflow APIs and Services - Runtime LAB 4: Using the K2 Workflow Management API

© SourceCode Technology Holdings, Inc. All Rights Reserved Page 53

either attempt to repair the workflow or just force the workflow to go directly to the "end" activity.

Page 54: K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... · 2017-11-17 · 300.NRT-K2 Workflow APIs and Services - Runtime Module Overview ©

300.NRT-K2 Workflow APIs and Services - Runtime Other common Workflow APIs

© SourceCode Technology Holdings, Inc. All Rights Reserved Page 54

Other common Workflow APIs

Apart from the APIs and services discussed in this learning module, there are other API’s available to interact with

workflows. Due to time constraints we cannot discuss each API in detail, but feel free to discuss these API’s with

your instructor or research them further with resources such as the K2 product documentation, http://help.k2.com

and http://www.k2underground.,com

SourceCode.Workflow.Authoring.dll This assembly is used to programmatically generate and build workflows. It is sometimes used to create automated

TFS tasks that perform daily build+deployment tasks.

SourceCode.DeploymentTasks.dll This assembly is normally used to deploy workflow projects to a K2 environment programmatically, when the

msbuild deployment approach is not an option.

SmartObject APIs and Services If workflows have been exposed as K2 SmartObjects, you can use any of the available SmartObject APIs and

services to interact with workflow programmatically. These API’s are discussed in detail in the learning module

300.YOK K2 SmartObject APIs and Services - Runtime

Other common Workflow APIs

SourceCode.Workflow.Authoring.dll Programmatically create, update and build workflow definitions

Create deployment packages

Similar functionality as K2 Studio/K2 for Visual Studio

SourceCode.DeploymentTasks.dll Publish K2 deployment packages to a K2 server

Commonly used to automate deployment tasks

SmartObject APIs and Services If the workflow is exposed as a SmartObject

See the K2 Developer Reference for more details and

other APIs

Page 55: K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... · 2017-11-17 · 300.NRT-K2 Workflow APIs and Services - Runtime Module Overview ©

300.NRT-K2 Workflow APIs and Services - Runtime REVIEW

© SourceCode Technology Holdings, Inc. All Rights Reserved Page 55

REVIEW

Let’s review the main topics covered in this learning module:

The available K2 Workflow runtime APIs

Workflow.Client .NET API

.asmx web service

WCF Services

REST services

Workflow.Management .NET API

Using the .NET API

Using the asmx web service

Using the WCF services

Using the RESTful services

Configuring the services

Comparing the APIs

Consider how you might use the available APIs in your organization. Would you prefer to use the .NET client .dll, the

WCF services or the REST services? If using the .NET Client dll, how would you ensure that the applications are

kept up-to-date if the K2 installation is updated? Would it make sense for your organization to create wrapper or

helper classes around the workflow APIs?

This is also your opportunity for asking questions to clarify any of the topics covered during this module. If you are

unclear about a topic, please do ask the instructor to explain or elaborate.

The available K2 Workflow runtime APIs

Workflow.Client .NET API

.asmx web service

WCF Services

REST services

Workflow.Management .NET API

Using the .NET API

Using the asmx web service

Using the WCF services

Using the RESTful services

Configuring the services

Comparing the APIs

Review and Q&A

Page 56: K2 Workflow APIs and Services - Runtimecommunity.k2.com/pfxaw45692/attachments/pfxaw45692/K2... · 2017-11-17 · 300.NRT-K2 Workflow APIs and Services - Runtime Module Overview ©

300.NRT-K2 Workflow APIs and Services - Runtime Additional Resources

© SourceCode Technology Holdings, Inc. All Rights Reserved Page 56

Additional Resources The following table lists additional resources that supplement the information provided in this module:

Resource Location and Notes

How to use Asynchronous Server Events in K2 blackpearl

http://help.k2.com/en/kb000272.aspx This KB article describes how to use asynchronous server events. Note the use of the OpenServerItem() method in this design approach.

K2 blackpearl Connection Strings http://www.k2underground.com/blogs/fromthebench/archive/2008/04/30/misc-k2-blackpearl-connections-strings.aspx This blog post illustrates some different connection strings you can use to connect to a K2 server

An Introduction To RESTful Services With WCF

http://msdn.microsoft.com/en-us/magazine/dd315413.aspx This MSDN Article describes RESTful services built on WCF. You will find this useful when writing code against the K2 REST web service.

K2 Services (high-level intro) http://k2underground.com/blogs/comingsoon/archive/2011/04/09/k2-services-part-2.aspx This blog post by Ruben d’Arco has a nice high-level intro to the K2 Services (WCF, REST and WS)

WCF Primer/Tip http://www.k2underground.com/blogs/johnny/archive/2011/05/13/wcf-primer-tip-in-relationship-to-k2-services-and-smartobject-services.aspx This blog post by Johnny Fang links to additional content that describes the technical foundations of the K2 Services

K2 and jQuery: Creating a simple Worklist

http://cyclops.nettrends.nl/blog/2011/04/k2-and-jquery-creating-a-simple-worklist/ Ruben d’Arco describes how to create a custom worklist with AJAX, jQuery and the REST workflow services

K2 Service Reference http://help.k2.com/en/displaycontent.aspx?id=4814 Document that describes the K2 Services (WCF and REST) in detail

Random fact: Fugu is the Japanese word for pufferfish and the dish prepared from it. Fugu can be lethally poisonous and therefore it must be carefully prepared to remove toxic parts and to avoid contaminating the meat. The restaurant preparation of fugu is strictly controlled by law in Japan, and it takes about 7-10 years of intensive training to learn how to prepare fugu safely. (This training may not be needed in the future as some fish farms in Japan are producing non-poisonous fugu.)