Download as pdf or txt
Download as pdf or txt
You are on page 1of 100

uniGUI Developer Manual

© 2016 FMSoft Co. Ltd.


2 uniGUI Developer Manual

Table of Contents
Foreword 0

Part I Introduction 4

Part II Installation 5
1 System
...................................................................................................................................
Requirements 5
2 Installation
...................................................................................................................................
Instructions 6
3 Sencha
...................................................................................................................................
Touch Installation 14
4 Running
...................................................................................................................................
Demos 15

Part III Technology Overview 20


1 Unified
...................................................................................................................................
GUI 21
2 Web
...................................................................................................................................
Sessions 22
3 Deployment
...................................................................................................................................
Options 23
4 Forms
...................................................................................................................................
and Modules 25
Application
.........................................................................................................................................................
MainForm 25
LoginForm......................................................................................................................................................... 26
MainModule......................................................................................................................................................... 28
ServerModule
......................................................................................................................................................... 28
ServiceModule
......................................................................................................................................................... 29
DataModules
......................................................................................................................................................... 29
Fram es ......................................................................................................................................................... 30
5 Special
...................................................................................................................................
Objects 31
UniApplication
.........................................................................................................................................................
Object 31
UniSession.........................................................................................................................................................
Object 32
UniServerInstance
.........................................................................................................................................................
Object 33

Part IV Developer's Guide 33


1 Creating
...................................................................................................................................
a New uniGUI Application 33
Standalone
.........................................................................................................................................................
Server Project 35
Standalone
.........................................................................................................................................................
Server / ISAPI Module Project 35
ISAPI Module
.........................................................................................................................................................
Project 37
Window s Service
.........................................................................................................................................................
Project 37
2 Application
...................................................................................................................................
Design Considerations 38
General Design
.........................................................................................................................................................
Concept 38
Web Application
.........................................................................................................................................................
Scalability 41
Create Resource
..................................................................................................................................................
on Demand 41
Database Connections
.................................................................................................................................................. 42
Third party
.........................................................................................................................................................
Com ponent Libraries 42
Reporting Tools
.................................................................................................................................................. 44
FastReport........................................................................................................................................... 44
ReportBuilder ........................................................................................................................................... 45
Using a Report ...........................................................................................................................................
Server 46
Creating Controls
.........................................................................................................................................................
at Runtim e 46
Object Lifetim
.........................................................................................................................................................
e Managem ent 46

© 2016 FMSoft Co. Ltd.


Contents 3

3 Client-side
...................................................................................................................................
Scripting 46
4 Web
...................................................................................................................................
Deployment 47
Sencha License
.........................................................................................................................................................
Considerations 47
uniGUI Runtim
.........................................................................................................................................................
e Package 48
Adjusting .........................................................................................................................................................
Paths 49
Standalone .........................................................................................................................................................
Server 52
Window s Service
......................................................................................................................................................... 53
ISAPI Module
......................................................................................................................................................... 55
IIS 5 .................................................................................................................................................. 55
IIS 6 .................................................................................................................................................. 60
IIS 7 and Later
.................................................................................................................................................. 69
ISAPI and CGI ...........................................................................................................................................
Restrictions 80
Apache 2.2 .................................................................................................................................................. 82
SSL Configuration
......................................................................................................................................................... 82
Obtain a SSL ..................................................................................................................................................
Certificate from an Authority 84
Generate a..................................................................................................................................................
Self-Signed Certificate 85
Configure ..................................................................................................................................................
SSL Parameters 88
Adjusting .........................................................................................................................................................
Folder Access Rights 90
5 Stress
...................................................................................................................................
Test Tool 91
Introduction
......................................................................................................................................................... 91
Usage ......................................................................................................................................................... 92
Recording..................................................................................................................................................
a Session 92
Running the ..................................................................................................................................................
Stress Test 94
Server Flood ..................................................................................................................................................
Protection Considerations 97
Additional ..................................................................................................................................................
Settings 98

Index 99

© 2016 FMSoft Co. Ltd.


4 uniGUI Developer Manual

1 Introduction

uniGUI is a Web Application Framework for Delphi. C++ Builder development is also
supported for RAD Studio owners. uniGUI features a rich set of visual controls for developing stateful
Web applications. Development process which is very similar to developing regular VCL applications.
uniGUI Web applications can easily be run and debugged directly in Delphi IDE which makes
development process very easy and straightforward. uniGUI extends Web application development
experience to a new dimension. In this new dimension productivity is the primary goal. uniGUI
allows developer to focus on application business logic rather than working on web application
development details such as working directly with HTML, JavaScript, XML Templates, and other web
technologies. uniGUI will save many valuable development hours which in turn helps to considerably
reduce project development, deployment and support costs. This makes uniGUI a perfect tool for
small development teams which have a limited resources to spend on development details. uniGUI is
also perfect for large teams who need to deliver enterprise scale projects in a limited time scale.

Deployment is another serious step in Web application development process. With uniGUI
deployment is very easy and straightforward. Developers can choose one of the available options for
deployment; Such as, Windows Service, Standalone Server or ISAPI Module. ISAPI modules
can be deployed using Microsoft IIS, Apache Web Server for Windows or any other compatible
ISAPI enabled Web server.

uniGUI uses Sencha Ext JS and Sencha Touch libraries for client side rendering. These
libraries are considered as one of the industries leading frameworks to create RIA applications.
uniGUI combines powers of Ext JS with RAD capabilities of Delphi which probably is the fastest way
of creating a RIA applications in Delphi. uniGUI encapsulates Ext JS classes inside a special set of
Delphi controls which enables developers to create feature rich web applications without a need to
learn client side scripting and working on UI details on client side, so valuable development time can
be spent on business logic rather than working on repetitive UI design details which can be time
consuming and technically demanding tasks.

© 2016 FMSoft Co. Ltd.


Introduction 5

uniGUI application in Delphi 10 Seatle IDE

Web Application running inside a brow ser

2 Installation
2.1 System Requirements
Supported Delphi* versions are Turbo Delphi, Delphi 2006, Delphi 2007, Delphi 2009, Delphi
2010, Delphi XE-XE8 and Delphi 10 Seatle.

C++ Builder is supported but not tested with all Versions.

uniGUI does not require any special hardware or OS configuration. A typical uniGUI installation will
occupy 100-150MB of HDD space.

Note 1: Requirement for runtime environment can be very different and will be discussed under
deployment topic.
Note 2: In order to install uniGUI for C++ Builder you need to have RAD Studio IDE installed.
Installing C++ Builder alone is not enough. Please see Installation Instructions for details.

*All Delphi versions must be installed with latest available updates and service pack s.

© 2016 FMSoft Co. Ltd.


6 uniGUI Developer Manual

2.2 Installation Instructions


Installation instructions for uniGUI (Delphi and C++ Builder**)

· Before installing a new version remove all design packages from Delphi and uninstall uniGUI from
Windows Program Add/Remove.
· After re-compiling an application with this new version, "ext" folder must be re-deployed to PCs
running new version of your application or you can simply re-install the newly introduced Ext JS
runtime package which can be downloaded from Downloads page.

**Note for C++ Builder: You need RAD Studio IDE to install uniGUI for C++ Builder.

1) Download the latest uniGUI Setup from customer portal.


You will notice that there are two versions for of setup:

· FMSoft_uniGUI_{Edition_0.XX.0.YYYY}_Beta.exe
o This is the one which will be installed on developer PC for development purpose only.
· FMSoft_uniGUI_{Edition_runtime_0.XX.0.YYYY}.exe
o This one is only for deployment purpose and will be installed on your server PC which your
uniGUI apps will run.

2) Enter required information. Make sure entered email address is same as email address registered
in customer portal.

© 2016 FMSoft Co. Ltd.


Installation 7

3) Accept the license agreement by pressing next.

4) Enter your license key in memo field as shown below.

© 2016 FMSoft Co. Ltd.


8 uniGUI Developer Manual

Note: Starting from version 0.99.95 license keys are directly obtained from an activation server. You
can easily get your license key by pressing the Get License Key button. This will fill the License
Key area with an appropriate key. Alternatively you can get your license key by clicking on the blue
link: Web link to license key.... This will open a browser window which will open a page containing
your key. You can paste the key in License Key area.

After key is acquired you can press Continue... button and proceed to the next step.

It is also possible to save your acquired license key in a local file and use it next time you re-install
same edition and version of uniGUI.

© 2016 FMSoft Co. Ltd.


Installation 9

5) Select an installation folder. Default installation folder is [ProgramFiles]\Fmsoft\Framework \.

6) Select Delphi version(s) you want to install uniGUI library. You must be sure that Delphi is not
running while installation is in progress. Current version of installer will not warn you about this.

© 2016 FMSoft Co. Ltd.


10 uniGUI Developer Manual

7) Press Install to start and complete the installation process.

8) Start Delphi and open the project group for your Delphi version. e.g. uniGUI2016Group (Delphi
XE6).

**Additional step for C++ Builder: Instead of Delphi IDE open project in RAD Studio IDE.

© 2016 FMSoft Co. Ltd.


Installation 11

© 2016 FMSoft Co. Ltd.


12 uniGUI Developer Manual

9) In project manager there are 11 Delphi packages. Build all packages starting from
SynEdit_Rxxxx.bpl.

**Additional step for C++ Builder: Before building packages, for each individual package please go
to Options->Linker and Select/Set Generate all C++Builder Files.

© 2016 FMSoft Co. Ltd.


Installation 13

If you are installing the Plus Edition you will see three additional files related to Mobile development
in project group:

10) After building all packages install design time packages by right-clicking and selecting Install in
following order:

· SynEdit_D20xx.bpl
· uniGUIxxdcl.bpl
· uniGUIxxChartdcl.bpl
· uniGUIxxmdcl.bpl (Plus/Complete Editions only)

Several new components will be installed:

© 2016 FMSoft Co. Ltd.


14 uniGUI Developer Manual

Com plete Edition only

**Additional notes for C++ Builder:

· After starting a new C++ project you must disable Linker->Dynamic RTL.
· Currently building with Run Time Packages doesn't work properly. You must statically link all
libs and create a single EXE. (Simply unselect Build with runtime packages option.)
· New C++ projects are created without a resource (.RES) file. As a result project has no default
Icon. This issue will be fixed in next releases.
· Combo VCL/ISAPI projects are not supported for C++ Builder.

2.3 Sencha Touch Installation


Note: This step is only required for uniGUI Plus Edition. For other editions you can sk ip this step.

Current version of commercial uniGUI Plus with Sencha Touch support, does not distribute Sencha
Touch files. ( uniGUI Complete is the edition which deploys Sencha Touch.)

You must download it from Sencha Touch web site.

Here are the instructions:

Please download Sencha Touch from here. What you need from package is the folder named
touch-2.4.2 which will be extracted under touch-2.4.2-commercial folder.

You must copy touch-2.4.2 folder to same folder your Sencha Ext JS folder resides.

For example if your folder structure looks like:

..\uniGUI\Dcu
..\uniGUI\Demos
..\uniGUI\ext-4.2.2.1144

You must copy touch-2.4.2 folder to ..\uniGUI.

So after copying it should look like below:

..\uniGUI\Dcu

© 2016 FMSoft Co. Ltd.


Installation 15

..\uniGUI\Demos
..\uniGUI\ext-4.2.2.1144
..\uniGUI\touch-2.4.2

2.4 Running Demos


