Thursday, January 23, 2014

Conditional Validation in K2 SmartForm

I have to admit that currently K2 SmartForm is lack of built-in validation functionality, you can only specify which fields are required to be specified before the form is submitted.

In this post, I will show you a trick how to create a custom validation based on a condition.

Our form (or view) is very simple:

image

It contains:

  • 2 Text boxes which have names: Amount Text Box and Comment Text Area
  • 2 Labels for field header (I ignore the control’s names).

It is a petty cash request form. User can request for specified amount of money and specify notes if needed. Here is the condition:

  • If Request amount >= 1000000 (above or equal to 1 million), user must specify notes.
  • If Request amount < 1000000 (below 1 million), the notes field is optional to be specified.

If we use common validation condition in SmartForm, we can only specify whether field Notes is required or not, we cannot validate Notes based on certain condition.

Here is my trick;

1. Add a text box to Form or View, give it name: Notes. Clear Visible check box in its property. This new text box will act as fake “Notes” text box:

image

 

2. Create some expressions, click the Notes text box (the invisible textbox), select Expressions in property window, click Add to add new expression, give it name Comment is Blank:

image

Create a new expression again and give it name Request Above 1M:

image

Create again a new expression and give it name Notes Validation:

image

Value 9 is random value, you can use any value other than 9.

Make sure the last expression is selected before closing Expression window:

image

 

3. Create rule for click event of Submit button, add validation to the rule:

image

 

4. Specify validation configuration:

image

See validation configuration window above: mark Amount Text Box and Notes (text box) as required. Note that Comment Text Area does not need to be required and do not activate “Do not validate hidden…” option, and activate “Show validation message…”.

Then add Show a Message action if validation passes:

image

Click OK and then click Finish to close message configuration window and Rules Wizard Configuration window.

Click Finish to save the Form / View.

Let’s try to run the Form / View:

If I specify 500000 in Request Amount text box and I do not specify any comments, my request can be submitted:

image

However, if I specify 5000000 in Request Amount text box, the validation will occur:

image

I have to specify something in Notes field (it is Comment Text Area) :

image

You can make the Notes text box becomes visible to see how this trick happens and yes, building forms using K2 SmartForm is very tricky Smile with tongue out

Wednesday, January 8, 2014

Creating Running Number in K2 SmartForm

This post will show you how to generate running number using K2 SmartForm. Running Number is a common feature in transaction forms, such as Invoice Number, Purchase Order Number, Quotation Number, etc. It is always incremented by 1 for each saved entry.

In this post, I will show you an example how to generate request number for Room Booking Request. Room Booking Request can be used for requesting a room for a purpose such as meeting, interviewing, and so on.

Let’s create our Room Booking Request SmartObject, give it name as Booking:

image

Request Number will contain running number which we’ll develop later in this post.

Let’s create Auto Number SmartObject:

image

Current Number will contain a number which is always increment by 1 for each new booking request.

Then, using SmartObject tester, insert a default row to Auto Number SmartObject:

image

Give the value 1 to Current Number and RO for Request Type, then click Execute to create a new row.

Now, we will generate a view for booking request data entry, right click on Booking SmartObject, then click Generate Views, click Item and give it name as Booking Item:

image

Click OK to generate the view.

Make a view layout to be neat looking as follow:

image

Delete Create, Delete, Load buttons as we don’t need them, change Save button text to Save as Draft. Then add two text boxes to the view, give them name Current Number Text Box and Increment Number Text Box, we can place them anywhere since we will make them as invisible to users. In my example below, the two new text boxes is placed next to Save as Draft button.

image

Switch to Rules tab and inspect when Save Button is clicked rule, K2 Designer has created a default behavior for Save:

image

Add a new action Execute SmartObject method before Execute the Save method.

In the newly added action: select Auto Number SmartObject, and select Load method.

image

Click configure option of the newly added action:

In Request Type input mapping type RO:

image

Click Next, then map Current Number property to Current Number Text Box:

image

Add a new action again of Execute SmartObject method after Execute the Save method, select Auto Number Smart Object and Save method:

image

Click configure option:

Map Increment Text Box to Current Number and type RO in Request Type:

image

Click Finish to close configuration window.

Add a new action again of Close browser window:

image

Click Finish to close Rules Wizard Configuration window.

