Working with Scripting

Working with Scripting

Logi Info
v12.6 - Oct 2018

Logi Info lets you take advantage of scripting objects and functions in your Logi applications. These include inline intrinsic functions, JavaScript code embedded in your definitions, and code in external script files. This document describes the Logi elements available for working with scripts in your applications. Topics include:

 

About Scripting

Developers using Logi products have several different scripting language options available to them:
 

Script Type Description

Intrinsic

These built-in script functions are available for use in expressions and embedded script. See our document Intrinsic Functions and Operators for more information about these.

JavaScript

This is the scripting language default, using standard JavaScript syntax.

VBScript

VB Script has been deprecated - use JavaScript instead for all new applications.


Where Does Scripting Execute?

It's important to understand where scripts execute in order to get them to work correctly.
 

In the Browser or "Client-Side"

Scripts that execute in the browser, or "client-side", recognize the browser's Document Object Model (DOM) with its Window and Document objects and DHTML events, such as OnClick and OnChange, which occur in the browser. Client-side scripts are useful for calculations, input validation, dynamic page changes, and other activities that do not require an exchange with the web server. This site documents the DOM objects and syntax.

 Note that all browsers may not recognize all objects, events, and functions in exactly the same way, so cross-browser testing is highly recommended if your users will use a variety browsers and/or browser versions.
 

On the Server or "Server-Side"

Scripts that execute on the web server, or "server-side", are usually very efficient and secure, but they can't access browser DOM objects or react to user interface events. They may be able to access server system resources, such as files, using special objects and third-party APIs, though this is often considered a security risk.

  Back to the top

 

Inline Scripting with "Formula" Attributes

Some element attribute values, such as the Label element's Caption attribute and the Calculated Column element's Formula attribute, are categorized as "formula" attributes. This means they can evaluate inline script expressions and use the results as their values. In attributes where what to do might be ambiguous - display the text or evaluate it - the use of a leading equals sign (=) is used to indicate that the text should be evaluated. Typically, the functions called in these expressions are the standard intrinsic functions and run at the server.
 

For example, consider the Label element attributes shown above. The Caption attribute contains an expression that starts with an equals sign and calls the intrinsic Left() function in an expression, and will result in the word "Logi" appearing on the report page. This is an easy way to work with individual functions.

Later, we'll see how to include external files with custom functions that can be called in formula attributes.
 

Error Handling

Elements that support inline scripting also have an Error Result attribute. If something is specified in this attribute, it will be displayed or used instead of the expression result if an error occurs.

The default Error Result varies depending on the element. For example, for the Condition Filter, the default is False. For the Calculated Column and Extra Crosstab Calculated Column elements, the default is blank. For other elements, the default is ???.

Two special constants are available to control error handling related to expressions that have the possibility of causing a divide-by-zero situation. If needed, specify these constants in the _Settings definition:

rdInfinityErrorResult - Specifies a global result for expressions that may produce a divide-by-zero situation (result: infinity), sparing developers the task of specifying a result on a per-element basis in their Error Result attributes.

rdJavascriptInfinityIsError - When set to True, specifies that expressions that produce a divide-by-zero situation (result: infinity) will trigger an error, which is then handled by elements' Error Result attribute or, if set, the rdInfinityErrorResult constant. If rdJavascriptInfinityIsError is not specified, the Logi Server Engine will return the value NaN (for "Not a Number") by default when a division-by-zero attempt occurs.

  Back to the top

 

Scripting with Action.Pre-Action Javascript

The Action.Pre-Action Javascript element allows you to run code after a link, button, etc. has been clicked but before its Action element executes. This makes it much easier to do specialized input validation or to perform custom UI changes before the page is submitted.

 

As shown above, Action.Pre-Action Javascript is available as a child element of most other Action elements. If the Javascript it runs returns any value other than false, then the parent Action element will execute. If it returns false, the parent Action element will not execute. You may use multiple Action.Pre-Action Javascript elements beneath a parent Action element.

The Javascript code can be inline, as shown above, or it can be a function in a separate script file, or a function included using an Include Script element. Here's a simple example of the latter:
 

function TestColor(inpColor) {
    if ( inpColor == 'red') {
        return true;
    }
    else {
        alert('You must enter red');
        return false;
    }
}


The code shown above is placed in an Include Script element in the report definition.
 

The Action.Pre-Action Javascript element code, shown above, is:

    return TestColor(document.getElementById('inpColor').value);

If the text "red" is entered in an Input Text element on the page with an ID of "inpColor" (not shown) and the "Save data" link is clicked then the next report will be shown. If any other text is entered and the link is clicked, a warning message will appear and navigation to the next report will not occur.

  Back to the top

 

Scripting with Action.Javascript

Scripting can be run using the Action.Javascript element and it will run in the browser.
 

The example above shows how you might validate data entry, using the DHMTL onBlur event, which fires when the cursor exits the input control. You can enter multi-line JavaScript code directly into the Action element's Javascript attribute value. For example, we might use this code to ensure that an email address has been entered:
 