Demos are a good place to start and become familiar with framework's basics quickly.
Fortunately uniGUI comes with plenty of example projects which can fully demonstrate all aspects of
uniGUI including all standard and advanced features. Almost all of uniGUI demos are compatible with
all supported versions of Delphi. A few demos may not compile on earlier versions of Delphi because
of language incompatibilities and lack of new features introduced in newer versions of Delphi.
Running demos is a very simple task and quite identical to run any VCL application except uniGUI
application will run inside a browser.

In order to run a demo in Delphi IDE go to File->Open and point location to where uniGUI demos are
located. Normally under <install folder>\FMSoft\Framework \uniGUI\Demos\...

Select demo folder named AllFeaturesDemo and open mdemo.dpr.

In IDE select Project->Build mdemo and build the project. After a successful build press Run and

you will notice a new icon will appear in tray

At this stage a firewall warning may appear in desktop asking for permission to allow uniGUI
application to listen its dedicated port. Please grant required permission to firewall.

© 2016 FMSoft Co. Ltd.


16 uniGUI Developer Manual

Now in order to run a web session please open one of compatible browsers such as FireFox,
Chrome, IE9+, Safari or Opera.

In Browser address bar type below address:

http://localhost:8077

uniGUI application running

You can terminate running application server bu right-clicking on tray icon and selecting shutdown
from pop-up menu.

If your uniGUI edition contains support for mobile application you can run demos you can follow
same principles to run mobile application demo.

This time please select and open mdemo.dpr from ..\Touch\AllFeatures folder.

© 2016 FMSoft Co. Ltd.


Installation 17

You can open Mainm.pas in IDE to see how mobile designer looks in IDE. It looks a bit different than
standard Form designer and modified to reflect look and feel of a mobile device.

uniGUI Mobile w eb application in IDE

Now you can run application server by building project and running it.

Again a new tray icon will appear.

You can test or debug a mobile web session in an ordinary desktop browser or directly run it on a
mobile device. On desktop you need a fully HTML5 compatible browser. Fortunately all modern
browsers come with extensive support for HTML5.

In Browser address bar type below address:

© 2016 FMSoft Co. Ltd.


18 uniGUI Developer Manual

http://localhost:8077

You will notice that address will be automatically redirected to a new address:

http://localhost:8077/m

uniGUI m obile app in Google Chrom e brow ser

You can also run on a mobile device by simply opening a browser window and type a proper
address. This time you need to enter IP address of PC which is running demos and also make sure
your mobile device and PC are connected to same LAN.

© 2016 FMSoft Co. Ltd.


Installation 19

uniGUI w eb application running on a sm artphone

© 2016 FMSoft Co. Ltd.


20 uniGUI Developer Manual

3 Technology Overview
Developing a Rich Internet Application (RIA) is one of the challenging fields in software
development. Tasks such as handling user sessions, tracking view state, updating web controls,
handling AJAX calls and etc. can be very challenging if your development tool doesn't automatically
handle all of these for you. uniGUI Web application framework makes developing stateful Web
applications easier than ever. uniGUI extends Web Application development experience to a new
dimension. Each uniGUI application can be considered both as a standard Delphi VCL application
which uses web as its presentation layer. uniGUI enables developers to create, design and debug
their Delphi applications as if they are developing regular desktop applications and then choose one
of the available options for web deployment. uniGUI itself is not a single library. For Web front-end
uniGUI relies on well known Sencha Ext JS JavaScript library. Thanks to Ext JS for enabling uniGUI
to provide a high end, visually perfect and fully AJAX enabled web front-end.

uniGUI uses same Form oriented application model available in a typical VCL application.
This means your application will be consisted of many forms which all belong to same session. This
will enable developers to follow same principles and design patterns they were following in designing
standard desktop application. This will highly reduces learning curve which can be very steep for
other web application frameworks. Especially for those which need developers' direct interaction with
UI design details, CSS code, HTML code, XML templates and JavaScript code. This means that a
Delphi developer with little web knowledge can start developing web application using uniGUI out of
the box. While uniGUI enables developers to develop web applications with little knowledge for web
technologies, it is always recommended for developers to fully become familiar web underlying web
technologies which are used in general in the web and used in particular in uniGUI, such Ext JS
framework. Becoming familiar with Ext JS framework will open door to a new world which developers
can customize their web application in a war which wouldn't be possible otherwise. uniGUI allows
developers to directly write JavaScript client side event handlers for Ext JS controls. This advanced
feature allows developers to directly allow interaction between client side screen elements without a
need to communicate with the server.

In general each uniGUI application is a standard Delphi executable powered with


specialized modules which all together turn the application into a full featured web server. Among
these modules we can count Session Manager, Web HTTP Server, ISAPI Handler, Cache Eraser
and Server Module. These modules cooperate to create sessions, handle Ajax calls, create web UI
and manage session lifetime. All these actions happens completely transparent to developers.

© 2016 FMSoft Co. Ltd.


Technology Overview 21

3.1 Unified GUI


uniGUI stands for Unified Graphical User Interface or Unified GUI in short. It is called
unified because it allows same UI experience in all devices with a web browser. Regardless of
device, OS, CPU and display same level of user experience can be achieved on all devices with a
compatible web browser. It allows a great freedom in choosing client devices. Client device can be
anything from a Windows PC, OSX device to a PC with any flavor of Linux or even a Raspberry Pi!

Of course, this feature is not something unique to uniGUI. This level of independency from
platform is something that any web application can provide except that uniGUI enables you to create
web applications which are very close to desktop applications in look and feel.

© 2016 FMSoft Co. Ltd.


22 uniGUI Developer Manual

3.2 Web Sessions


Web Sessions are main elements of a uniGUI web application. Each time a user opens a
new instance of web application a new session on server is created. Each session will remain active
in server until user terminates it or a timeout condition occurs. Each session keeps a complete state
of running web application. That's why uniGUI sessions are called stateful. You can consider each
session as a private copy of your web application which co-exists with other sessions in server's
address space. Each session is isolated from other sessions and each web request is automatically
redirected to its respected session. Each session has a unique "Session Id" which is used to
distinguish it from other sessions. Session Id is assigned upon creation of session and included in
each Ajax request, so request can be directed to correct session.

Below diagram represents internal structure of a uniGUI server. Each uniGUI server has a
single copy of ServerModule which is created once per server, along with multiple sessions which are
dynamically created and destroyed according to user activity. A uniGUI session contains a
specialized DataModule called MainModule which is automatically created for each session. Also a
Form named MainForm is created which apparently is main entry point of web application. MainForm
can be preceded with a LoginForm which provide a reliable and secure way for user login. As
expected each session can contain several additional DataModules and Forms.

© 2016 FMSoft Co. Ltd.


Technology Overview 23

3.3 Deployment Options


uniGUI supports all major deployment options available for Windows platform.

1.Standalone Server
Basic method of deployment is Standalone Server. In this mode application server runs
directly like a desktop application. It is also the mode used for debugging application. After running
application executable it will minimize itself to tray icon and will run until manually terminated by
user. See below pic:

uniGUI Standalone Server

A standalone application can be accessed from browser by simply typing:

http://localhost:8077

Where 8077 is dedicated port number which your application is bound. It can easily be modified from
ServerModule.

Standalone mode is only recommended for debugging purpose. Since it runs as a desktop
application it will be terminated as soon as current user is logged off. It also will not start
automatically after a restart. This mode is best for debugging purpose. When your app runs in debug
mode you can set breakpoints, pause, go to cursor and use all other advanced debugging features of
Delphi IDE to debug your application just like any other VCL application. Apparently, this method is
not recommended for production environment, as it doesn't automatically run when OS restarts. Also
it can be easily terminated by an unauthorized user intervention.

2. Windows Service
Another deployment method is Windows Service. By creating a uniGUI Windows Service
application you can deploy your application as a standard Windows Service application. This method
is one of the preferred method for use in a production environment. Windows Services are integrated
part of OS and they run automatically each time system restarts. This will guarantee required
availability expected from a web application. A Windows Service application can be accessed from a
browser with same method as Standalone server described above. Which means each Windows
Service application requires a dedicated port.

3. ISAPI Module
Last available deployment option is ISAPI Module. This method is introduced in Microsoft IIS
server. It is available from early versions of IIS and it is based on Windows DLL technology.There are
other web servers such Apache which also support loading ISAPI modules. ISAPI modules differs
from other two options which discussed above in many aspects. First of all it doesn't contain with a
built-in web server as opposed to Standalone Service and Windows Service which both embed a web
server to serve incoming HTTP requests. In ISAPI mode IIS server is the HTTP server and ISAPI
module performs as an application only. You can easily create ISAPI module application using
uniGUI Wizards in Delphi IDE. Compiling an ISAPI uniGUI application will output a DLL file instead of
an EXE file.This DLL file must be deployed to IIS server which is described in detail in section ISAPI
Module under Web Deployment section. uniGUI DDLs support all IIS versions starting from IIS 5.1
and above. ISAPI modules gives developer the freedom of deploying many modules in same server
without a need to choose a different port for each application. It also take benefits from all advanced
security features available in Microsoft IIS.

© 2016 FMSoft Co. Ltd.


24 uniGUI Developer Manual

Running an ISAPI application is as easy as calling below Url in your browser:

http://localhost/appdir/app.dll

if you have multiple apps under same folder you can call them by simply specifying a different DLL
name:

http://localhost/appdir/app.dll
http://localhost/appdir/app2.dll
http://localhost/appdir/appaccount.dll

© 2016 FMSoft Co. Ltd.


Technology Overview 25

3.4 Forms and Modules


Unlike a VCL application which can contain only a single form, a uniGUI application is
created with a specialized form named MainForm and two data modules MainModule and
ServerModule. Other form type which has a special meaning in uniGUI is LoginForm.

3.4.1 Application MainForm


Application Main Form or MainForm is the first displayed form when a web session starts.
In general MainForm is first form of your application which is used to navigate to other forms using
menus or other navigation tools. MainForm is automatically created when a new project is created.
Each web session has its own private copy of MainForm and closing a MainForm will terminate the
session.

A blank MainForm

MainForm is registered in initialization section of unit so uniGUI can distinguish it from other
forms.

initialization
RegisterAppFormClass(TMainForm);

end.

© 2016 FMSoft Co. Ltd.


26 uniGUI Developer Manual

3.4.2 LoginForm
LoginForm is another special Form type which is solely used for login purpose. If your
application contains a LoginForm it will the first form displayed when a web session starts. A
LoginForm can be created from uniGUI Wizard by following this path: File->New->Other->Delphi
Projects->uniGUI for Delphi->Form.

uniGUI Wizard

Create a Login Form

This action will create a blank LoginForm which looks identical to a regular form:

© 2016 FMSoft Co. Ltd.


Technology Overview 27

A blank LoginForm

Sam ple LoginForm design

A LoginForm is a descendant of a built-in class named TUniLoginForm. Each application


can only has one LoginForm. After adding LoginForm your application will show this form as default
form when a new session starts. You need to add controls, event handlers and etc. to implement
required functionality. Login behavior is controlled using Form's ModalResult. If LognForm returns
mrOK it means a successful login which will proceed to MainForm. When ModalResult returns
mrCancel it will terminate application. So what you need to do is to validate user input and once
there is a valid combination of user name and password you must return mrOK as ModalResult.

procedure TUniLoginForm1.UniButton1Click(Sender: TObject);


begin
ModalResult := mrOK; // Login is valid so proceed to MainForm
end;

procedure TUniLoginForm1.UniButton2Click(Sender: TObject);


begin
ModalResult := mrCancel; // Invalid Login exit from app
end;

Once user is logged in and MainForm is displayed, there are two ways to terminate the session. You
can terminate the session and return to LoginForm by returning mrOK as ModalResult or terminate
the session by returning mrCancel. For security reasons existing session is always terminated
before displaying the LoginForm. i.e. each new login.starts a new session by default.

© 2016 FMSoft Co. Ltd.


28 uniGUI Developer Manual

3.4.3 MainModule

Application MainModule

MainModule can be considered as heart of each session. It is a special purpose DataModule


which is automatically created and added to project each time a new project is created. MainModule
has a many important roles in a uniGUI application. Some of these roles are not visible to the
developers. For developers MainModule can be a used a central module to place session's shared
resources, such as database connections, shared variables and etc. For example, you can declare
public variables in MainModule's public section and then access it from other forms in session.
Below example demonstrates a common practice in uniGUI to share data among various forms in a
session. Since each session has its private copy of MainModule it will be ensured that each form will
access its private set of data in its session.

TUniMainModule = class(TUniGUIMainModule)
private
{ Private declarations }
public
{ Public declarations }
aUserName, aPassword: string;
end;

Later you can access these variables from other forms in application:

procedure TMainForm.UniButton1Click(Sender: TObject);


begin
UniLabel1.Caption := UniMainModule.aUserName + ' ' + UniMainModule.aPassword;
end;

Also see Web Sessions.

3.4.4 ServerModule

uniGUI ServerModule

© 2016 FMSoft Co. Ltd.


Technology Overview 29

Each uniGUI application contains a special data module named ServerModule which is the
core module of the application. It is a singleton, which means it is created only once per application.
It is mainly used to configure various server settings. ServerModule will be covered in more details in
other sections.

3.4.5 ServiceModule
A ServiceModule is only created when project type is Windows Service. It a descendant of
Delphi's standard TService class. It allows to configure Windows Service related parameters
including service name, service type and etc.

3.4.6 DataModules
uniGUI supports adding DataModules to project. This will allow developers to design their
app like a standard VCL application divide application business logic among several DataModules.
The important thing to remember is that while uniGUI DataModules are identical to standard VCL
DataModules in nature, they must be created using uniGUI wizard to ensure each session will have
its own private copy of that DataModule. If DataModule is created using standard IDE wizard that
module will not be compatible with uniGUI session management system so it should be avoided.

Using uniGUI w izard to create a new DataModule

© 2016 FMSoft Co. Ltd.


30 uniGUI Developer Manual

3.4.7 Frames
uniGUI has complete support for frames. Frames must be created using uniGUI IDE wizard.

Using uniGUI w izard to create a new Fram e

An em pty uniGUI Fram e

© 2016 FMSoft Co. Ltd.


Technology Overview 31

3.5 Special Objects


3.5.1 UniApplication Object
UniApplication returns an instance of TUniGUIApplication for current session. For each
session UniApplication's main role is to be owner for MainForm, MainModule and all other forms and
DataModules which belong to current session. It is globally available and can be accessed inside
uniGUI control event handlers. UniApplication has several useful properties which can be used to
obtain various information regarding the associated session. For example, url parameters, client
screen width, client screen height, device type, information related client PC and cookies.

For each session an instance of UniApplication is created and all forms and data modules in
projects will be owned by this instance UniApplication. When a form is created in code its owner
must be set as UniApplication too.

procedure TMainForm.UniButton2Click(Sender: TObject);


begin
with TUniForm2.Create(UniApplication) do
ShowModal();
end;

UniApplication itself is actually a function which returns the correct instance of TUniGUIApplication
for current session:

unit uniGUIApplication;

interface

function UniSession: TUniGUISession;


function UniApplication: TUniGUIApplication;
...

For this reason UniApplication should only be accessed inside an event handler which is fired from a
uniGUI control.

procedure TMainmForm.UnimButton1Click(Sender: TObject);


begin
if upAndroid in UniApplication.UniPlatform then
ShowMessage('This is an Android device!');
end;

© 2016 FMSoft Co. Ltd.


32 uniGUI Developer Manual

3.5.2 UniSession Object


UniSession returns an instance of TUniGUISession class for current session. It contains all
information related to a session. Among these there are important information such as IP Address,
User Agent, Host Address, Platform related data and etc. UniSession also contains important
methods which can be used to control a session. For example you can call Terminate method to
terminate a session:

procedure TMainForm.UniButton2Click(Sender: TObject);


begin
UniSession.Terminate; // Terminate current session

end;

procedure TMainForm.UniButton2Click(Sender: TObject);


begin
UniSession.UrlRedirect('http://www.newsite.com'); // Redirect current window to a new locati

end;

Like UniApplication, UniSession object has a valid instance only when accessed from a uniGUI
control event handler. Here we are referring to controls which belong to a session. For example, a
TUniButton instance always belongs to a session.

procedure TMainForm.UniButton2Click(Sender: TObject);


var
IPAddress : string;
begin
IPAddress := UniSession.RemoteIP; // We are in an event handler from a TUniButton, so UniSes

end;

In below example accessing UniSession object will cause an access violation because
UniThreadTimer is not an uniGUI control and its events are not associated with any session.
UniThreadTimer events run asynchronously in a separate thread.

procedure TMainForm.UniThreadTimer1Timer(Sender: TObject);


var
IPAddress : string;
begin
IPAddress := UniSession.RemoteIP; // this will cause an access violation error because there

end;

It can be confusing that how UniSession can be a global object and still hold different values when
accessed from different sessions. The answer is that just like UniApplication, UniSession is actually
a global function declared in uniGUIApplication.pas. This function returns correct session instance
when called inside an event handler.

unit uniGUIApplication;

interface

function UniSession: TUniGUISession;


function UniApplication: TUniGUIApplication;
...

© 2016 FMSoft Co. Ltd.


Technology Overview 33

3.5.3 UniServerInstance Object


UniServerInstance is a global function defined in uniGUIServer.pas and returns the global
instance of ServerModule object which is a singleton. There are some reasons that we have used a
function instead of a variable here. One reason is to make sure that UniServerInstance is accessed
as read only.

unit uniGUIServer;

interface

function UniServerInstance: TUniGUIServerModule;


...

4 Developer's Guide
4.1 Creating a New uniGUI Application
Creating a new uniGUI project is quite easy. All needed is to point Delphi IDE to uniGUI
Application Wizard.

Select File->New ->Other

© 2016 FMSoft Co. Ltd.


34 uniGUI Developer Manual

Select uniGUI for Delphi -> Application Wizard

Select a Project Type

© 2016 FMSoft Co. Ltd.


Developer's Guide 35

4.1.1 Standalone Server Project


A Standalone Server project is the most simple type of a uniGUI project. It creates an
application which runs similar to a desktop application. i.e.application is started and terminated by
user. This type of application is best for debugging purpose. Below is the sample DPR file for a
typical newly created Standalone Server project. Also see Deployment Options.

program Project1;

uses
Forms,
ServerModule in 'ServerModule.pas' {UniServerModule: TUniGUIServerModule},
MainModule in 'MainModule.pas' {UniMainModule: TUniGUIMainModule},
Main in 'Main.pas' {MainForm: TUniForm};

{$R *.res}

begin
Application.Initialize;
TUniServerModule.Create(Application);
Application.Run;
end.

4.1.2 Standalone Server / ISAPI Module Project


This type of project is a combo project which has a dual type. It can both be a Standalone
server and an ISAPI Module. This type of project is very good to start with if ISAPI Module
deployment will be targeted for use production. You will be able to convert your Standalone server to
an ISAPI DLL by simply commenting out the first line of DPR file. Also see Deployment Options.

© 2016 FMSoft Co. Ltd.


36 uniGUI Developer Manual

{$define UNIGUI_VCL} // Comment out this line to turn this project into an ISAPI module'

{$ifndef UNIGUI_VCL}
library
{$else}
program
{$endif}
Project1;

uses
uniGUIISAPI,
Forms,
ServerModule in 'ServerModule.pas' {UniServerModule: TUniGUIServerModule},
MainModule in 'MainModule.pas' {UniMainModule: TUniGUIMainModule},
Main in 'Main.pas' {MainForm: TUniForm};

{$R *.res}

{$ifndef UNIGUI_VCL}
exports
GetExtensionVersion,
HttpExtensionProc,
TerminateExtension;
{$endif}

begin
{$ifdef UNIGUI_VCL}
Application.Initialize;
TUniServerModule.Create(Application);
Application.Run;
{$endif}
end.

By default above project will produce an EXE file which is an Standalone server. If you change the
first line of project it will turn into an ISAPI module. Later you can convert it back to Standalone EXE
mode by removing the comment from first line. Here is how it works.

Steps to convert a combo project to an ISAPI DLL:

1. Open DPR file.


2. Change first line of DPR file to: {.$define UNIGUI_VCL}
3. If your Delphi edition is XE2 or newer then you need to close your project and open it again. (This
step is not needed if your Delphi version is older than XE2)
4. Build your application.
5. DLL file will be created in related folder.

Steps to convert a combo project back to Standalone mode:

1. Open DPR file.


2. Change first line of DPR file to: {$define UNIGUI_VCL}
3. If your Delphi edition is XE2 or newer then you need to close your project and open it again. (This
step is not needed if your Delphi version is older than XE2)
4. Build your application.
5. Your project will be compiled to EXE file again.

© 2016 FMSoft Co. Ltd.


Developer's Guide 37

4.1.3 ISAPI Module Project


If you plan to start an ISAPI Module project and choose it as the default deployment method
you can select this type of project. It is apparent from the DPR file that this project will produce a
DLL when it is compiled: For deployment options plesee see ISAPI Module section. ISAPI modules
can be deployed to Microsoft® IIS server or Apache server for Windows. Also see Deployment
Options.

library Project1;

uses
uniGUIISAPI,
ServerModule in 'ServerModule.pas' {UniServerModule: TUniGUIServerModule};

{$R *.res}

exports
GetExtensionVersion,
HttpExtensionProc,
TerminateExtension;

end.

4.1.4 Windows Service Project


Another deployment method for production environment is Windows Service. It creates a
standard Delphi Windows Service project with few modifications to allow creation of a uniGUI
ServiceModule. Service projects allows creation of standard Windows Service executables which can
be installed like any regular Windows Service. A Windows Service is automatically started by OS
and it is always available as long as server OS is running. This provides a high level of availability for
uniGUI application. Also see Deployment Options.

program Project1;

uses
SvcMgr,
ServerModule in 'ServerModule.pas' {UniServerModule: TUniGUIServerModule},
MainModule in 'MainModule.pas' {UniMainModule: TUniGUIMainModule},
Main in 'Main.pas' {MainForm: TUniForm},
ServiceModule in 'ServiceModule.pas' {UniServiceModule: TUniGUIService};

{$R *.res}

begin

if not Application.DelayInitialize or Application.Installing then


Application.Initialize;
Application.CreateForm(TUniServiceModule, UniServiceModule);
Application.Run;
end.

© 2016 FMSoft Co. Ltd.


38 uniGUI Developer Manual

4.2 Application Design Considerations


There are certain aspects which make a uniGUI web application different from a desktop
application. A desktop applications is designed to run as a single instance on desktop and it is able
to use all system resources available to it. Most of the time this will result in poor application design,
as developers don't see a need to optimize resource usage. With advancement of computer
technology new systems are equipped with more resources with each new model. 10 years ago PCs
with 128mb of RAM where considered as entry level while today this limit is upgraded to at least 2
GB of memory. This may lead developers to adopt wrong practices when designing applications
which overuse of system resources. Unlike a desktop application where a single user session runs
inside a single process, a web application is where several user sessions run in same process
instance. In this case resource management can be a vital task which should be taken seriously.

Another important difference is shared resources. Again in a desktop application all


resources are dedicated to same user session while in a uniGUI web application resources are
shared among several user sessions. Any mismanagement in resources may affect web application
server's health which may lead to server instability. One example for resource mismanagement is
memory leaks. In a desktop app memory leaks can be a serious issue if desktop app runs for a very
long period of time. SInce desktop apps are mainly used for a few hours per day, mainly working
hours, such memory leaks will not lead to serious issues. However, in a web application memory
leaks can seriously affect server stability in a short period time.

Web application servers are intended to work in a 24/7 manner, so any resource
management related issue can build-up over time and cause server to run out of resources. Such
conditions can lead to applictaion server instability and eventually to server crash. When discussing
shared resources it is good to mention memory corruption problems. Again, in a desktop application
memory corruption issues can remain undetected for a long time because such corruptions may not
produce dangerous side-effects, but in a web application memory is allocated and disposed at a very
high rate in multiple threads, so any sort of memory corruption can lead to serious server instability
and erratic application behavior.

Finally, a uniGUI web application is a heavily multi-threaded environment where multiple


sessions can be executed in simultaneous threads. As a result, components used in uniGUI must
be fully multi-thread proof. Components which are not compatible with mult-threaded environment will
cause serious issues which again will lead to instability of web server.

4.2.1 General Design Concept


Each uniGUI application is created with a MainForm, a MainModule and a ServerModule. As
described before MainModule and MainForm are created in a per session basis while ServerModule
is a singleton. Additional to MainModule you can add extra DataModules to your application. A
LoginForm can also be added if needed.

MainModule is automatically created with your application and internally it performs many
important tasks. MainModule is best place to place shared resources for a session. Here by saying
shared resources we refer to resources which are shared among a session's forms and
DataModules. A database connection is a good example for shared resources. We can consider
each session as a separate copy of web application, so like a regular application you need a
separate database connection for each application instance. In uniGUI this can be achieved by
placing the connection component on DataModule, so a connection will be created when a new

© 2016 FMSoft Co. Ltd.


Developer's Guide 39

session is started and destroyed when session is terminated. This will guarantee that each session
will use its private copy of database connection.

Another example for shared resources can be shared data structures. For instance, each
session may need to keep a shared record which holds information about current user. All other
forms and DataModules in application should be able to access this structure when needed.
Consider below data structure defined in unit MainModule.pas:

type
TUserInfo = record
Name, Surname : string;
UserId : Integer;
end;

Above structure needs to be accessible from other forms in current session, so we must define it as
a public property in TUniMainModule:

TUniMainModule = class(TUniGUIMainModule)
private
{ Private declarations }
FUserInfo: TUserInfo;
public
{ Public declarations }
property UserInfo: TUserInfo read FUserInfo;
end;

Above structure will be populated with real user data when user logs in. MainForm can access
UserInfo as following:

procedure TMainForm.UniFormCreate(Sender: TObject);


begin
UniLabel1.Caption := UniMainModule.UserInfo.Name + ' ' + UniMainModule.UserInfo.Surname;
end;

You can see that it can be easily done by accessing UserInfo property of UniMainModule object.
Since each session has its private copy of UniMainModule each form in session will access
correct instance of UserInfo record.

At this point it is good to remind that one should avoid using shared global objects in uniGUI.

For example, one could define TUserInfo as a global variable in MainModule:

unit MainModule;

interface
...
var
UserInfo: TUserInfo;

And access it in MainForm:

procedure TMainForm.UniFormCreate(Sender: TObject);


begin
UniLabel1.Caption := UserInfo.Name + ' ' + UserInfo.Surname;
end;

© 2016 FMSoft Co. Ltd.


40 uniGUI Developer Manual

Above code actually works during initial tests because as long as there is only one active session
UserInfo will not be shared and application seems to behave correctly! However, as soon as multiple
sessions logs in application starts to behave in a strange way.

Such design flaws may remain undetected where few sessions are active at a time, but with an
increased load side effects of intial design flaw will become more visible while it may not be easy to
spot the source of the problem. For this, it is very important to stick with a correct design pattern
from the beginning.

Likewise, putting components on ServerModule must be avoided. As described before, ServerModule


is a singleton and it will not be created for each session, so for example, putting a database
Connection component on ServerModule may work when there are few sessions, but with more
sessions you will get unexpected errors which are difficult to detect and debug.

Application ServerModule

© 2016 FMSoft Co. Ltd.


Developer's Guide 41

4.2.2 Web Application Scalability


When it comes to web application development, scalability is one of the most important
topics. Web applications are designed to server many users. While for some apps 10 simultaneous
users can be the maximum, for other application 100 can be the minimum. It is one of the major
differences between a desktop app and a web application. A desktop app is designed for one user
only but a web application is designed for multiple users. As number users grow scalability issues
may start to show. Many of such issues are related to flawed application design. A web application
is designed to serve multiple simultaneous sessions which means more system resource usage with
more sessions.

Consider that you are porting a desktop application to web application. In your desktop
application you have datasets and grids which load all available rows from a table. Now assume that
each time a new session starts thousands of rows are fetched from the table and populated in a
dbgrid. Consider that the dataset and grid may consume up to a few megabytes of memory each
time table is opened. It will pose no issue if it was a desktop application, as all system resources
could be dedicated to the desktop app. However, in web application each new session will consume
this amount of memory. In this case if you have 100 active sessions and each session consumes
10MB of ram, total consumed memory will be 100 x 10 = 1,000 MB = 1 GB.

As you can see memory consumption can easily become huge if your sessions are not
optimized for resource usage. This shows importance of resource optimization for applications where
scalability is important. There can be cases where scalability doesn't have the highest priority. For
example, if you develop a web application for s system with up to 10 users, scalability is not an
issue, but for a web application where 100 users is the minimum resource management should be
done in a way to make sure your application will never run out of resources.

Stress Test Tool can be a great assist in finding scalability issues. Running a stress test
can precisely show the maximum amount of memory that your server will consume when certain
number of sessions are running. It can be used to test your web application in a worst case scenario
and see if it can pass the test under such rare conditions. If your application can pass the stress
test it can be deployed to production environment.

uniGUI itself is optimized in many aspects to deal with resource optimization issue. To give
some examples, it stores bitmaps in cache files, creates forms when called and destroys them when
user closes them, keeps ImageLists in cache file and etc. Likewise, developers should consider
adopting a Create Resource on Demand principle to optimize resource usage. One good example
can be database tables and related datasets. In a classical Delphi approach a developer may place
the connection component and all related datasets on a DataModule, but in uniGUI it would cause
that all datasets be created each time a new session starts. This will pose even more problem if
datasets are Active by default.

In uniGUI correct approach is to place connection component on MainModule and place the
datasets on related forms or on a temporary DataModule. When you place a dataset on a form, it will
be created when form is shown and destroyed when form is closed. This approach will optimize
memory usage related to datasets.

4.2.2.1 Create Resource on Demand


This is an approach which must be followed when designing a scalable web application. The
general rule here is to create resource sensitive objects when they are needed not before and
destroy them when they are no longer needed.One example is database tables. As described in
previous section db tables can load many rows at once which can increase memory usage with

© 2016 FMSoft Co. Ltd.


42 uniGUI Developer Manual

increased number of rows. It is true especially with memory datasets. Delphi's built-in
TClientDataset is an example for memory datasets. In order to make sure dataset is created and
loaded with data when it is needed, it is good to place the dataset on a form or frame where db-aware
controls exist. Each time user needs to visit that form, form is created and shown along with tables
and db aware controls. When user closes form dataset will be freed and used memory is sent back
to application memory pool.

Same method can be applied to reporting tools. Instead of putting report component on
MainModule it can be created just before generation of report and destroyed right after report is
generated and saved in a temporary file.

4.2.2.2 Database Connections


Connections to a database is another resource which should be taken into consideration
when it comes to application scalability. As recommended, for each session a connection object
should be placed on MainModule. A new instance of connection object will be created when a new
session is initiated, so in a typical scenario each session will establish a new connection to the
database server. Th,s can pose an issue with scalability if database server can only serve limited
number of simultaneous connection. It is the case with many database servers. Some of them have
a default limit of a few hundred while some other can handle thousands of connections or more.
Again, database connection must be treated as limited resources and your app should not reach the
upper limit.

You can configure your server to serve a higher number of simultaneous connections, but it
is not to the correct way of dealing with this problem. There are ways to deal with this issue:

1. Enabling Connection Pooling. Connection pooling is a method to re-use database


connections with same properties. Some database libraries implement pooling by default while
others don't implement this feature. You must check your particular connection library to see if
pooling feature is available or not. For example, TADOConnection component combined with
Microsoft SQL Server enables pooling by default.

2. Using a Middleware Library. When number of concurrent sessions are bigger than
upper limit of your database server, one way to overcome this issue is to use a middleware layer.
This is one of the purposes of middleware layers to manage database connections in most possible
efficient way. A middleware creates a connection when it is needed and frees it when it is no longer
used, making it possible to serve many sessions with few number of simultaneous connections.
Some middleware libraries internally implements connection pooling which improves performance.
Among commonly used middleware libraries in Delphi we can count DataSnap, DataAbstract and
kbmMW.

4.2.3 Third party Component Libraries


There are few applications which may not rely on third party component libraries. Third party
libraries help to create feature rich application with expanded functionality. In some cases using a
third party is mandatory. For instance, a database engine may need a special set of components to
perform connection and making queries. Reporting is another area where 3rd part tool come to mind.
When it comes to uniGUI application 3rd party tool compatibility becomes an important issue. As we
decribed in previous sections, stability of web application depends on all elements which consist the
application. A buggy, poorly developed or incompatible 3rd party library can lead to server instability.

There some important points that must be taken into consideration when choosing for a
uniGUI application:

© 2016 FMSoft Co. Ltd.


Developer's Guide 43

Compatibility: As described in many place throughout this document, a uniGUI server is a


heavily multi-threaded environment. This means that any tool used along with uniGUI must be thread-
safe. i.e. several instance of component must be capable of running in several threads in parallel. If a
component relies on global variables it is very likely to fail in a web application. Likewise, if a
component relies on embedded VCL controls then it is likely to affect server stability in a harmful
way. VCL controls and not thread-safe and it is explicitly stated since early documents related to
VCL. Unfortunately, some reporting tools are designed to rely on VCL controls to generate report
output.

Some 3rd party tools rely on window handles (HWND) and message loops to function. This
is another point which can cause serious problems in uniGUI. uniGUI doesn't have a main thread and
it doesn't implement a message loop. Although Standalone Server borrows a main thread from
Delphi's VCL, a main thread is not available in an ISAPI dll. So any 3rd party relying on sending
messages is likely to fail in an ISAPI module. You may experience that some apps work properly in
Standalone Mode and works differently when deployed as an ISAPI module. It happens because In
Standalone mode uniGUI server implements a VCL Form which is minimized to tray. As a result
Application.Run() is called to keep server running until user terminates it. This will create a
message loop which allows some incompatible components work to some level. However, in an
ISAPI module no VCL form is created and Application.Run() is not called, so any attempt to call
SendMessage() will fail to return a result because there is no message loop to process the
messages.

