Thursday, May 19, 2011

K2 BlackPearl 4.5 Server Event Code Snips

OK - I'm still new to K2, and slowly figuring out how to work with K2 in C#. This post will be my little scrapbook of helpful code chunks for later use.

Get count of a specific user's worklist items for a given process - within a K2 Server Code event.
Use a new workflow client connection to the server to do all the work.

// create a new workflow client connection
using (Connection c = new Connection())

    // Using ConnectionSetup as connection string
    ConnectionSetup cs = new ConnectionSetup();
    // From a server code event in a K2 process we can use K2 environment variables for connection strings
    cs.ConnectionString = K2.StringTable["Workflow Server"].ToString();
    // Open server connection using ConnectionSetup

    // Impersonate Bryan so we can get at his worklist >_>

    // Build worklist filter criteria
    // We only want to return work items that match a given process
    WorklistCriteria wc = new WorklistCriteria();
    wc.Platform = "ASP";
    wc.AddFilterField(SourceCode.Workflow.Client.WCField.ProcessName, WCCompare.Equal, "BryansTestProcess");

    // dump resulting count of Bryans worklist items for the BryanTestProcess to a K2 Data Field
    int itemCount = c.OpenWorklist(wc).TotalCount;
    K2.ProcessInstance.DataFields["BryansWorklistCount"].Value = itemCount;

Get distinct count of process instances for a given process pending a specific activity - within a K2 Server Code event.
Use a K2 SmartObject to do all the work.

// Use SmartObjectClientServer for accessing SmartObjects
SmartObjectClientServer sos = new SmartObjectClientServer();

// Prep the connection

// From within a K2 process Server Code event, use K2 environment variables for connection strings
sos.Connection.Open(K2.StringTable["SmartObject Server"]);

// Get an "Activity Instance Destination" SmartObject (an OotB K2 SmartObject)
SmartObject so = sos.GetSmartObject("Activity_Instance_Destination");

// Tell the SmartObject to return a list of results
so.MethodToExecute = "List";

// Set filter for results - return active items pending "Bryans First Activity" for "BryansTestProcess"
so.Properties["ActivityName"].Value = "Bryans First Activity";
so.Properties["ProcessName"].Value = "BryansTestProcess";
so.Properties["Status"].Value = "Active";

// Execute - return the results as a DataTable
DataTable dt = sos.ExecuteListDataTable(so);

// If you use groups for destinations by using advanced mode to split groups to users...
// you can get duplicate Process Instance IDs - one for every user in the group
// to get a distinct list of process instances, use a datatable view to return distinct results
DataTable DistinctDT = dt.DefaultView.ToTable(true, "Process Instance ID");

// copy the resulting count to a K2 process data field
K2.ProcessInstance.DataFields["WorklistCount"].Value = DistinctDT.Rows.Count;

// and do cleanup

No comments: