Tag Archives: API

Building K2 Smartform Control – Part 3

Now with the previous post, we talk about adding our own custom library and cleaning up the template. This is so that we have a clean baseline to start working on.

If you missed the previous post, visit them here.

K2 Smartform Custom Control – Part 1

K2 Smartform Custom Control – Part 2

This post will be relative short and last part of the series.

Today, we are going to cover the main portion of it and some deployment procedure.


Within, K2 Smartform Custom Control project, located the SideMenu_Contro.cs file.

Add the following codes.

13. Adding method to generate HTML

This is required of the Javascript library to render the html within in the K2 Smartform Custom Control.


Add the following codes to SideMenu_Script.js

At the top of the file, add the following.


14. Javascript file Init the class


Next, scroll to the bottom and add the required javascript to invoke the SideMenu.


15. Adding Document.Ready method


Testing & Deployment

We are all done now, let’s build it and deploy it.

If you are facing the following errors during your build phase, change the .Net framework of the project to 4.5


16. Error in compiling



17. Changing the .Net Framework

Now, copy the dll and place them in the Bin folder of your K2 Runtime and K2 Designer and run the .bat file.

Building K2 Smartform Control – Part 2

Continuing from the previous post on building a custom control, visit Part 1 here.

We are going to add a sidemenu javascript library to the K2 Smartform Control.

I have chosen the following javascript library, you can download it from here.

Add Javascript Library to Solution

Now lets add those library to the solution project.

6. Adding the javascript and CSS library


Open up the property windows of those files and set them to “Embedded Resources”

7. Setting the properties to Embbedded Resources

NOTE: This is critical for the K2 SmartForm Control, as this will tell the solution to compile the library along with it.

Linking the Javascript Libraries & CSS in the source code

In the SideMenu_Control.cs, open it up and add the following lines of codes.

8. Adding CSS library to Control source file


9. Adding JS library to source file


We are not done yet, the above codes only tells to K2 Smartfrom Custom Control that those are required resources.

We are going to add those following JS and CSS to the code base with the following lines.

9.1 Adding JS library to source file


You will notice that the K2 Smartform Custom Control Template generate a whole bunch of codes for you. In this section, we going to remove some stuff to keep it clean.


Remove the following sections that is generated along with the template.

section 1:


10. Remove the Generated Method

section 2:

11. Remove the Generated Method 2

section 3:

12. Remove input type as this not a input control

With that all done, we have a clean baseline to work with.

Go to K2 Smartform Custom Control – Part 3


Building K2 Smartform Control – Part 1

K2 Smartform is a rapid development tool that provide a WYSIWYG interface. There’s a lot of plus point to this as this closely resemble the visual studio designer or even dreamweaver and K2 have place alot of thought in the Smartform product design and a whole lot of controls are available out of the box.

However, the downside here is that since the K2 Smartform only work within the K2’s technology ecosystem, to extend the capability of the Smartform such as cooking your own controls or even using those commercially available (e.g. Telerik) are limiting.

In this article, we will be writing a mulit part series to show you guys how to build your own custom control.


The K2 Smartform is design such that its almost similar to any custom user control on ASP.NET or Sharepoint Webpart in terms of architecture.

To get started building a K2 Smartform custom control, head over to the following url and install the template that the community have release to help everyone get started.

K2 Visual Studio Template

Download the respective template and install for your version of Visual Studio. The “good” guys at the community have cater for different version of Visual Studio.

Getting Started – Creation of the K2 Smartform Control Project Solution

Now, let go about creating a new project. You should have a new category for the option on the left which is named K2.

K2 Visual Studio Project

Expand the K2 and select K2 Extension. Now choose Custom Smartform Control Project and give it a project name.

This should generate a Visual Studio Solution Project for you.

Generating the K2 Smartform Control Files

Let’s go generate some files for the custom control that we are going to build.

Right-Click and select Add New Item.

2. Visual Studio - Add New Item

Choose SmartForms Basic Client Control Item and give it a name. (This should be the name of the control).

3. Visual Studio - Add New Basic Client Control


Your Visual Studio Solution Explorer should look like below.

4. Directory Structure


Go to K2 Smartform Custom Control – Part 2

K2 Server Event Run As API