In order to give a specific example, TRichEdit is a VCL control which is a Memo with styled
text. Some reporting tools use it to generate blocks of text with various styles. Like other VCL
controls in internally uses SendMessage() to communicate with its Handle (HWND). As described
above this will fail and RichEdit fails to render. You may experience that a report containing RichEdit
renders correctly when application is deployed in Standalone mode, but doesn't render anything
when same app is deployed as Windows Service or ISAPI module.

As last example, 3rd party component should not use global variables. They must follow
same rules that are applied to uniGUI applications. Each instance of component must have its own
private set of variables to work with and should not rely on global variables or data modules which are
not protected.

Some third party components need to be configured properly to run in a threaded


environment. You must check specific section of related manual for the instructions.

Stability: Any 3rd party component which have stability issues will affect stability of uniGUI
application. Component library must be free of bugs and tested against memory leaks.Vendor must
ensure that it can be used in a multi-threaded environment without any issues.

Scalability: 3rd party Components used in uniGUI must be scalable. There should be no
upper limit for number of simultaneous instances of component that may co-exist unless limited by
system resources. If there are such limits, developer must be aware of them and design application
accordingly.

© 2016 FMSoft Co. Ltd.


44 uniGUI Developer Manual

4.2.3.1 Reporting Tools


There are some special guidelines for reporting tools to make sure they run in a compatible
mode with uniGUI. Some reporting tools have special settings for multi-threaded applications. In
many cases you need to disable visual dialogs and other VCL related forms from being displayed
while report engine is running. Since in uniGUI you can not display VCL forms, in order to show a
report it must be converted to a file first. A commonly used format is PDF format which can be
embedded in a browser window or an iframe.

In uniGUI the recommended method to create a report is converting report to a PDF file and
displaying it inside a TUniUrlFrame control. For each reporting tool there are different paths to
achieve this. Under this topic we will shortly cover a few reporting tools. You can also load and run
the related demos to see how it is actually done.

Important: As described in previous section, there are some common issues in reporting
tools that may affect uniGUI application stability and scalability. Initial versions of reporting tools
mainly were created for desktop applications only. In time they evolved and started to support server
applications too, however they may still contain components or code parts which are not compatible
with multi-threaded server application For rendering some controls report generator may rely on VCL
controls to render the object on a canvas which later will generate the PDF output.

Some of the used VCL controls such as TRichEdit uses Windows handles and messaging
system to initialize itself. Since VCL controls are not thread-safe and uniGUI application doesn't
implement a message loop, this initialization will fail and RichEdit control will not render anything on
the report canvas. You will notice that RichEdit text object is missing in the PDF output. Again, this
may work in Standalone Server mode, but again it will not scale when many users try to generate
same report. Another issue can be that reporting tool may internally rely on unprotected global
variables. Using global variables is prohibited in uniGUI, so again it may cause stability issues.

In order to fully test compatibility of reporting tool with your application it is required to run a
Stress Test and fully analyze your application behavior with reporting tool. It is important to make
sure both your particular reporting tool and particular report design both can scale up when server is
under load.

4.2.3.1.1 FastReport

FastReport is a widely used reporting tool for Delphi. In order to use FastReport in a uniGUI
application there are certain rules to follow. FastReport engine must be adjusted so it can cope with
uniGUI multi-threaded environment.

First of all, report engine parameters must be adjusted. In below example Report is a TfrxReport
object.

Report.EngineOptions.SilentMode := True; // no dialogs


Report.EngineOptions.EnableThreadSafe := True; // Thread safety
Report.EngineOptions.DestroyForms := False; // Needed for correct operation
Report.EngineOptions.UseGlobalDataSetList := False; // Do not keep a global list of a datase

Next step is to adjust report related settings:

Report.PrintOptions.ShowDialog := False; // do not show any VCL dialog


Report.ShowProgress := false; // do not show report progress
Report.PreviewOptions.AllowEdit := False;

© 2016 FMSoft Co. Ltd.


Developer's Guide 45

In order to export file you need to use an export component. For PDF files TfrxPDFExport
component is used. Here are the related settings:

Exp.Background := True; // export in background


Exp.ShowProgress := False; // no progress window
Exp.ShowDialog := False; // no dialogs
Exp.FileName := UniServerModule.NewCacheFileUrl(False, 'pdf', '', '', AUrl); // Assign a u
Exp.DefaultPath := '';

After all settings are done last step is to generate the report:

Report.PrepareReport;
Report.Export(Exp);

Finally, we need to show the report in uniGUI. The preferred method here is to display it inside a
UrlFrame:

UniURLFrame1.URL := AUrl;

Another method can be sending the report to user by sending it using .UniSession.SendFile
method.

UniSession.SendFile(Exp.FileName);

4.2.3.1.2 ReportBuilder

ReportBuilder is another widely used reporting tool in Delphi. Again here we generate a PDF output
of report and direct it to a TUniUrlFrame .

lPDFDevice := TppPDFDevice.Create(nil);
try
lPDFDevice.PDFSettings := ppReport1.PDFSettings;
lPDFDevice.FileName := UniServerModule.NewCacheFileUrl(False, 'pdf', '', '', AUrl);
lPDFDevice.Publisher := ppReport1.Publisher;

// generate the report

ppReport1.PrintToDevices;
UniURLFrame1.URL := AUrl;

finally
lPDFDevice.Free;
end;

Above example demonstrates generation of a PDF output. Full demo is available under ..
\demos\Report Builder folder.

© 2016 FMSoft Co. Ltd.


46 uniGUI Developer Manual

4.2.3.1.3 Using a Report Server

In some cases where stability and scalability concerns have highest priority, it is wise to use
a separate report server. In many cases your reporting tool already provides a server solution which
runs in its own service. Your uniGUI application can generate reports by sending proper requests to
the report server. Generated report will be displayed in a TUniUrlFrame as normal.

4.2.4 Creating Controls at Runtime


Enter topic text here.

4.2.5 Object Lifetime Management


Enter topic text here.

4.3 Client-side Scripting


One of the advanced features of uniGUI is the ability to write JavaScript handlers for client
side events. i.e. it allows adding JS code for Ext JS events for uniGUI controls. Each uniGUI control

© 2016 FMSoft Co. Ltd.


Developer's Guide 47

4.4 Web Deployment


Currently there are four options available for deploying your uniGUI project to the Web .

Standalone Server
ISAPI Module
Windows Service

4.4.1 Sencha License Considerations


FMSoft Co. Ltd. is an official partner of Sencha Inc. and is granted to distribute OEM copies
of Sencha Ext JS and Sencha Touch. UniGUI distributes a partial copy of OEM Sencha Ext JS.
Your uniGUI license grants you using and deploying Sencha Ext JS. However, your OEM copy of
Sencha Ext JS can only be used in combination with uniGUI. You shall not use or distribute OEM
Sencha Ext JS for any other purpose other than using it to develop and deploy uniGUI projects.
This library can not be treated as a standalone library and can't be used to create independent
software products based on it. Sencha Ext JS/Sencha Touch is distributed as an integrated part of
uniGUI package. Sencha Ext JS/Sencha Touch is not distributed in form of a separate product
and you are not granted a separate license for it.

© 2016 FMSoft Co. Ltd.


48 uniGUI Developer Manual

4.4.2 uniGUI Runtime Package


uniGUI Runtime Package is an easy way to distribute uniGUI runtime files on server where
web applications are deployed. Runtime Package can be downloaded from FMSoft Portal. This
package is not available for uniGUI Trial Edition. After installing Runtime Package your web
application will be able to find related Ext JS and Sencha Touch files required to run your application.
uniGUI Runtime Package includes a minimal set of Sencha Ext JS/Touch library which is
required for uniGUI application. It also includes other JavaScript library files that will be needed during
runtime.

You must make sure that installed Runtime Package matches version of uniGUI package
you have used to compile your web application. For instance, if you have used
FMSoft_uniGUI_Complete_Pro_0.99.80.1267 to build your application, you must also make sure
that FMSoft_uniGUI_Complete_runtime_0.99.80.1267 is installed on your server. You can install
multiple versions of runtime package on your server, so web applications compiled with different
versions of uniGUI can co-exits on same server.

Deploying with Runtime Package requires all related path settings to be their default values.
ExtRoot, TouchRoot, UniMobileRoot and UniRoot must be set at their default settings. See below:

© 2016 FMSoft Co. Ltd.


Developer's Guide 49

4.4.3 Adjusting Paths


If you don't plan to deploy your app using uniGUI Runtime Package and you want to deploy runtime
files yourself then path settings must be adjusted accordingly. There are some essential paths for a
uniGUI application which must be adjusted before you deploy runtime files.

First of all, you must be sure that your Web Application knows where Ext JS files are located. For
this, in your Application ServerModule your must assign a proper path to ExtRoot property. Default
value of ExtRoot is "[ext]\" which means Ext JS files are located under where uniGUI Runtime
Package is installed: <InstallFolder>\FMSoft\Framework \uniGUI\ext-x.y.z.build

If you do not install uniGUI Runtime Package on target PC, you must assign a full or a relative
path to ExtRoot. If you assign a relative path it will be relative to ServerRoot and you can use the "..
\..\..\myfolder" partial path notation.

The easiest method is to set the ExtRoot to ".\[ext]" and copy the "ext-x.y.x.build" folder to root
folder of your web application where application executable or dll module resides. However, for
security reasons it is better to put "ext-x.y.x.build" folder in another folder and deploy all "ext-
x.y.x.build" files as read-only. Under IIS you must be sure that your application has enough
credentials for a read-only access to "ext-x.y.x.build" folder and its files.

© 2016 FMSoft Co. Ltd.


50 uniGUI Developer Manual

Some Examples:
ExtRoot = "[ext]" ExtJS Files are in <Runtime Pack age
InstallFolder>\FMSoft\Framework \uniGUI/ext-x.y.z.build\ (*Recommended method )
ExtRoot = ".\[ext]" ExtJS Files are in <server root>\ext-x.y.z.build\
ExtRoot = "C:\ExtJS\[ext]" ExtJS Files are in C:\ExtJS\ext-x.y.z.build\
ExtRoot = ".\ExtJS\[ext]" ExtJS Files are in <server root>\ExtJS\ext-x.y.z.build\
ExtRoot = ".\ExtJS\ext" ExtJS Files are in <server root>\ExtJS\ext\

In all cases ext-x.y.x.build is translated into a string which represents correct folder for your Ext JS
version. For example, if your uniGUI version is based on Ext JS version 4.2.5.1736 then it will be
translated to folder name: .\<path>\ext-4.2.5.1763\

Same principle is applicable to uniRoot, uniMobileRoot and TouchRoot properties.

Example:
UniRoot = "[uni]" uniGUI JS Files are in <Runtime Pack age
InstallFolder>\FMSoft\Framework \uniGUI/uni-x.y.z.build\ (*Recommended method )
UniMobileRoot = "[unim]" uniGUI JS Files are in <Runtime Pack age
InstallFolder>\FMSoft\Framework \uniGUI/unim-x.y.z.build\ (*Recommended method )
UniRoot = ".\[uni]" uniGUI JS Files are in <server root>\uni-x.y.z.build\
UniMobileRoot = ".\[unim]" uniGUI JS Files are in <server root>\unim-x.y.z.build\