Switch back to Layout tab, then select Increment Text Box, select Expression property, click Add to create a new expression. Drag Current Number Text Box to expression details area , drag Plus operator from Operators tab – Operators node, and type 1 after Plus operator. Click Validate to verify the expression.

image

If the expression validation passes, click Finish twice to return to view layout.

Select Request Number Text Box, then select Expression property, click Add to create a new expression. Give it name Running Number Format as expression name. Drag Concatenate function from Operators tab – Text node, and drag Pad Left function as follow:

image

Click Finish twice to return to view layout. Make the Current Number Text Box and Increment Number Text Box invisible by unchecking Visible check box property.

Click Finish again to save the view.

Now we can try to run the view. Click on Booking Item view at the tree node, you will see Runtime URL at right panel, click the Runtime URL, the browser will create a new window/tab:

image

Click Save as Draft to save entry and the view will be closed after saving.

To view the request data, switch to SmartObject Tester, select Booking SmartObject, right click and select Execute SmartObject, change Method to Execute to GetList and click Execute button:

image

Why my request number starts from 7 ? Because I had tried to create data before I wrote this blog post  and I deleted them all. But if you follow steps in this article, your request number must be started from 1 (RO001).

Sunday, January 5, 2014

Extract PDF file from K2 PDF SmartObject

In K2 workflow, we can create PDF file using PDF SmartObject, located in System node:

image

PDF Converter is a built-in SmartObject in K2 to create PDF and save it in PDF File SmartOject. The PDF is saved as BLOB. Actually it is a column contains XML and in the XML contains PDF as binary content.

The problem is, I have to extract the PDF and copy it to the file server using Windows File Sharing. K2 does not have built-in feature to extract PDF to physical file, thus I have to create it.

The following code utilizes SmartObject Client API to communicate with PDF File SmartObject in K2 Blackpearl server.

   1:  public void ExtractPDFWithSmartObject(int snapshotID, string fileName)
   2:  {
   3:      var smartObjServer = new SmartObjectClientServer();
   4:   
   5:      using (var connection = smartObjServer.CreateConnection())
   6:      {
   7:          connection.Open(k2WorkflowServer);
   8:          //smartObjServer.Connection.Open();
   9:   
  10:          var pdfSmartObj = smartObjServer.GetSmartObject("PDFFile");
  11:          pdfSmartObj.MethodToExecute = "Load";
  12:          pdfSmartObj.Properties["ID"].Value = snapshotID.ToString();
  13:   
  14:          var result = smartObjServer.ExecuteScalar(pdfSmartObj);
  15:          var file = (SmartFileProperty)pdfSmartObj.Properties["PDF"];
  16:          byte[] data = Convert.FromBase64String(file.Content);
  17:          File.WriteAllBytes(fileName, data);
  18:      }
  19:  }



Add reference to SourceCode.HostClientAPI.dll and SourceCode.SmartObjects.Client.dll


Parameter snapshotID is an ID created by Create* method of PDF Converter and parameter fileName is a physical file name to be created in file system.


In line 7, we have to create string variable named k2WorkflowServer, this variable will be populated as connection string to K2 Blackpearl server.


The complete code can be downloaded from here, it is a .NET DLL file and can be referenced from K2 workflow.


 


Call this DLL from K2 Workflow



To use this DLL (PDFHelper.dll), open your K2 workflow (.kprx) using K2 Designer for Visual Studio, add Code Reference Event and add reference to PDFHelper.dll


In Code Reference Event, add call constructor and pass the K2 Connection String as parameter.
image


then call instance method ExtractPDFWithSmartObject and pass snapshot ID and filename as parametersOpen-mouthed smile:


image




Do I have to use Visual Studio to use this DLL in my K2 workflow?


If I use K2 Studio to add reference to this workflow, strangely I cannot call constructor and call instance method, it seems K2 Studio cannot load PDFHelper.dll. But if I use Visual Studio, I can add reference, call constructor, and call instance method smoothly.

Tuesday, November 26, 2013

Zooming

If you have been doing public presentation using projector and laptop, you may want to zoom an area or region to make the audience pay attention for some details in your screen. Usually, the presenter will change zoom level of projector, or the presenter will change the font size of the presentation document.

Actually, Windows has a built-in zoom feature that you can activate it easily with single keystroke. The built-in zoom tool is Magnifier and you can activate it by pressing Windows and Plus key. The plus key usually placed beside backspace button.