In K2 blackpearl workflow, you can specify “Run As” credentials on your Server Events. During workflow execution, the event will be ran using the specified account instead of the K2 Service Account (Note: All Server Events are ran using the service account by default). This feature is available in the K2 Studio and K2 Designer in Visual Studio and it is particularly useful when you need to run critical tasks like create create new AD account, provision Exchange mailbox etc. You do not want the K2 Service Account to have all these critical rights and no Developer should create these critical workflows without the K2 Administrator’s knowledge.

Updating K2 Server Event Run As via K2 Workspace
Updating K2 Server Event Run As via K2 Workspace

Now, the problematic part comes when the Development environment is running on the Development AD whereas the UAT and Production running on the Production AD. It is not possible to embed the credentials in the Server Events now and the only other option is to set it in the K2 Workspace (See article). Setting the credentials in K2 Workspace requires the Administrator to update it on every deployment since it is version specific. Things could get worst when there are multiple events to update in a workflow. To make things simple, we can write a console application that makes use of the workflow management api to update the credentials.

Let’s Code K2 Server Event Run As API

You can find a copy of the working codes at GitHub repository.

The logical steps go like this:

1. Connect to the Workflow Management Server. You need to run using a K2 Administrator account.

2. Get the Process Set for your process. Process Set contains the generic configuration for a Process and is the parent container for all the versions of this process.

3. Find the default Process version. This is required for “Run As” credential setting is version specific.

4. Find the Activity that holds the Server Event which you want to update.

5. Find the required Event.

6a. To set a credential.

6b. To remove the credential and event to service account.


And that’s the end of how to code K2 Server Event Run As API.



K2 smartforms control custom property

In this article, I’m going to show you how to add a property, MaxFileSize, to a K2 smartforms custom control.

Note: The focus of this article is all about adding a property and using it in your control. For the basics on how to create a K2 smartforms control, please visit K2 smartforms Developers Reference .

Adding a K2 smartforms control custom property

1. Add a new property to your control’s xml definition

In your control’s definition xml file, add a new Prop element under Properties. It should look like the following:

ID attribute is the new property’s name and InitialValue sets the default value when the control is first added to a View.

For more information about what each of the property’s attribute does, look at Control Definition XML File.

2. Add a Getter/Setter method in your control class to access the property value

You need this method to create and save the option values into the control so that you can retrieve it in your JavaScript later.

The method name should match the ID value set in the property earlier on. In the GetOption and SetOption method, use small caps for your option name (e.g. maxfilesize) as this will be the data-options attribute registered in the control’s html.

3. Reading the option values via JavaScript

Now, as I mentioned earlier, the options will be surfaced as data-options attributes in the control’s html. Use your browser’s in-built developer tools to look at the control’s html. It should look similar to this:

Notice that the maxfilesize value has been registered in the data-options attribute? This is the value set in the K2 Designer and you have access to it now. =)

So, last step. To get the value, just use the jQuery .data function to retrieve the data-options values. For me, I create a initialise function to handle the values initialization.


Good luck!

Using K2 WorklistCriteria

In my previous post, I’ve discussed on how to use K2 blackpearl’s SourceCode.Worklist.Client API for basic functions like start Process Instance, open Worklist, open Worklist Item and action a Worklist Item. All these functions are straight forward (that’s about all you can do with it) except the open Worklist  function.

Normally, when you use the OpenWorklist method, you will like to have some form of filtering. It could be a filter to show the user his/her tasks based on the current department website listed or some custom prioritization logic to help the user to focus on the tasks at hand. To make this filtering possible, you will need to make use of the WorklistCriteria class.

Using K2 WorklistCriteria

To use the WorklistCriteria class, you will need to carry out the same open/close workflow connection steps in my previous post, which I’m not going to repeat here. Once that’s done, you will need to create an instance of the class.

You will need to add your filters here, which we will discuss in the next section and lastly pass the object into the OpenWorklist method.

So in the full picture, your codes will look like this:

So if you execute the codes now, it will return all Worklist Items of the current user.

My result without filter

Filter Basics

Now, to add a filter, you will need to call on the AddFilterField which has 3 variations:

WCField is the list of properties you can filter on and they are pretty much self explanatory.

Do take note that WorklistItemStatus comparision uses the following values:

WCCompare lists the comparison operators you can use in the filter:

If you notice, there is no “greater than”, “greater than or equal”, “less than” and “less than or equal” operators here, so you will need to put some thoughts into your mathematical operations (=

WCLogical is the joining operator between 2 filters. This will be discussed in more details in a subsequent section.

SubField is a string value used to reference additional key names like Data Field name during comparison.

Object is a object value for your comparison.

So if you just want to filter and show all Worklist Item with “Available” status, the code will look like this:

When using my test Worklist, I’ll get:

Result showing all “Available” status only

Using AND and OR Logical Operators

Using the AND and OR filter is pretty straight forward.

In my AND join example, I’m going to create a filter that requires the Process Name to start with “C” and the Worklist Item status to be “Open”.

Result for Process start with “C” and status = “Open”

In my OR join example, I’m going to create a filter that requires the Worklist Item status to be “Available” or “Open”.

Status = “Available” OR “Open”

Using the Other Operators

Other than AND and OR operators, the following shows what the other operators does:

StartBracket: Draws the “(” operator for the given filter.

AndBracket: Adds the AND operator and closes the filter with a “)” operator.

OrBracket: Adds the OR operator and closes the filter with a “)” operator.

EndBracket: Closes the filter with a “)” operator, if you have a StartBracket earlier on

Filtering by Process or Activity Data/Xml Field

If you need to filter by Process or Activity Data or Xml Field, you will need to pass in the field name in the SubField like the following:


Well, the above details should get you through majority of your needs to create a custom Worklist. Enjoy!!

How to access and manuipulate ActivityInstanceDestination XML field in Workflow

To access datafields in K2 workflow is pretty straigh forward, but to access the XML fields require a bit more work to get to the text. In the following, the K2 API code is used to access the InfoPath XML data

1) Load the XML field using XmlDocument. If you have more then one XML field used, then loop through the XMLfield, use a IF statement to determine which XML field to load

XmlDocument document = new XmlDocument();
for (int i = 0; i < WLItem.ProcessInstance.XmlFields.Count; i++)
    if (WLItem.ProcessInstance.XmlFields[i].Name == “ABC”)
    {  xmlDoc.LoadXml(WLItem.ProcessInstance.XmlFields[i].Value.ToString());

2) Once loaded, because K2 uses the namespace “my”. create a XmlNamespaceManager (as shown in the code below). Why the use of XMLNamespaceManager? From MSDN (MSDN URL) XmlNamespaceMaanager explanation:

Resolves, adds, and removes namespaces to a collection and provides scope management for these namespaces.

The namespace manager implements enumeration support in addition to adding and retrieving namespaces. You can loop through the information saved in the namespace manager by using the foreach construct.

Because the namespace manager provides a string comparison with the prefix and namespaces as objects, there is a performance improvement when using the namespace manager over the direct comparison of a string

System.Xml.XmlNamespaceManager xmlNSMgr = new System.Xml.XmlNamespaceManager(xmlDoc.NameTable);
xmlNSMgr.AddNamespace(“my”, xmlDoc.DocumentElement.GetNamespaceOfPrefix(“my”));

XmlNode RemarksNode = xmlDoc.DocumentElement.SelectNodes(<Insert the node structure here>, xmlNSMgr).Item(0);

node structure example: /my:myFields/my:Approver/my:Approver_Remarks

Full example: XmlNode RemarksNode = xmlDoc.DocumentElement.SelectNodes(“/my:myFields/my:Approver/my:Approver_Remarks”, xmlNSMgr).Item(0);

3) Once the node has been selected, you can manipulate the innerText. Example, I am updating the innertext of the node comments

Approver_Remarks.InnerText = tbRemarks.Text;

4) Now this is when some additional steps need to be done:

StringWriter _SW = new StringWriter(); // create a stringwriter
XmlTextWriter _XmlW = new XmlTextWriter(_SW); // create a new xml textwriter, writing to the stringwriter
xmlDoc.WriteTo(_XmlW); // write the xmlDoc to the xmltextwriter
string UpdatedXml = _SW.ToString(); // store the stringwriter value

//pass the XML value back to the XmlField

WLItem.ActivityInstanceDestination.XmlFields[“ApproverComment”].Value = UpdatedXml;

WLItem.Actions[“Approve”].Execute(); // Execute the action to update the field

Using K2 Workflow Client API

[Updated: 4/6/2015]: Added reference to usage of WorklistCriteria here.

The SourceCode.Workflow.Client assembly provides the access to interact with the K2 blackpearl Server in the context of a User. This means that the API will not be able to query, for example, for all Users who has a Worklist Item from a specific Process. You will need to use SourceCode.Workflow.Management assembly for this. This API, however will allow the current User to impersonate as any other User within K2, if the account has the Impersonate rights on the Workflow Server. We will see more about this. Now down to the basics.