Note: In above cases if "path\uni-x.y.z.build\" folder does not exist, "path\uni\" folder will be used
instead.

In this case uni-x.y.z.build is translated into library's uniGUI version. If your uniGUI version is
0.99.80.1260 translated folder name will be uni-0.99.80.1260.

If you deploy custom uniGUI themes to your server you can also set a custom folder for theme files.
You can use UniPackagesRoot property for this.
Default value for UniPackagesRoot is "[unipack]\" which means custom themes are placed in the
default location installer installs them. You can change this location by assigning a different value to
UniPackagesRoot property. Make sure that "themes" folder from default installation is completely
copied to the target folder:

UniPackagesRoot = "C:\ext\[unipack]" Themes are in "C:\ext\unipack ages\themes\" folder


UniPackagesRoot = ".\themefiles\" Themes are in "<server root>\themefiles\themes\" folder
UniPackagesRoot = ".\[unipack]" Themes are in "<server root>\unipack ages\themes\" folder

In ServerModule there are two other path related parameters: ServerRoot and CacheFolder.

© 2016 FMSoft Co. Ltd.


Developer's Guide 51

ServerRoot:

ServerRoot defines root path for all relative paths. A blank value points to application startup folder.

CacheFolder

A uniGUI server needs a folder to create temporary files. Normally, it is a folder named Cahce
created under same folder your module exists. You can change this by assigning a different path to
CacheFolder parameter. Under IIS you must be sure that your application has enough credentials
for a full access to CacheFolder.

If you want assign above properties a value at run time the correct location is OnBeforeInit event of
UniServerModule.

procedure TUniServerModule.UniGUIServerModuleBeforeInit(Sender: TObject);


begin
ExtRoot := 'C:\deploy\[ext]';
UniRoot := 'C:\deploy\[uni]';
end;

© 2016 FMSoft Co. Ltd.


52 uniGUI Developer Manual

4.4.4 Standalone Server


Standalone Server mode is very similar to VCL Application with some differences which makes it a
better option for Web deployment. In this mode your application main form is no longer visible on the
desktop, instead an icon is placed in Windows taskbar.

uniGUI Standalone Server

Double-clicking on this icon will open application control panel. Below you see an initial version of
control panel.

You can shutdown a running server by right-clicking the icon and selecting Shutdown menu item or
you can open server control panel and select Manage->Shutdown from top menu. .

One of the advanced features in uniGUI is accessibility of the Control Panel from web. You can
access control panel from this URL:

http://mysite:port/server

© 2016 FMSoft Co. Ltd.


Developer's Guide 53

Default Icon can be customized by either Changing the Delphi Application Icon or assigning a new
Icon to ServerModule->Favicon

Standalone Server is a good option for debugging your application or when you need a web server
where server availability is not very important. To automatically start server you must place a shortcut
to server executable in Windows Startup folder. In this mode server will not start until a Windows
user logs in. For serious deployment you must choose either ISAPI Module or Windows Service
deployment options.

4.4.5 Windows Service


Windows service is created and deployed like other regular Service applications created using
Delphi.

To install service simply type following command at command line*:

MyServiceApp -install

You can start service from Windows service manager or type the following command:

net start ServiceName

When you create a new project default value for service name is: UniServiceModule
You can change it from ServiceModule.pas->UniServiceModule->Name

To uninstall service:

MyServiceApp -uninstall

© 2016 FMSoft Co. Ltd.


54 uniGUI Developer Manual

*Please note that command line prompt must be started with Administrative rights in order to be
able to run above commands.

© 2016 FMSoft Co. Ltd.


Developer's Guide 55

4.4.6 ISAPI Module


Deploying your Internnet application as ISAPI module probably is best method of deployment. You
can run several modules together without a need to dedicate a TCP port to each application.

You can use all Web Servers which support ISAPI extentions. uniGUI generated modules are tested
with IIS 5.1, IIS 6.0, IIS 7.0 and Apache 2.2.

Installing instructions are different for each Web server. Please refer to below sections for
instructions:

IIS 5.1
IIS 6.0
IIS 7.0
Apache 2.2

4.4.6.1 IIS 5

In order to setup an IIS 5 uniGUI web application first step is to create a new Virtual Directory.

© 2016 FMSoft Co. Ltd.


56 uniGUI Developer Manual

Select an alias for new virtual Directory.

Now assign a folder to newly created alias.

© 2016 FMSoft Co. Ltd.


Developer's Guide 57

In next step give necessary permissions. Execute permission is required.

© 2016 FMSoft Co. Ltd.


58 uniGUI Developer Manual

After creating a new virtual directory you are ready to deploy your uniGUI server.Copy your ISAPI
module and other required files to virtual directory. You must be certain that ISS built-in users
IUSR_<ComputerName> and IWAM_<ComputerName> has enough credentials to access your
virtual directory and other folders that may be accessed during web application execution.

For instance if your ISAPI apps are under folder C:\WebApps then you must give full access to

© 2016 FMSoft Co. Ltd.


Developer's Guide 59

Your web application can be loaded by browsing to this URL:


http://localhost/<virtualdirectory>/<modulename>.dll

Also refer to Adjusting Paths for more information.

© 2016 FMSoft Co. Ltd.


60 uniGUI Developer Manual

4.4.6.2 IIS 6
In IIS 6 first step is to create a compatible application pool.

Give a proper name to the new pool.

In Application Pool properties, Recycling Tab uncheck the Recycle worker processes option.

© 2016 FMSoft Co. Ltd.


Developer's Guide 61

In Performance Tab uncheck the Shutdown worker processes after being idle... option.

© 2016 FMSoft Co. Ltd.


62 uniGUI Developer Manual

Next step is to create a Virtual Directory.

© 2016 FMSoft Co. Ltd.


Developer's Guide 63

Assign an alias to new virtual directory.

© 2016 FMSoft Co. Ltd.


64 uniGUI Developer Manual

Select the folder where your ISAPI modules are located.

Bu sure to grant Execute permission to Virtual Directory.

© 2016 FMSoft Co. Ltd.


Developer's Guide 65

Now open the properties of newly created Virtual Directory and change the default pool to pool you
created in first step.

© 2016 FMSoft Co. Ltd.


66 uniGUI Developer Manual

There is one further step in IIS 6. Your ISAPI extenstion must added to list of allowed extensions.

© 2016 FMSoft Co. Ltd.


Developer's Guide 67

Assign a name to your extension, add the extension's module DLL file and check the Set extension
status to Allowed option.

© 2016 FMSoft Co. Ltd.


68 uniGUI Developer Manual

After creating a new virtual directory you are ready to deploy your uniGUI server.Copy your ISAPI
module and other required files to virtual directory. You must be certain that ISS built-in users
IUSR_<ComputerName> and IWAM_<ComputerName> has enough credentials to access your
virtual directory and other folders that may be accessed during web application execution.

For instance if your ISAPI apps are under folder C:\WebApps then you must give full access to

Also refer to Adjusting Paths for more information.

© 2016 FMSoft Co. Ltd.


Developer's Guide 69

4.4.6.3 IIS 7 and Later


Like ISS 6, in IIS 7 first step is to create a new Application Pool.

Assigne a name to your pool and select No Managed Code option.

After creating the Pool open Pool's Advanced settings dialog and make the following modifications:

· Set Enabled 32-Bit Applications to True. (This option is available in 64-bit versions of Windows)

© 2016 FMSoft Co. Ltd.


70 uniGUI Developer Manual

· Set Disable Overlapped Recycle to True.


· Set Regular Time Interval to 0

Now add a new Application.

© 2016 FMSoft Co. Ltd.


Developer's Guide 71

Give it a proper name and adjust the Physical path. It is the path where your module DLL files exist.

Select Advanced Settings menu and open Advanced Settings dialog.

© 2016 FMSoft Co. Ltd.


72 uniGUI Developer Manual

In Advance Settings screen set the Application Pool to one you created in first step.

© 2016 FMSoft Co. Ltd.


Developer's Guide 73

Next step is to adjust the handler mapping for the application you just created.

© 2016 FMSoft Co. Ltd.


74 uniGUI Developer Manual

In Handler Mappings screen right-click on ISAPI-dll and select Edit Feature Permissions

© 2016 FMSoft Co. Ltd.


Developer's Guide 75

Check the Execute option and press OK.

If you don't see ISAPI-dll in handlers list then you must make sure that ISAPI Extensions are
installed in Windows Features. Visit Windows Features to check if it is installed.

© 2016 FMSoft Co. Ltd.


76 uniGUI Developer Manual

Next step is to check Authentication settings:

© 2016 FMSoft Co. Ltd.


Developer's Guide 77

Make sure Anonymous Authentication is enabled and the default user IUSR is set.

© 2016 FMSoft Co. Ltd.


78 uniGUI Developer Manual

© 2016 FMSoft Co. Ltd.


Developer's Guide 79

Last step is set ACL bits for web application physical folder. If IUSR is not available in the top list
you must add it manually to the list. IUSR is a built-in Windows user account which is available by
default.

Also refer to Adjusting Paths for more information.

© 2016 FMSoft Co. Ltd.


80 uniGUI Developer Manual

4.4.6.3.1 ISAPI and CGI Restrictions

For IIS versions after 7.0 there is an extra setting needed to make sure your ISAPI module
can be loaded by the IIS server. To adjust this setting open IIS Manager and select ISAPI and CGI
Restrictions from root server. (See below image)

ISAPI and CGI Restrictions

Double click on ISAPI and CGI Restrictions icon and open the module settings. Here you have two
options. You can either add each ISAPI module individually or allow IIS to run all unspecified ISAPI
modules by default.

© 2016 FMSoft Co. Ltd.


Developer's Guide 81

If you want to enable all ISAPI modules by default select Edit Feature Settings... and check Allow
unspecified ISAPI modules.

If you want to add modules one by one the select Add... button and add your ISAPI modules as
demonstrated in below image:

© 2016 FMSoft Co. Ltd.


82 uniGUI Developer Manual

4.4.6.4 Apache 2.2


Apache 2.2 web server for Windows allows running ISAPI modules. For this, a plugin called
mod_isapi must be enabled.

Apache doesn't have a visual interface for configuration. You must do some modifications to
httpd.conf file.

First of all, uncomment the following line:

LoadModule isapi_module modules/mod_isapi.so

Next you must associate .dll files with ISAPI module.

Add the following line

AddHandler isapi-handler .dll

Next step is add your module directory to Apache directory entries.

<Directory "C:/webapps">
Options Indexes FollowSymLinks ExecCGI
AllowOverride None
Order allow,deny
Allow from all
</Directory>

Finally create a new Alias for your directory.

Alias /mywebapps "C:/webapps"

Be sure to restart your Apache server after making the necessary modifications to httpd.conf file.

4.4.7 SSL Configuration


uniGUI supports SSL protocol for Standalone Server and Windows Service applications. Let's
emphasize that built-in SSL support is only for Standalone and Windows Service applications. In
ISAPI mode you must configure SSL by configuring your particular ISAPI server; IIS, Apache and
etc.

© 2016 FMSoft Co. Ltd.


Developer's Guide 83