image

If you press Windows-Plus once, you will activate Magnifier and your screen has not zoomed yet. Press it for the second time will zoom your screen.

You can bring your screen to normal size (zoom out), either by pressing Windows – Minus or close the Magnifier window.

The other tool to zoom your screen is ZoomIt from SysInternals tool, and you can download and using it freely. With ZoomIt, you can define your own keystroke for zooming-in and zooming-out.

image

The Ctrl-1 is the default keystroke for toggle zooming.

Friday, November 22, 2013

Removing USB Drive

Sometimes I’m too lazy to remove USB drive using taskbar. We can remove USB drive from taskbar by clicking Safely Remove Hardware and Eject Media.

image                image

but as I said, sometimes I’m too lazy to do it and I prefer remove it by using command line since I can do it immediately rather than moving my pointing device.

The command line tool can be downloaded from here.

Using this tool, I can remove my USB drive or other removable drive from command prompt:

image

we can also invoke it using PowerShell:

image

Thursday, November 21, 2013

Say goodbye to Winamp

This is very sad news. Winamp will be discontinued and no longer available for download officially, except from unofficial sites. I had always install this software when I used Windows 95 and Windows 98. It is well known as a lightweight software to play MP3 and it has great visualizations and equalizers. I also have used Winamp to rip CDs.

This sad news came from winamp.com:

image

Wednesday, November 20, 2013

How to Create CLR Stored Procedure

Since SQL Server 2005, developers can write stored procedures using .NET languages. In this post, I will show you how to create stored procedure using C# using SQL Server 2008 R2 and Visual Studio 2012. If you use newer version of SQL Server, the solution should also be applied. I will create factorial function as applied in Math such as:

5! = 5 * 4 * 3 * 2 * 1 = 12

First, we have to download SQL Server Data Tools (SSDT). At this time of writing, I use SSDT for Visual Studio 2012 October Release which can be downloaded from here.

Then, launch SSDT setup and wait until finished.

Launch Visual Studio 2012, create new project, select SQL Server template, and select SQL Server Database Project.

image

Since I’m using SQL Server 2008R2, I have to change target framework to .NET Framework 3.5. Change the name to SPFaktorial and click OK to create the project, Visual Studio 2012 will create the Database Project for you.

In Solution Explorer, right click in project, click Add – New Item, select SQL CLR C#, then select SQL CLR C# User Defined Function.

image

Change the name to Faktorial and click Add, Visual Studio will create a C# file contains some dummy codes. We can change this code to our factorial function:

   1:  using System;
   2:  using System.Data;
   3:  using System.Data.SqlClient;
   4:  using System.Data.SqlTypes;
   5:  using Microsoft.SqlServer.Server;
   6:   
   7:  public partial class Matematika
   8:  {
   9:      [Microsoft.SqlServer.Server.SqlFunction]
  10:      public static SqlInt64 Faktorial(int f)
  11:      {
  12:          if (f == 1)
  13:              return f;
  14:   
  15:          return f * Faktorial(f - 1);
  16:      }
  17:  }



Our factorial function is a recursive function, it will call itself until the factorial number turns 1.


Let’s build the project! Select Build menu, then select Build Solution. If you see in project folder, Visual Studio will create Debug folder which contains compiled .NET assembly inside.


Actually, we can directly deploy our project to SQL Server, but in this post I will show you how to manually deploy our .NET assembly to SQL Server.


Lets launch the SQL Server Management Studio and connect to the Database Engine and open New Query window, then issue this command:

exec sp_configure 'clr enabled', 1
go
reconfigure
go



The command above will enabling CLR feature (which is disabled by default).


At this point, we are ready to deploy the .NET assembly to SQL Server using CREATE ASSEMBLY:

create assembly SPFaktorial
from 'D:\Docs\visual studio 2012\Projects\SPFaktorial\SPFaktorial\bin\Debug\SPFaktorial.dll'



Press F5 to run the command, then we have to create T-SQL function to wrap the CLR method:

create function Faktorial(@i int) returns bigint
as external name SPFaktorial.Matematika.Faktorial



Press F5 to run the command.


At this point, the .NET assembly has been deployed successfully to SQL Server, the next step is to test it:


image


Voilla….our C# method has been successfully executed inside SQL Server.


The sample code can be downloaded from here.