K2 Workflow Client API

Adding a reference to the assembly
  1. SourceCode.Workflow.Client
  2. SourceCode.Hosting.Client

These 2 assemblies can be found in the following location:

  • GAC – This is if you are working from within the K2 sever
  • K2 blackpearl’s bin folder – If you have the client components installed on your machine. The default path is C:\Program Files (x86)\K2 blackpearl\bin.
  • K2 Host Server’s bin folder – If you are working from within the K2 server. The default path is C:\Program Files (x86)\K2 blackpearl\Host Server\bin.

Note: The API call is carried out via RPC, so it means that as long as you have the required DLLs with your application, you will be able to make the call even if you did not install the K2 Client Components on that machine.


Open a connection to K2 blackpearl server

To open a connection, you only need the following:

For the Open method, there are a couple of variations:

  • Open(string Server): This requires a server name that can be resolved by the DNS/Host File or an IP.
  • Open(string Server, string ConStr): The 2nd parameter provides a connection string information. See ConnectionSetup.ConnectionString property.
  • Open(ConnectionSetup setup): This requires a ConnectionSetup object. You can provide a different log in credentials here.


User Property

Once the connection is opened, the User property will show the current logged on account:

Connection object’s User property

If you find that the User property does not match the current logged on User in your ASP.NET page, it means that your web.config file is not configured to impersonate the current logged on User. Make sure the following is present in your web.config file:


Impersonate another User

If the current logged on User has the Impersonate rights on the Workflow Server:

You can execute the following code to impersonate as any User within the K2 environment:


Closing a connection to K2 blackpearl server

When you are done with the connection, always remember to close it by calling on the Close or Dispose method. You should always wrap the connection in a Using block:

Or a try-catch and/or finally block:


Start a Process Instance

To start a new process instance (a.k.a new workflow instance),  you will need to create a ProcessInstance object first.

The path to process is a combination of the root project folder name, followed by any folders’ name till the process. So in the following example:

K2 Designer for Visual Studio

K2 Workspace

The path will be “TestProject1\ModuleA\Process1”.

With the ProcessInstance object created, you will be able to update the Folio and process level Data Fields before the process instance starts. This procedure is optional.

When the necessary updates on the ProcessInstance object is completed, you will need the Connection object’s StartProcessInstance method call to kick start the process instance.

Note: The StartProcessInstance method runs asynchronously by default. If you need the method to be executed synchronously, pass a 2nd parameter “true”:


Opening a Worklist

A work list (task list) is a collection of work list items (task list items) that is assigned to the current logged on user. You need to call on the OpenWorklist method of the Connection object and it will return a Worklist object, which is a collection of WorklistItems. The following is a sample method call:

Note: The OpenWorklist method without any input parameter will return the entire collection of WorklistItems of the current User. This is not going to be efficient and very time consuming if the current User has thousands of tasks. To overcome this, we should use a Filter with the OpenWorklist method, which we will discuss in a separate article you can find here. [Updated: 4/6/2015]


Open WorklistItem

Now, the WorklistItem is a single task assigned to the current User. It has the information of the current process instance and also the Activity Destination Instance. This means that we can draw the following information from it (Just to name a few):

  • WorklistItem.ProcessInstance.Folio: The Folio of the current process instance.
  • WorklistItem.ProcessInstance.DataField[“myField”].Value: Get the process level data field.
  • WorklistItem.Data: The full URL of the task form.
  • WorklistItem.Actions: The configured Actions for this task.

To open a work list item, it means getting K2 to assign a slot to this user. This method will also validate if the current user is the valid Destination User and whether the work list item is still available for actioning.

SN stands for Serial Number, which is an identifier that the K2 server will insert as a query string parameter with the task form URL.

Just for information, the serial number comprises of:

  • Process Instance Id; and
  • Activity Destination Instance Id

The 2 values will be separated by an underscore ‘_’ symbol. For example: SN=123_45


Execution the work list item action

And of course, with the WorklistItem, you will be able to execute the configured Action (i.e. when User clicks on the Approve button).

Note: The action name needs to be spelled exactly the same as configured in the process.

Note: The Execute method runs asynchronously by default. If you need the method to be executed synchronously, pass a 2nd parameter “true”.


Here are some “more complete” sample codes if you are still unclear:

Start a new process instance

Open work list

Open work list Item

Execute an action


Have fun!!