First step to configure SLL is to obtain the required certificate files. In Standalone and Service modes
uniGUI uses Indy as the underlying TCP transport layer.

There are three files which you must provide here:

root.pem
cert.pem
key.pem

As you can see files are in pem format. Pem files are a human readable base64 ascii files which
can be opened and edited in an editor. A pem file may contain a single certificate or more than one
certificate. In order to work with Indy each pem file must contain only one certificate.

Below sample shows contents of a pem file:

-----BEGIN CERTIFICATE-----
MIIB8jCCAV+gAwIBAgIQfjGd2Py0qZJGqdkPiRlDdjAJBgUrDgMCHQUAMBAxDjAM
BgNVBAMTBWVsaXRlMCAXDTEzMDYwMjE3NTA0OFoYDzIxMTMwNTA5MTc1MDQ4WjAQ
MQ4wDAYDVQQDEwVlbGl0ZTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAt3pi
pMYHNzUueLZBb1eMrPop6Emta/KLyLaK94vlM1lV/6ITiuFtuSs9gq0s516s2th7
FUkBpgfQvrb+3b9h10WMca8MTbYrLGL+dHqRk4jGt/8GAUeYHkKddk/NeXkZWqaD
3aMdURpTgE2iK/d86C1YdsxqXTxP+Uax/eN4RUECAwEAAaNTMFEwFQYDVR0lBA4w
DAYKKwYBBAGCNwoDBDAtBgNVHREEJjAkoCIGCisGAQQBgjcUAgOgFAwSZWxpdGVA
RUxJVEUtUFJJTUUAMAkGA1UdEwQCMAAwCQYFKw4DAh0FAAOBgQCDSHm54tMh1sPY
aBrpZeZtbt9e1gPZ2B/Gd7U2KGK46yM8OQQ3LlnPaTc96q2ocD9sL3GP1B2itwX/
THOgUX7MpUipfUg6+8te6A7//gjiGyCf/OauJJrHal8p2QPwecGo3YnxUvTCu9gH
+iGE3Yqxv/6YqgDjGnpNdAvvX9gEfQ==
-----END CERTIFICATE-----

There are two types of certificate you can use along with your uniGUI server. You can either use a
certificate issued by a certificate authority or you can use a self-signed certificate for
development, test and / or private use.

© 2016 FMSoft Co. Ltd.


84 uniGUI Developer Manual

4.4.7.1 Obtain a SSL Certificate from an Authority


SSL certificates are published by companies which are specialized in issuing and hosting SSL
certificates. In order to obtain such a certificate you need to make a contract and purchase a
certificate dedicated to your company. This certificate will be known to whole web and will contain
information regarding your company, the certificate issuer and your web site.

Exam ple for a secured w eb site

First step is to create a CSR (Certificate Signing Request) file. There are several tools to create s
CSR file. OpenSSL is best tool which is widely used for such tasks. After you created the CSR file
you must send it to your certificate authority and they will verify information you provided in the CSR
file. Upon a successful verification they will sign your certificate and issue required certificate files.

Your certificate authority will guide you in process of creating a CSR file and rest of application
process.

After a successful application you will receive your certificate files. As described in previous section
you need three files to distribute with your server: root.pem, cert.pem and key.pem.

Note: sometimes cert.pem and key.pem can be issued as a single file. In this case you need to
open this file with a text editor and save the individual certificates in separate pem files.

© 2016 FMSoft Co. Ltd.


Developer's Guide 85

4.4.7.2 Generate a Self-Signed Certificate


This kind of certificate is good when you don't need a globally signed certificate issued by a
certificate authority such as Verisign. You can use a self-signed certificate for development purpose
or for private use in your intranet network or over the internet. You can use OpenSSL to generate
related certificate files.

First of all download and install OpenSSL Windows binaries from here. After installing open a
command prompt and follow below instructions.

We recommend downloading the lite version of the binaries:

Win32 OpenSSL v1.0.1e Light


Win64 OpenSSL v1.0.1e Light

a) Generate a self-signed Root certificate.

If you already have a root certificate installed in Windows you can try exporting it instead of
generating a new one. Simply go to Control Panel and click the Internet Options -> Content ->
Certificates. Select the root certificate you want to export. Choose the base64 format and select
folder and file name to export. This will export your root certificate in .cer format which can safely
rename it to .pem and use it in your uniGUI project.

You can also create a root certificate from scratch.

At command prompt issue following command:

openssl genrsa -out root.key 1024

This will create a new root.key file with strength of 1024 bit. Other options are 2048 and 4096.
Normally 1024 bit is enough.

If you want to create a root key with a password use below command instead:

openssl genrsa -des3 -out root.key 1024

Next step is to self-sign the certificate.

openssl req -x509 -days 365 -new -nodes -key root.key -out root.pem

If your root key is created with a password use below command instead:

openssl req -x509 -days 365 -new -key root.key -out root.pem

Now you will be prompted to provide several details needed to sign your certificate. You will also be
prompted for a password if your root.key file is created with a password in first step.

© 2016 FMSoft Co. Ltd.


86 uniGUI Developer Manual

Enter pass phrase for root.key:

You are about to be asked to enter information that will be incorporated


into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:TR
State or Province Name (full name) [Some-State]:Ankara
Locality Name (eg, city) []:Cankaya
Organization Name (eg, company) [Internet Widgits Pty Ltd]:FMSoft
Organizational Unit Name (eg, section) []:R&D
Common Name (eg, YOUR name) []:Farshad Mohajeri
Email Address []:[email protected]

Note: 365 is the number days which certificate will remain valid.

This will place a new root.pem file in same folder. This file will be used in your uniGUI server.

b) Generate a self-signed key.

Next step is to generate a self-signed key. This step will produce the key.pem and cert.pem files.

At command prompt issue the following command:

openssl req -x509 -days 365 -nodes -newkey rsa:1024 -keyout key.pem -out cert.pem

Again, you'll be prompted to answer several questions.

Loading 'screen' into random state - done


Generating a 1024 bit RSA private key
........++++++
.....++++++
writing new private key to 'key.pem'
Enter PEM pass phrase:
Verifying - Enter PEM pass phrase:
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:TR
State or Province Name (full name) [Some-State]:Ankara
Locality Name (eg, city) []:Cankaya
Organization Name (eg, company) [Internet Widgits Pty Ltd]:FMSoft
Organizational Unit Name (eg, section) []:R&D
Common Name (e.g. server FQDN or YOUR name) []:Farshad Mohajeri
Email Address []:[email protected]

© 2016 FMSoft Co. Ltd.


Developer's Guide 87

To create same key with a password use below command:

openssl req -x509 -days 365 -newkey rsa:1024 -keyout key.pem -out cert.pem

This time you'll be prompted to enter a password:

Enter PEM pass phrase:


Verifying - Enter PEM pass phrase:

This password will be assigned to SSL->SSLPassword parameter of UniServerModule. (See SSL


Configuration )

When all above procedures are completed you will end up with three files named root.pem,
key.pem and cert.pem which are required to setup and run your project in SSL mode.

© 2016 FMSoft Co. Ltd.


88 uniGUI Developer Manual

4.4.7.3 Configure SSL Parameters


Copy all three pem files to same folder your uniGUI server executable resides.

You also need OpenSSL standard DLL library files.

libeay32.dll
ssleay32.dll

These DLL files are distributed as a part of OpenSSL installation. You can also find the most recent
version of OpenSSL DLL files under below folders:

[UniGUI Installation Folder]\..\Framework\uniGUI\SSL\dll\x86


[UniGUI Installation Folder]\..\Framework\uniGUI\SSL\dll\x64

Depending on how you deploy your app you can copy them under Windows system folder (such as
C:\Windows\System32 ) or put them in same folder as your uniGUI server.

Note: There is a chance that above dll files are already installed by other programs and already
present in your system path. In this case you must make sure that most recent versions of dlls are
installed.

Next step is to open your project's ServerModule and make the following changes:

SSL->Enabled = True
SSL->SSLOptions->CertFile = cert.pem
SSL->SSLOptions->KeyFile = key.pem
SSL->SSLOptions->RootCertFile = root.pem

If you have protected your key files with a password then you need to assign it here:

SSL->SSLPassword = [Password]

Next parameter to confgure is the SSL port. You can leave it to default value which is 0. In this case
you can access your server through port which is configured in ServerModule -> Port which default
value is 8077.

© 2016 FMSoft Co. Ltd.


Developer's Guide 89

https://localhost:8077

Or you can use the default port for SSL whch is 443. Since 443 is the default value you can omit the
port number in address:

https://localhost

Normally you only want to use https protocol for a secured web application, but if for any reason you
need both http and https protocols for same site you can enable them by assigning different ports to
each protocol.

Consider the following configuration:

ServerModule->SSL->SSLPort = 443
ServerModule->Port = 8077

In above configuration you are able to access standard http protocol from port 8077 and access
https protocol from port 443.

If you choose the default port of 443 for SSL make sure neither IIS nor any other web server software
is not listening on this port.

© 2016 FMSoft Co. Ltd.


90 uniGUI Developer Manual

4.4.8 Adjusting Folder Access Rights


A uniGUI web server requires access to several folders to read, write or create files during
server lifetime. Many of such files will be created under Cache folder which is used to store all uniGUI
temporary files including session temporary files. Depending on deployment method web server will
be bound to a Windows user account.

· For a Standalone server this account will be current Windows user account.
· For a Windows Service this will be one of the LOCAL SYSTEM, LOCAL SERVICE or NETWORK
SERVICE accounts. It can also be any other user account.
· For an ISAPI module this account will be one of the IUSR, IUSR_<ComputerName>,
IWAM_<ComputerName> or IIS_IUSR built-in accounts. The account name varies between
different IIS version. For most recent versions of IIS, IUSR account is used when Anonymous
Authentication method is enabled. Please see ISAPI Module section for details.

After determining the correct Windows account necessary permissions must be granted to the
folders.

Full permission must be granted to web application physical folder. Go to Security tab and add the
correct user account to the list of account. For instance, if you are adjusting access rights for an
ISAPI module then you must grant full access to IUSR account for web application physical folder
and its sub folders:

© 2016 FMSoft Co. Ltd.


Developer's Guide 91

4.5 Stress Test Tool


4.5.1 Introduction
Scalability is one of the major concerns when developing web applications. Each web
application must be able to serve multiple users. Number of users can vary depending on type of
application. An application designed for a small intranet may be targeted by 10-50 concurrent users
at most while an internet web application may be used by more than 500-1000 simultaneous users.

In order to make sure your web application is ready for deployment in multi-user production
environment several tests must be performed. Firstly, application must be analyzed for its resource
usage. For a desktop app where only a single instance of your app is running resource usage will not
be your main concern because your application can use all of resources available in system. On the
contrary, a web application server is designed to serve multiple users and each user can be
dedicated only a fraction of available resources.

Scalability simply means ability of your project to scale up when number of sessions
increases in a real world system. A scalable web app should use several techniques to manage and
use system resources in most efficient way possible. For example, if each of your sessions
consumes ~1000 KB of memory (~1MB) in this case a web app running 400 sessions will require at
least 400 MB of physical/virtual memory to run properly. However, if each session consumes more
than 10MB then it is easy for your app to run out of memory when there are more than 100 active
sessions. Other system resources such as disk space, database connections and etc. should also
be taken into account.

