Blog: Posts from August, 2012

Labels
AJAX(112) App Studio(7) Apple(1) Application Builder(245) Application Factory(207) ASP.NET(95) ASP.NET 3.5(45) ASP.NET Code Generator(72) ASP.NET Membership(28) Azure(18) Barcode(2) Barcodes(3) BLOB(18) Business Rules(1) Business Rules/Logic(140) BYOD(13) Caching(2) Calendar(5) Charts(29) Cloud(14) Cloud On Time(2) Cloud On Time for Windows 7(2) Code Generator(54) Collaboration(11) command line(1) Conflict Detection(1) Content Management System(12) COT Tools for Excel(26) CRUD(1) Custom Actions(1) Data Aquarium Framework(122) Data Sheet(9) Data Sources(22) Database Lookups(50) Deployment(22) Designer(177) Device(1) DotNetNuke(12) EASE(20) Email(6) Features(101) Firebird(1) Form Builder(14) Globalization and Localization(6) How To(1) Hypermedia(2) Inline Editing(1) Installation(5) JavaScript(20) Kiosk(1) Low Code(3) Mac(1) Many-To-Many(4) Maps(6) Master/Detail(36) Microservices(4) Mobile(63) Mode Builder(3) Model Builder(3) MySQL(10) Native Apps(5) News(18) OAuth(9) OAuth Scopes(1) OAuth2(13) Offline(20) Offline Apps(4) Offline Sync(5) Oracle(11) PKCE(2) Postgre SQL(1) PostgreSQL(2) PWA(2) QR codes(2) Rapid Application Development(5) Reading Pane(2) Release Notes(183) Reports(48) REST(29) RESTful(29) RESTful Workshop(15) RFID tags(1) SaaS(7) Security(81) SharePoint(12) SPA(6) SQL Anywhere(3) SQL Server(26) SSO(1) Stored Procedure(4) Teamwork(15) Tips and Tricks(87) Tools for Excel(2) Touch UI(93) Transactions(5) Tutorials(183) Universal Windows Platform(3) User Interface(338) Video Tutorial(37) Web 2.0(100) Web App Generator(101) Web Application Generator(607) Web Form Builder(40) Web.Config(9) Workflow(28)
Archive
Blog
Posts from August, 2012
Wednesday, August 1, 2012PrintSubscribe
Validators and Converters

A common requirement in web applications is to perform validation and conversion of field values whenever a user inserts or updates a record, or changes a field value. Code On Time web applications allow the creation of business rules of any complexity using JavaScript, SQL, or C#/Visual Basic. To help get you started, the Project Designer can set up a simple generic validator or converter. The validators and converters have a consistent implementation model.

Validator