var mStr = document.getElementById('inpEmail').value;
if ( mStr.indexOf('@') == -1 ) {
  alert('Invalid email format');
}


The Attribute Zoom window comes in handy when entering code (double-click the attribute name).
 

Support for JavaScript "this" Keyword

The JavaScript "this" keyword is supported. When working with Event Handlers in Logi apps, this generally means that instead of code like document.getElementById('inpEmail').value you can use this.value instead. This is nice bit of shorthand for referring to the "owner" of the event and saves a lot of keystrokes. 

Here are some other JavaScript validation examples:

Example 1: Ensure some data is entered

var myStr = document.getElementById('inpLoginID').value;
if (myStr.length == 0 ) {
   alert('You must enter some message text.');
}


It's beyond the scope of this document to delve too deeply into JavaScript or the object model, but essentially the code above assigns the data in inpLoginID to a variable, then tests the length of that variable's value, and displays a message box if the length is zero. This is very similar to the Validation.Required element's functionality. The Document object's getElementById method is very handy in this situation (remember: JavaScript is case-sensitive).
 

Example 2: Ensure some data is entered but not more than 4,000 characters

var myStr = document.getElementById('inpTextArea').value;
if (myStr.length > 4000) {
   alert('Your message is too long (' + myStr.length + ' chars) - maximum length is 4,000 characters.');
}
if (myStr.length == 0 ) {
   alert('You must enter some message text.');
}


The example script above does something special: it limits the length of data that can be entered into an Input Text Area element, which doesn't have a Maximum Length attribute, and, if it's too long, reports the actual number of characters currently entered. It also requires that some data be entered.

Example 3: Replace all occurrences of '@' with '#'

var myStr = document.getElementById('inpTextArea').value;
myStr = myStr.replace(/[@]/g, '#');
document.forms[0].inpTextArea.value = myStr;


The example code above demonstrates a method for replacing certain characters in the data entered, using a JavaScript regular expression. In the example, any @ characters that were entered by the user are replaced with the # character, and then the altered data is substituted for the data that was entered. Regular expressions are very powerful, can be quite complex, and can perform actions such as adding, replacing, or removing characters, changing character case, and expanding or contracting phrases.

As you can see, the ability to run JavaScript whenever data changes in user input elements provides developers with a very powerful validation tool.

  Back to the top

 

"On Load" Scripting

Developers often want scripting functions to run as soon as the report page is loaded into the browser. Use-case examples include redirecting users who are not logged-in and setting the focus to a specific user input control. Let's see how this can be done in a Logi application.
 


In the example shown above, an Image element has been added to the report header. The image is a 1-pixel by 1-pixel white dot that blends into the header background and is effectively invisible. When the image is loaded, the Event Handler element, set for the OnLoad event, will run the Action.Javascript element. This "invisible image" technique is very common and reliable.
 

if ( '@Function.Username~' == '' ) {
    window.location = '@Constant.myLogiAppURL~/rdPage.aspx?rdReport=Login';
}


The code shown above is used in the Action.Javascript element to test the token that, when using Logi Security, contains the user name if a successful login occurred. If the token is empty, then the browser is redirected to the login page.

Using JavaScript and the DOM, you can access any of the components on the page. For example, to set the focus to a specific Input control when the page loads, you would add

document.getElementById('myTextInputID').focus();

to the code so that it runs if the @Function token has a value.

  Back to the top

 

Inserting Code Directly

The Include Script element can be used to insert script, entered into one of its attributes, directly into the HTML output when a page is generated. Script inserted in this way runs in the browser.
 

The example above shows the Include Script element as a child of the Report Header but it can be the child of the Body, Page Footer, and about 20 other elements. The inserted script will appear in the HTML code between < SCRIPT> tags (do not include these tags in the Include Script element's Included Script attribute value).

You can also use Include Script to insert tags, such as HTML < META> tags, into the page's < HEAD> section. See our document Inserting HTML Into Reports for more information.

  Back to the top

 

Scripting within External Files or 3rd Party Libraries

In the previous section we saw how script can be inserted directly into the HTML page. However, you may want to create and use your own custom functions that are stored in a external file, or use third-party libraries, such as JQuery. This can be done by including the external files using these elements:
 

Element Runs At Description

Formula Script File

Server

Used in Report definition, specifies custom or third-party script library.

Include Script File

Browser

Used in Report definition, specifies custom or third-party script library.

Procedure.Script

Server

Used in Process definition, specifies custom or third-party script library.

Additional Script File

Server

Optional child of the other three elements, specifies additional external files that contain supporting functions.


One advantage of using custom external libraries is that they can be shared and re-used in different applications. Functions in these files can be directly called from a formula attribute.

Script files can be created and edited in Studio. JavaScript and the deprecated VBScript files are listed as options when you right-click the _SupportFiles folder in Studio's Application panel and select Add New File...

Scripting in files included using the elements listed above does not require < SCRIPT> tags; they're added automatically.
 

/* this is MyFunctionLib.js */
function sayHello(UserName) {   // user name comes from his login
   return 'Hello ' + UserName + ' from Logi Analytics';
}

Script files used with Logi applications are "regular" in their syntax and form. Everything that's normally available in the scripting language, such as comments, can be used, as shown above.
 

Including Script Files

In order to include a script file in your Logi application, you need to configure one of the elements mentioned earlier. Here's an example:

 


     

  1. Add a Formula Script File element beneath the root element, as shown above.
  2. Its Script File attribute value is set to the name of the script file. If the file is in the _SupportFiles folder in Logi Studio's Application Panel, it will appear in a list of available files, as shown above. Otherwise, a fully-qualified file path can be entered.

Once this has been configured, the functions in the script file are available for use within the Report definition.

 


     

The example above shows how to call a custom function in your formula script file. It's done in exactly the same way as an intrinsic function: in a expression preceded by an equals sign (=). Once a Formula Script File element has been added, the functions in the script file it identifies are available directly to all "formula" attributes within the Report definition.
 

Working with jQuery

jQuery is a cross-browser JavaScript library designed to simplify client-side scripting and special elements are available to make it easy for developers to work with this library. Here's a quick example that uses the jQuery "date picker" UI component:

First, we configure our report definition's Style element to use a jQuery style sheet hosted online by Google:

    http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js

The jQuery versions used here are representative and other versions will work as well.
 

Then we add two Include Script File elements to our definition, as shown above, and configure their attributes to include the jQuery libraries hosted online:

    http://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js
    http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js


 The Google API hosting page suggests using these URLs with the "https:" protocol. However, if your Logi application is not specifically configured for SSL, then using "https:" URLs to include these libraries will not work. Use "http:" instead, as shown.

You could, of course, use local copies of the jQuery style sheet libraries, downloaded into _SupportFiles, by just selecting their filenames instead.
 

Next we add an Include Script element and enter our jQuery code in its Included Script attribute, as shown above. The full code is:
 

$(document).ready(function() {
    $("#divDatePicker").datepicker();
 });


And finally, we need to add a container (a Division element) for the date picker,
 

as shown above. The Output HTML Div Tag attribute must be set to True and notice that the ID of the division is used in the jQuery code, which is case-sensitive.
 

When you run the report, you should see a fully-operational date picker calendar similar to the one shown above.

This, of course, is an extremely basic example but it gives you the idea. Third-party libraries like jQuery offer a lot of functionality and, with these Logi elements, it's easy to make them work in your Logi app.

We have a more comprehensive discussion of jQuery in our document Working with jQuery.

  Back to the top

 

Process Tasks and Script Files

Scripting can also be used in Process definition tasks. Let's look at an example that uses scripting to read a text file on the web server:
 


     

  1. In the example above, a Procedure.Script element has been added to a task, and its attribute values have been set to point to the script file and function to be called.


     
     
  2. Next, a Script Input Parameters element is added beneath Procedure.Script. This is the element that passes arguments to the function and its attribute values have been set as shown.

    The arbitrary parameter name "Filename" will become part of a special token we'll use in the actual function to access the passed value. Its value is set to the name of the text file to be read. This assumes that the file is in the same folder as the script file; the value could instead include a more complete path or a combination of the @Function.AppPhysicalPath~ token and other folder/filename information.


     


  3. Next, a Script Output Parameters element is added and its attributes set to arbitrary values. This is the element that receives the value (the text from the text file) the function returns. The parameter name "result" will be the return variable in the function and we'll reference the value "outputText" later in the task to view the returned text.




     
  4. Finally, an element is added to do something with the returned text, in this case, a Procedure.Send Mail element. Its attributes are set as shown, and a token that incorporates the value from the Script Output Parameters, @Procedure.procReadTextFile.outputText~, is used to access the text returned from the function.

function ReadFile() {
    var forReading = 1;
    var fso = new ActiveXObject('Scripting.FileSystemObject');
    var tf = fso.OpenTextFile('@Input.Filename~', forReading);
    result = tf.ReadAll();
    tf.Close();
}


An example of the JavaScript that might be used for this purpose is shown above. Note the way in which the @Input token and result variables are used.

 The example above uses a Logi Server Engine object that is not available on Windows 64-bit or Java platforms.

  Back to the top

 

Debugging Script Files

You can also cause debugging to extend to scripts. When enabled, a special link will be included in the standard Debugger Trace page:
 

To enable this, configure the General element's Script Source Debugger Style attribute.

Its None value is the default, or you can set it to OnError, in which case the View Script File link shown above appears in the Debugger Trace Page when an error occurs. This link displays the script as generated when the report was run. If the script is a simple, single line of script, the actual error may appear here instead of a link.

A third value option, Always, causes the link to appear in the trace page at all times. The routine use of Always is discouraged as it will incur a significant performance hit.

  Back to the top

 


© Copyright 2007-2019 Logi Analytics, Inc. All Rights Reserved