For developers it may not be an easy task to simulate production environment on his/her
desktop. Your app maybe running smoothly when there are only a few sessions, but when number
sessions start to pass above a certain threshold several resource related issues and scalability
problems may arise. To deal with such scalability issues uniGUI is equipped with a very useful
named Stress Test Tool which aims to simulate a multi-user environment right on your desktop.
Stress Test Tool is located under ..\uniGui\Utils\StressTestTool folder and it is deployed with full
source code so it can be customized by developers if needed. This tool introduces many advanced
features which enables developers to simulate a production environment under heavy load.

© 2016 FMSoft Co. Ltd.


92 uniGUI Developer Manual

4.5.2 Usage
Here is the main form of stress test tool:

Using this tool you can record a web session and then playback to simulate multi-user behavior in
production environment. Stress test tool an stores each test environment in a project file which can
be used later to repeat the test. A project saves all of your recorded sessions and test parameters. It
is good to create a separate Stress Test project for each uniGUI project. uniGUI Stress projects are
stored under Projects folder with a extension of (*.uprj)

4.5.2.1 Recording a Session


Recording a session is an easy task.

§ First of all, you must compile your server with ServerModule->Options-


>soAllowSessionRecording = True. This parameter must be set to False once your app is
ready for production.
§ Build and run your uniGUI server.

© 2016 FMSoft Co. Ltd.


Developer's Guide 93

§ In Stress Test Tool set Url to Web Application to Url address of your server. If your server is
running in same machine a typical address would be http://127.0.0.1:8077

§ Press the Record button. This will launch a new browser window which will show main form of
your web application. This action will use your system default web browser.

Session Recoding
§ At this stage you can start using web application by navigating in menus, forms, grids and etc. All
of your actions will be recorded.
§ You can continue recording this session until you think all required menus, forms, grids and
functions of your app are fully visited.
§ When you are done you can terminate your web application.

© 2016 FMSoft Co. Ltd.


94 uniGUI Developer Manual

§ Now switch to Stress Test Tool and press the Stop button .
§ This finish your record session and adds it to list of available records for this project.

§ You can save your project using Save button .

Important: A session must be recorded in a way that session output is always predictable
i.e. it will always produce same HTML content. For example, pressing Button1 should always open
Form1 and selecting menu item User1 should always show a frame named TUserFrame. Normally,
it is the case for 99% of web applications where each user action results same output. There are
certain cases where user action may not produce a predictable result. Inserting rows in a DBGrid is
an example for this case. When user inserts a new row it creates a new grid row and also a new grid
page after certain number of rows are inserted. This means that each inserts produces a different
JavaScript content which is not predictable and it totally depends on current number of rows in the
attached database table. For this, it is recommended to avoid inserting data into a DBGrid while
recording a session.Likewise deleting or editing a row may not run properly during session playback.
Consider that your table contains 100 rows and you delete a single row while recording. When you
playback 100 instances of same session will try to delete same row while only one session can
actually delete it.

4.5.2.2 Running the Stress Test


Running a stress test by playing a previously recorded session is an advanced feature which will help
you to simulate a real time multi-user environment. After you have one or more recorded sessions
you can proceed with actual stress test procedure.

Stress test tool will play back a session by sending sequences of recorded Ajax requests to server.
This will simulate an environment where many users are using the web application. It is important to
know that play back process does not run your web application in a real browser window. The
simulation is performed by sending previously recorded Ajax packets to server in the exact order
generated while recording a session.

© 2016 FMSoft Co. Ltd.


Developer's Guide 95

To run a stress test you must follow below steps:

· Make sure that you don't run the Stress Test Tool in IDE and in debug mode. Running in
debug mode will highly reduce speed and performance of the Stress Test Tool. It is better
to compile it and run the executable directly.
· To record and playback a mobile session you must explicitly add '/m' to end of the
application Url.

§ Load a saved project or record a new a session if there are no recorded session available. (see
previous section to see how sessions can be recorded).
§ Adjust various test parameters:
· Total sessions per run: This is the number of sessions which will be created in each run. It is
proper to start with a low value and increase it gradually. This value should be a value lower or
equal to server's ServerModule->ServerLimits->MaxSessions property.
· Max Worker Threads: Number of worker threads used to communicate with the server. This
should be a value lower or equal to server's ServerModule->ServerLimits->MaxRequests
property.
· Total number of runs: Total number of times that recorded session will be played.
· Delay between runs: Number of seconds to wait before a new run starts
· Playback Speed: Using this parameter you can adjust the speed at which session is
simulated. If you choose Max Speed no delay will be inserted between Ajax calls so your
session will be played at max speed. You can also choose Real Time which will try to simulate
playback close to the original timing of the recorded session.

§ Start server monitor by pressing button.

§ Now you can press Start button which to start the actual stress test.
§ Start monitoring your server by analyzing various real time information displayed in server monitor:

© 2016 FMSoft Co. Ltd.


96 uniGUI Developer Manual

· Sessions: It shows number of sessions that are running in your uniGUI server. Peak value
shows maximum number of sessions that where running during server lifetime.
· Requests: Number of pending Ajax requests which are currently being processed by the server.
· Purged Files/Folders: These are files or folders which no longer belong to a session, but not
erased yet. Framework will gradually delete purged files and folders in a background thread.
Under normal conditions this value should eventually become zero.
· Bytes: Number of bytes Sent/Received during server lifetime.
· Uptime: Time passed since server has been started.
· Memory: It is one of the vital information which you need to constantly keep an eye on while
performing the stress test. It will show total amount of memory your server application is
consuming. It is important especially when your server is a 32-bit app. While 32-bit application
can consume up to 2 GB of RAM in theory, in practice any memory usage value above 1.0 - 1.1
GB means that your application is in danger zone. That happens because memory used by
uniGUI app will be fragmented over time. For this and for other reasons Delphi memory manager
can not use a total of 2.0 GB of RAM for a 32-bit uniGUI server. When your app runs out of
memory it will start logging "Out of Memory" messages and user will also see this warning when
a new session is started.
This is a serious situation and may produce unpredictable results which will eventually lead
to a server crash. If you are concerned with memory usage and your app will use more than 1GB of
RAM it is better to target your server for 64-bit platform. In a 64-bit server it is very unlikely to get an
"Out of Memory" error because even when physical RAM is consumed Windows will switch to virtual
memory which is limited by swap space available on your hard drive. So in a 64-bit server you can
consume memory much larger than the available physical memory. Of course, it must be noted that
virtual memory is much slower than physical memory, so in a 64-bit uniGUI server when your system
runs out of physical RAM you will notice a considerable drop in web application's performance and
responsiveness.
o Memory (Internal/Process): Internal memory is amount of memory internally used by the
uniGUI application. Process memory is the total memory consumed by Windows process
which is the uniGUI application. For example, if your app is an ISAPI dll main process which
is an ISAPI worker process will use more memory than internal memory used by the app
itself. If your app relies on external dll libraries such as Midas, again memory used by
process will be higher than memory used internally.

© 2016 FMSoft Co. Ltd.


Developer's Guide 97

· CPU Load: This will show amount of CPU power currently being used. If your CPU has multiple
cores (which is the case for all modern CPUs) this value will show total CPU usage for all CPU
cores. An idle uniGUI server will use very low CPU ticks so when both OS and uniGUI app are
idle CPU usage should not be more than 1%.
· GDI Handles: GDI handle is a limited system resource which is limited by OS. uniGUI is
optimized in a way to keep GDI handle usage at a very low level. If your app uses components
which rely on GDI handles you must check this value to see if it remain within a safe range. A
typical uniGUI app will not consume more than 100 GDI handles when it is in idle state (there
are no pending requests) even when there are hundreds of active sessions. uniGUI is designed
in a way so a GDI handle is returned to OS as soon as it is not needed. If you see a constant
increase in GDI handle then you must look for components which may leak GDI handles or
overuse them. When your app runs out of GDI Handles it will start logging EOutOfResources
exceptions in your log file. This is a serious problem which will eventually lead to server crash.
§ Another important step is to monitor your web application log files. Stress test runs in background
without any GUI output, so log file is the only way to see if your app runs properly. It is also the
only way to see any error logs generated while running the stress test. Log files are placed under .
\logs folder where your application's binaries are located. For each calendar day a separate log file
is created. You must open related log file in a text viewer/editor and see if there are any
unexpected logs such as Access Violations or other important Exceptions. By carefully analyzing
the log file you can have a better idea about your application stability and scalability. If you need a
more detailed log you can use a more advanced debugging tool such as EurekaLog.
§ Important: You must take this into consideration that each stress test runs same recorded
session in simultaneous threads for multiple times from same URL, so it is important to set the
ServerModule->SessionRestrict parameter to srNone while you are testing your server.

4.5.2.3 Server Flood Protection Considerations

Apparently, Stress Test Tool will send lots of requests in a very short periof of time. All these
requests are sent from same IP to your uniGUI application which is being tested. Your server OS
may interpret these high volume of requests as a flood DOS (Denial Of Service) attack and start
blocking such requests. It may happen especially if you run Stress Test Tool from a remote PC with
PlayBack speed set at Max Speed for a long period of time. Since flood detection algorithms varies
from OS to OS and highly depends on particular configuration and used server software it is hard to
predict when such blockages may occur. When server starts blocking requests you will notice lots of
HTTP error messages in right side memo in Stress Test Tool. This shows that requests are being
blocked and are not reaching their target.

For example, behavior will be different among running uniGUI app as ISAPI module in IIS, standalone
EXE and Windows Service. While running the Stress Test Tool from a remote PC may trigger flood
protection, running both uniGUI app and Stress Test Tool on same desktop should work without
triggering any flood protection mechanisms.

Additional to server OS some third party protection software such as Kaspersky, Symantec and
etc. may add additional layers of protection to your server IP traffic which may disallow fast and
continuous requests coming from Stress Test Tool. In such cases you need to slow down playback
speed by setting it to Real Time and/or putting a longer delay between Runs to allow the requests
pass through the anti-flood detection layers.

© 2016 FMSoft Co. Ltd.


98 uniGUI Developer Manual

4.5.2.4 Additional Settings


By nature Stress Test Tool creates hundreds of HTTP requests per second to perform a
heavy stress on subject server. This may go beyond the limits of OS which is running the Stress
Test Tool. One of these limitations is TCP port limit which is limited to a certain value by OS by
default. In order to make a smooth run of Stress Test Tool we need to adjust the TCP port limit and
increase it to a higher value. This requires a few registry setting in Windows Registry.

Good news this that Stress Test Tool can automatically make this change in registry for you. All
you need to do is selecting Other->Adjust Registry Settings in Stress Test Tool.

Above dialog will be opened and it will give a brief information about the settings and will ask you to
confirm the operation. These changes are totally harmless and will increase TCP port creation limit
on your OS.You must make sure that you have started Stress Test Tool as administrator to be
able to make this change.

A successful operation will show below message and ask you to restart your PC to finalize the
operation.

© 2016 FMSoft Co. Ltd.


Index 99

Index
-D-
DataModule 22

-E-
ExtRoot 55

-L-
LoginForm 22

-M-
MainForm 22, 38
MainModule 22, 28
ModalResult 26
mrCancel 26
mrOK 26

-R-
RIA 4

-S-
ServerModule 22, 28

-U-
uniGUI 4

© 2016 FMSoft Co. Ltd.


100 uniGUI Developer Manual

Endnotes 2... (after index)

© 2016 FMSoft Co. Ltd.

You might also like