Start the Project Designer. In the Project Explorer, switch to the Controllers tab. Right-click on Orders / Fields / OrderDate field node. The context menu will display commands to create a Validator or Converter using JavaScript, SQL, or Code (C#/Visual Basic).

Select Add SQL Validator option.

Add SQL Validator context menu option for a field in the Project Explorer in Code On Time web application generator.

Press OK to confirm creation of the business rule.

Confirmation window to add an SQL business rule.

A validation SQL business rule will be configured to prevent saving of blank values in OrderDate field.

New SQL business rule added to Orders controller.

The script for the sample SQL business rule goes as follows:

if @OrderDate is null
begin
    /* prevent the default action processing */
    set @BusinessRules_PreventDefault = 1
    /* set the focus on the field and display an error */
    set @Result_Focus = 'OrderDate,Required field.'
end

On the Project Browser toolbar, press Browse button and wait for the web application to load.

Navigate to the Orders page, and edit an order. Clear the OrderDate field, and press OK to save. The business rule will validate the Order Date and show a message showing that the field is required.

Order Date field validated and message has appeared declaring that the field is required.

Note that this is a generic validation example. A simpler method to insure that the field is not blank is to mark it as required. Use a business rule when a more complex validation is needed.

Custom Validator

Let’s modify the sample business rule in order to perform a more complex validation. In the Project Explorer, right-click on Orders / Fields / Freight data field node. Select Add SQL Validator.

Add SQL Validator context menu option for a field in Orders controller.

The Project Browser will open the new business rule. Replace the sample script with the following:

if (@Freight is null) or 
    not(@Freight >= 5 and @Freight <= 30)
begin
    /* prevent the default action processing */
    set @BusinessRules_PreventDefault = 1
    /* set the focus on the field and display an error */
    set @Result_Focus = 'Freight,The range is between 5 and 30.'
end

Press OK to save the business rule. On the toolbar, press Browse.

Navigate to the Orders page, and create a new order. If you press OK without entering any values, the first validator on Order Date will display a “Required field.” message.

Error message displayed for validated field when new order is saved.

Enter a value in Order Date. In the Freight field, type “4”, and press OK to save. A message will be displayed, warning the user that the value must be between 5 and 30.

Error message displayed if Freight is not validated in the correct range.

Enter a value in the specified range. When you press OK, the validation test will pass and the record will be saved.

New order saved when Freight value is in the correct range.

Converter

Switch back to the Designer. Right-click on Customers / Fields / City field node. Select Add JavaScript Converter option.

Add JavaScript Converter context menu option for City field in Customers controller.

Press Yes to confirm the addition.

Confirm the creation of a JavaScript converter.

The field will automatically be configured as a calculated field. A business rule will be added that will convert the field value to uppercase when a user inserts, updates, or switches focus from the field.

City_Converter business rule added for Customers controller.

The preconfigured business rule script will look as follows:

var fieldValue = [City];
var commandName = this.arguments().CommandName
var triggerFieldName = this.arguments().Trigger;
var tryConversion = commandName != 'Calculate' ||
    triggerFieldName == 'City';
if (fieldValue != null && tryConversion) {
    // make sure that the value is a string
    fieldValue = fieldValue.toString();
    // convert the value to an upper-case string
    var newFieldValue = fieldValue.toUpperCase();
    // assign a new value to the field
    [City] = newFieldValue;
    // prevent the server-side processing of the event
    if (commandName == 'Calculate')
        this.preventDefault();
}

On the toolbar, press Browse.

Navigate to the Customers page, and create a new record. Type a value in the City data field.

Lowercase text entered into City field.

Press Tab on your keyboard, or use the mouse to shift focus. The value entered in City will be converted to uppercase.

Upon exiting the City field, the JavaScript business rule converts the field value to uppercase.

The major benefit of implementing converters in JavaScript is that the script is executed by the web browser and requires no server interaction.

Custom Converter

Let’s customize the standard converter to perform a more advanced operation – conversion of phone numbers.

In the Project Explorer, right-click on Employees / Fields / HomePhone field node, and select Add JavaScript Converter.

Add JavaScript Converter context menu option for HomePhone field in the Project Explorer.

The business rule will open in the Project Browser. Replace the default business rule script with the following:

var fieldValue = [HomePhone];
var commandName = this.arguments().CommandName
var triggerFieldName = this.arguments().Trigger;
var tryConversion = commandName != 'Calculate' ||
    triggerFieldName == 'HomePhone';
if (fieldValue != null && tryConversion && fieldValue.match(/^\d{10}$/)) {
    var newFieldValue = fieldValue.replace(/(\d{3})(\d{3})(\d{4})/, '($1)-$2-$3');
    [HomePhone] = newFieldValue;
    // prevent the server-side processing of the event
    if (commandName == 'Calculate')
        this.preventDefault();
}

Press OK to save the business rule. On the toolbar, press Browse.

Navigate to the Employees page. Create a new employee, and type in 10 digits in the Home Phone field.

10 Digits entered into Home Phone field.

Shift focus away from the field by pressing Tab or clicking on another area of the page. The digits will be formatted as a US phone number.

Home Phone field value converted into US Phone format.

Code Validators and Converters

If neither SQL or JavaScript is flexible enough, then validation or conversion can be performed with the full power of Microsoft.NET. Code validators and converters are created using the programming language of your project.

Right-click on Customers / Fields / City field node, and press Add Code Converter.

Add Code Converter context menu option in Code On Time's Project Explorer.

Press OK to confirm the creation of a code business rule.

Confirm creation of a code business rule.

On the toolbar, press Generate or Browse to have the code generator produce the source code.

When complete, right-click on Customers / Business Rules / City_Converter node and press Edit Rule in Visual Studio if you want to see the source code.

Edit Rule in Visual Studio context menu option for a business rule in Code On Time web application generator.

The business rule file will open in Visual Studio. The generic handler will look as follows:

C#:

using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Security;
using MyCompany.Data;

namespace MyCompany.Rules
{
    public partial class CustomersBusinessRules : MyCompany.Data.BusinessRules
    {
        
        /// <summary>
        /// Rule "City_Converter" implementation:
        /// This method will execute in any view before an action
        /// with a command name that matches "Calculate|Insert|Update".
        /// </summary>
        [Rule("r100")]
        public void r100Implementation(string customerID, 
            string companyName, string contactName, string contactTitle, 
            string address, string city, string region, string postalCode, 
            string country, string phone, string fax)
        {
            if (!(String.IsNullOrEmpty(city)) && 
                (this.Arguments.CommandName != "Calculate" ||
                (this.Arguments.Trigger == "City")))
                UpdateFieldValue("City", city.ToUpper());
        }
    }
}

Visual Basic:

Imports MyCompany.Data
Imports System
Imports System.Collections.Generic
Imports System.Data
Imports System.Linq
Imports System.Text.RegularExpressions
Imports System.Web
Imports System.Web.Security

Namespace MyCompany.Rules

    Partial Public Class CustomersBusinessRules
        Inherits MyCompany.Data.BusinessRules

        ''' <summary>
        ''' Rule "City_Converter" implementation:
        ''' This method will execute in any view before an action
        ''' with a command name that matches "Calculate|Insert|Update".
        ''' </summary>
        <Rule("r100")> _
        Public Sub r100Implementation(ByVal customerID As String,
                                      ByVal companyName As String,
                                      ByVal contactName As String,
                                      ByVal contactTitle As String,
                                      ByVal address As String,
                                      ByVal city As String,
                                      ByVal region As String,
                                      ByVal postalCode As String,
                                      ByVal country As String,
                                      ByVal phone As String,
                                      ByVal fax As String)
            If (Not (String.IsNullOrEmpty(city)) AndAlso
                (Not ((Me.Arguments.CommandName = "Calculate")) OrElse
                 (Me.Arguments.Trigger = "City"))) Then
                UpdateFieldValue("City", city.ToUpper())
            End If
        End Sub
    End Class
End Namespace

Let’s try the rule in action. Navigate to the Customers page, and create a new record. Type a value in the City data field.

Lowercase text entered into City field on New Customers form.

Press Tab on your keyboard, or use the mouse to shift focus. The value entered in City will be converted to uppercase.

Text in City converted into uppercase.

Wednesday, August 1, 2012PrintSubscribe
Handling “Custom” Actions

Code On Time web applications can have “Custom” actions that trigger business rules.

For example, let’s implement a custom action on orders form to count the number of order details that belong to the order.

Creating Action

Start the Project Designer. In the Project Explorer, switch to the Controllers tab. Right-click on Orders / Actions / ag2 action group node, and press New Action.

New Action context menu option for action group in the Project Explorer.

Give this action the following properties:

Property Value
Command Name Custom
Command Argument CountOfOrders
Header Text Count of Order Details

Press OK to save the action.

Creating Business Rule

In the Project Explorer, right-click on Orders / Business Rules node, and press New Business Rule.

New Business Rule context menu option for Business Rules node in the Project Explorer.

Assign the following properties:

Property Value
Type SQL
Command Name Custom
Command Argument CountOfOrders
Phase Execute
Script
declare @CountofOrderDetails int

select distinct @CountofOrderDetails = count(ProductID)
from "Order Details"
where OrderID = @OrderID

set @Result_ShowViewMessage = 
    'This order contains ' +
    cast(@CountofOrderDetails as nvarchar) +
    ' order details.'

Press OK to save the business rule. On the toolbar, press Browse to generate the web app.

Navigate to the Orders page. Select an order – you will see the action Count of Order Details on the form.

Count of Order Details button displayed on the form.

Click on the Count of Order Details button, and a message will appear above the view displaying the count of order details.

When Count of Order Details is pressed, a message is displayed above the view.