Professional Documents
Culture Documents
BY DAVID INTERSIMONE
Chapter 1: Introduction
Today's computing landscape is no longer confined to a desktop, device, server, or data center.
Applications are being moved from the desktop to multiple devices, network edge connections, and to
on-premises, public and hybrid cloud services. With RAD Server and RAD Studio, you can build solutions
that cover a wide spectrum of your company's (and customer’s) computing needs and business
requirements.
This e-book will show you how to quickly design, build, debug, and deploy services-based multi-tier
applications using RAD Server’s REST-based API hosting engine, components and technologies that are
available in RAD Studio Enterprise and Architect editions.
The computers, software and devices used in creating this technical paper include RAD Studio 10.3.1 Rio
Enterprise Edition, InterBase 2017 Server, Dell desktop running Windows version 10, Dell notebook
running Windows version10, Dell notebook running Ubuntu version16.04 LTS, MacBook Pro running
macOS 10.14 Mojave, iPhone running iOS version 12.1.4 and Nexus 7 running Android version 6.0.1
Embarcadero’s RAD Server provides a turn-key application foundation for rapidly building and deploying
services-based applications using Delphi and C++Builder. RAD Server supports the REST
(Representational State Transfer) protocol with JSON (or XML) parameter passing and return results. You
can publish APIs, manage users and devices that are connected to the RAD Server, capture analytics
about the use and users of applications, connect to local and enterprise databases using the FireDAC
components and connect with Internet of Things (IoT) devices. RAD Server also supports user
authentication, push notifications, geolocation, and data storage.
Throughout the RAD Server documentation, source code, and in this technical paper, you’ll see
references to EMS (Enterprise Mobility Services). EMS was the original name for the product,
technologies, components and wizards that are now included the RAD Server product.
With RAD Server’s wizards, components, and tools you can quickly develop new middleware and back-
end applications or migrate your existing Delphi and C++Builder client/server applications to a RAD
Server based application to run on a server or in the cloud. You can publish your endpoints for REST calls
from desktop, mobile, console, web and other types of applications. RAD Server comes with a full set of
tools, components, database connectivity and interfaces that you will rely upon in building your service
applications.
RAD Server applications can be deployed on top of Microsoft Windows IIS and Apache web servers, and
you can deploy your Delphi-based services to Linux Intel 64-bit servers.
To build RAD Server based applications, the diagram below guides developers through seven aspects and
development phases.
To start, create your server REST/JSON API-based endpoints (you can also use XML instead of JSON if
required). Next extend the endpoints by integrating a wide range of databases, cloud services, IoT
devices, and other technologies.
You can add more application endpoints to users and create API access control rules. You can write code
that leverages RAD Server’s built-in secure data store to keep track of persistent data. You can create user
groups, add users via console portal and import, or authenticate users via LDAP-based API services.
After you have developed and debugged your applications, you can host RAD Server applications on a
private on-premises Windows and Linux servers. You can also migrate your applications to cloud systems
like Amazon AWS, Microsoft Azure, Google, and other cloud providers.
After your application is put into production, you can manage access to your APIs, control users access,
and analyze the utilization of your endpoint API activity with built-in application management interfaces.
Finally, you can build desktop, mobile, Web, console, and other application types supported by RAD
Studio. You can also build modern Web client applications using Sencha ExtJS’s set of components or use
other tools and programming languages to build client applications that support your RAD Server
application’s REST/JSON functionality.
The following sections contain the product and technical requirements for building, testing, and deploying
RAD Server applications. Unless otherwise noted, “RAD Studio” and the IDE apply to the RAD Studio,
Delphi, and C++Builder products.
A RAD Studio Enterprise or Architect Edition version 10.1 Berlin or later with a commercial license is
required to build RAD Server applications. This white paper was written and tested using a commercial
version RAD Studio version 10.3.1 Rio Enterprise Edition. The trial edition of RAD Studio Enterprise can
be used for 30 days, for development and testing. The trial edition does not support deployment to a
production server.
To test RAD Server applications, RAD Studio includes a 5-user developer license. Beginning with version
10.2 Release 2, RAD Server deployment licenses are included in Enterprise and Architect commercial
editions of RAD Studio. These commercial editions include a single-site deployment license for RAD
Server. RAD Studio 10.2.3 Architect edition includes a multi-site deployment license for customers who
are on active Update Subscription.
RAD Server requires an InterBase 2017 encrypted database as part of deploying your applications in a
Production Environment. You will need to use a valid RAD Server license to install this version of
InterBase.
If your RAD Server application needs to connect with SQL databases, MongoDB, or through an ODBC
database bridge, you can use FireDAC with the following database systems and versions.
• Windows 10
• Windows 10 Anniversary Update
• Windows 8.1
• Windows 7 SP1
• Windows Server 2012 and 2016
RAD Server applications have been tested using the following Web Server applications and platforms.
See Also
For the latest updated information about installation of RAD Studio and deployment of RAD Server based
applications please refer to the following Embarcadero DocWiki online links.
InterBase:
http://docwiki.embarcadero.com/RADStudio/Rio/en/InterBase
FireDAC:
http://docwiki.embarcadero.com/RADStudio/Rio/en/FireDAC
Core Features
Here is a list of some of RAD Server’s core features that you’ll want to leverage in building your services-
based applications.
• REST End Point Publishing – RAD Server implements a turn-key foundation for your application
back end APIs and Services. RAD Server provides an easy to use API for publishing your business
logic. Delphi or C++ code can be hosted as an API and auto-published as REST/JSON endpoints
which are measured and managed by RAD Server. Endpoint publishing features include:
◦ Access Control – You can set up group and user level access, with authentication, to all
application APIs and control who has access to your application’s API functionality.
◦ API Analytics – All REST API end-point activity is recorded and measured for robust statistics
tracking and analytics. You can analyze user, API, and services activity daily, monthly, and
yearly to gain insight into how your application is being utilized. You can also filter activity for
all resources or by specific groups, users, device installations, and more. You can also export
analytics to a CSV file for additional analysis with other tools.
◦ Desktop, Mobile & Web Client Applications – All C++ and Delphi code hosted on RAD Server is
published as REST/JSON end points consumable by any client application on multiple
platforms for extreme flexibility and future-proofing.
• Integration Middleware – RAD Server provides multiple integrations out of the box with
connectivity to external servers, applications, databases, smart devices, cloud services, and other
platforms. Integration capabilities include:
◦ Enterprise Data – RAD Server delivers high performance built-in connectivity to all popular
Enterprise RDBMS servers. Database connectivity uses the FireDAC set of components and
libraries for easy connectivity with data from a variety of sources.
◦ IoT Smart Device Connectivity – RAD Studio’s IoT components enable fast and easy
integration of IoT Smart devices into your application’s services. RAD Server’s IoT Edgeware
allows you to connect your Bluetooth IoT devices where they are physically located.
◦ Cloud Services – With RAD Server you can easily integrate REST cloud services from a variety
of cloud, social, and BaaS platforms such as Google, Amazon, Facebook, Kinvey, and more.
• Application Services – RAD Server includes a collection of ready to use built-in services to power
your application. RAD Server includes core functions such as user directory services and user
management, push notifications, user location tracking, and built-in data storage. Some of these
application and device services include:
◦ Push Notifications – Using RAD Server you can send programmatic or on-demand notifications
to your application users and their devices. RAD Server currently supports push notification
systems including Apple Push Notification service (APNs) and Google Cloud Messaging (GCM).
You can also write custom code to connect with other push notification systems.
◦ Built-in Secure Datastore – With RAD Server’s support for secure an InterBase server’s
encrypted datastore you can use built-in APIs to store and retrieve JSON data without
requiring a separate database server.
◦ User/Group Management –Using RAD Server APIs you can create and manage your users,
user groups, and control access via the RAD Server management portal.
◦ User Location/Proximity – Your RAD Server applications can leverage RAD Studio’s support for
GPS, beacons, and beacon fence technology. RAD Server applications can track user
movement, both indoors and outdoors, and respond to proximity events when users enter
and exit custom beacon zones or approach designated beacon points.
The following features are included in RAD Studio 10.3.x Rio. You’ll see notations for when some of the
core features were introduced, enhanced, and those that are new in the Rio release.
• RAD Server is a turn-key REST-based middleware stack that includes API hosting, data access, and
SQL Database access, with significantly optimized performance. RAD Studio version 10.3 Rio
Enterprise Edition includes a single site RAD Server deployment license (additional RAD Server
deployment licenses are available separately). RAD Studio version 10.3 Rio Architect Edition
includes a multi-site deployment license. (Enhanced in 10.3 Rio)
• Build, test and deploy RAD Server packages on Linux. Linux support is currently available for
Delphi. (Introduced in 10.2 Tokyo)
• Create custom REST APIs for your business functionality and map them to custom URIs. Use
loadable packages for RAD Server. Integrate with FireDAC high-performance enterprise data
access for Oracle, DB2, Microsoft SQL Server, Informix, MySQL Server, etc.
• The new EndpointProduce attribute allows mapping of MIME types (from Accept HTTP request
header) to GET endpoints; the new EndpointConsume attribute allows developers to map MIME
types (from Content-Type HTTP request header) to PUT, POST, PATCH endpoints. These new
features allow RAD Server applications to define two distinct ways to map methods to the same
URL and HTTP verb, and return different types of data depending on the request. (New in 10.3
Rio)
• HTTP Verb to Custom Method Name Mapping: Previous releases of RAD Server would generate
custom mappings for HTTP verbs (GET, POST, etc.) to method names (this remains the default
behavior). With RAD Server in v10.3 or later, you can also map an HTTP verb to a method with a
custom name by using the new EndpointMethod attribute. (New in 10.3 Rio)
• Delegate Processing of a Request to a Custom Class or Component. This feature allows for the
sharing of response processing code. (New in 10.3 Rio)
See Also
RAD Server uses an InterBase database for the storage of user information, user groups, analytics,
registered devices, version information, registered Edge Modules, push notification messages, and more.
RAD Server includes EMS (Enterprise Mobility Services) and offers a Mobile Enterprise Application
Platform (MEAP) that you can host in a cloud or on-premises. Developers can use RAD Server to expose
custom REST APIs and access enterprise database data using the FireDAC data access library and
components.
RAD Server provides developers with a comprehensive solution that includes remote database access,
user tracking, device application management, use analytics, and more. Compared to other solutions,
RAD Server includes a pre-built application server that supports integration of custom packages. These
custom packages can expose data sets, business logic, and other REST-based resources. Components are
also available for mobile, web, and desktop application code to access RAD Server resources.
The fastest way to get started is to use the New Projects menu (File | New | Other…) and choose the RAD
Server | RAD Server Package wizard for Delphi or C++Builder.
Select the RAD Server Package project. A wizard will display to help create the starting project. On the
first page choose how the wizard will create the resources and endpoints that will be included in the RAD
Server application. The RAD Server Package Wizard provides two choices to proceed.
Choice 1: Create an empty package that does not register a resource. Choose this option if you are going
to add your resources later on. Using this choice, a package project will be created with a starting main
library.
Clicking the Finish button will create the starting project for additional development work to create the
finished RAD Server application.
Choice 2: Create a package with a resource that extends the REST API of for the RAD Server. Click the
Next Button and two additional wizard steps will display to help create the package project, resource,
and endpoints. To build the first RAD Server project make this choice.
On the wizard’s second page set the Resource name to “Test”. The File type radio buttons presents two
options: 1) create a unit for implementing the resource in code, and 2) create a data module for
implementing the resource using the IDE’s designer, components, and code editor. For this first RAD
Server application choose to use a Data Module.
On the wizard’s third page choose from a set of predefined EndPoints: Get (REST GET), GetItem (REST
GET with a segment at the end of the URL that identifies the item to get), Post (REST Post), PutItem (REST
Put with a segment at the end of the URL that identifies the item to put), and DeleteItem (REST Delete
with a segment at the end of the URL that identifies the item to delete). There is also a Select/deselect
all check box at the bottom of the EndPoints list. To create a package project with all of the EndPoints
defined, click on all of the starting end-points or choose Select All. You can also step back through the
wizard or click on the step links to make changes to the Package, Resource, and Endpoints screens. To
create your starting project is to click the Finish button.
After the wizard completes, you are placed back in the IDE. The first thing to do is to save the project:
• For the C++ and Delphi data module, use the name “MyDMUnit”.
• For the C++ project and package use the name “MyFirstCppRADServerPackage”.
• For the Delphi project and package use the name “MyFirstDelphiRADServerPackage”.
Here are the projects and source code created by the wizard for Delphi and C++. For the C++ code, I have
added a couple of lines of code in the Get and GetItem endpoint implementations to set the response
(look for the // sample code comment line in MyDMUnit.cpp).
Delphi:
MyFirstDelphiRADServerPackage.dpk:
package MyFirstDelphiRADServerPackage;
{$R *.res}
{$IFDEF IMPLICITBUILDING This IFDEF should not be used by users}
{$ALIGN 8}
{$ASSERTIONS ON}
{$BOOLEVAL OFF}
{$DEBUGINFO OFF}
{$EXTENDEDSYNTAX ON}
{$IMPORTEDDATA ON}
{$IOCHECKS ON}
{$LOCALSYMBOLS ON}
{$LONGSTRINGS ON}
{$OPENSTRINGS ON}
{$OPTIMIZATION OFF}
{$OVERFLOWCHECKS OFF}
{$RANGECHECKS OFF}
{$REFERENCEINFO ON}
{$SAFEDIVIDE OFF}
{$STACKFRAMES ON}
{$TYPEDADDRESS OFF}
{$VARSTRINGCHECKS ON}
{$WRITEABLECONST OFF}
{$MINENUMSIZE 1}
{$IMAGEBASE $400000}
{$DEFINE DEBUG}
{$ENDIF IMPLICITBUILDING}
{$RUNONLY}
{$IMPLICITBUILD ON}
requires
rtl,
emsserverapi;
contains
MyDMUnit in 'MyDMUnit.pas' {TestResource1: TDataModule};
end.
MyDMUnit.pas:
unit MyDMUnit;
interface
uses
System.SysUtils, System.Classes, System.JSON,
EMS.Services, EMS.ResourceAPI, EMS.ResourceTypes;
type
[ResourceName('Test')]
TTestResource1 = class(TDataModule)
published
procedure Get(const AContext: TendpointContext;
const ARequest: TEndpointRequest; const AResponse: TEndpointResponse);
[ResourceSuffix('{item}')]
procedure GetItem(const AContext: TendpointContext;
const ARequest: TEndpointRequest; const AResponse: TEndpointResponse);
procedure Post(const AContext: TendpointContext;
const ARequest: TEndpointRequest; const AResponse: TEndpointResponse);
[ResourceSuffix('{item}')]
procedure PutItem(const AContext: TendpointContext;
const ARequest: TEndpointRequest; const AResponse: TEndpointResponse);
[ResourceSuffix('{item}')]
procedure DeleteItem(const AContext: TendpointContext;
const ARequest: TEndpointRequest; const AResponse: TEndpointResponse);
end;
implementation
{%CLASSGROUP 'System.Classes.TPersistent'}
{$R *.dfm}
var
LItem: string;
begin
LItem := ARequest.Params.Values['item'];
// Sample code
AResponse.Body.SetValue(TJSONString.Create('Test ' + LItem), True)
end;
procedure Register;
begin
RegisterResource(TypeInfo(TTestResource1));
end;
initialization
Register;
end.
C++:
MyFirstCppRADServerPackage.cpp:
// EMS Package
//---------------------------------------------------------------------------
#include <System.hpp>
#pragma hdrstop
MyDMUnit.h:
MyDMUnit.cpp:
//---------------------------------------------------------------------------
#pragma hdrstop
#include "MyDMUnit.h"
#include <memory>
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma classgroup "System.Classes.TPersistent"
#pragma resource "*.dfm"
//---------------------------------------------------------------------------
__fastcall TTestResource1::TTestResource1(TComponent* Owner)
: TDataModule(Owner)
{
}
{
// Sample code
AResponse->Body->SetValue(new TJSONString("Test"), True);}
Now that you’ve used the wizard to build your first RAD Server application, you can use the IDE to
compile and test the application. The IDE uses the EMSDevServer as the host executable
(EMDDevServer.exe) to start execution with the parameter being the package file to load. There are two
versions of the EMSDevServer for Win32 and Win64 development ($(BDS)\bin\EMSDevServer.exe and $
(BDS)\bin64\EMSDevServer.exe).
RAD Studio also includes EMSDevConsole.exe which will start the EMSDevConsole server and open the
EMS Console Server Window. The EMS Console provides a web application which displays analytics,
provides for user/group management, and more for your RAD Server application.
Choose the Run | Run menu item or hit F9 to compile, link and run the starting application. The RAD
Server Development Server will start, by default, using TCP port 8080. If this is the first time run of a RAD
Server Application, a dialog box will display that says the RAD Server configuration file (emsserver.ini)
was not found. This happens when there is no RAD Server registry key or if the configuration file does
not exist.
Click the Yes button to run the RAD Server configuration wizard.
In the first wizard step, enter the InterBase server instance (by default RAD Studio’s development version
of InterBase Server uses gds_db). If you previously installed InterBase using a different server instance
name, enter that name string. This wizard page also contains the name for the RAD Server database
(emsserver.ib), and directory that will contain the database and configuration file.
Click the Next button to tell the wizard whether you to create sample RAD Server database data for users
and user groups. For development and testing we’ll set both check boxes.
Click the Next button to set up the user name and password for logging into the RAD Server console.
Click the Next button to go to the final wizard step. The wizard is ready to create the RAD Server
database file, configuration file, and set the Windows registry key for the currently logged in user.
This page displays the database file path and name, configuration path and name, and the Windows
Registry key. You can always make changes to the RAD Server configuration file (emsserver.ini) at any
time. Click the Finish button. A confirmation dialog will display with a reminder that the configuration
will use an instance of InterBase that does not have a RAD Server license. The development license limits
your RAD Server application to a maximum of 5 users.
Figure 21: Confirmation dialog box - using InterBase instance without a RAD Server license.
When you are ready to deploy your RAD Server application, you’ll be able to use your deployment
licenses for RAD Server and InterBase.
Click the Yes button. The wizard will display the location of the emsserver.ini configuration file. It also lists
the sample data that has been added to the database.
Use RegEdit to view the registry key created for the RAD Server configuration file location.
When the RAD Server configuration server is created, the RAD Server Development Server will start
executing. On my development computer, the EMSDevServer reports that the default port (8080) is
already in use because some other application (Tomcat Server, another web server, etc.) is already using
the port 8080.
Figure 27: RAD Server Development Server not started due to port
conflict.
You can use the edit box to enter an unused port number (I chose port 8087). Click the Start button and,
if the new port number is unused, the RAD Server Development server will start running for this first
launch.
To make the port change permanent for your all of your development work, edit the RAD Server
development configuration file, emsserver.ini. Use a text editor to open the emsserver.ini file. Search for
the [Server.Connection.Dev] section. Edit the unused port number and save the configuration file
[Server.Connection.Dev]
Port=8087
The RAD Server configuration file will be covered in more detail in the chapter titled “RAD Server
Configuration INI File Explained”.
When you click run in the IDE the RAD Server Development Server will start executing and the log will
show the operations that take place for your package application.
C++ version:
Figure 28: RAD Server Development Server starting the first C++
application package.
Delphi version:
Figure 29: RAD Server Development Server starting the first Delphi
application package.
The RAD Server Development Server log will display the configuration, database connection, licensing
information, the application package that was loaded, the resources that were registered, and endpoints
that were created.
Clicking the Open Browser button will start your default browser and display the JSON result of calling
the GetVersion built-in endpoint. You’ve now used your first RAD Server REST endpoint!
In the browser, change the URL to localhost:8087/Test and hit enter. The browser will receive the JSON
response from the Get endpoint.
If you pass an additional item on the URL, the GetItem endpoint will be called, and the code behind will
return a JSON string containing the resource name plus the item you typed.
For simple examples it is okay to return a JSON string, but for larger, more complex data structures, you
may not want to return a large JSON string. RAD Studio provides many other ways to generate JSON data
including using JSON objects, JSON streams, and the JSON writer.
Edit the URL to use the “Users” resource which will call the default GetUsers endpoint to display JSON for
the user generated by the RAD Server configuration wizard in the RAD Server datastore (there is only one
to start).
Figure 33: JSON response in the Browser for a call to the GetUsers end point.
You’ve now used four of the endpoints that were generated by the RAD Server project wizard.
Go back to the RAD Server Development Server and click the Open Console button. This will start the
RAD Server Development Console Server.
Click the Open Browser button to get the RAD Server Console home page.
Click the Login link on the browser page and type your console username and password (Reminder:
consoleuser and consolepass are the default values) in the sign in wizard.
Type in the console username and password and click the Login button. The console’s overview page will
display after logging in. The links on the left side of the page provide navigation to display and manage
the users, groups, device installations, EdgeModules, Resources, and Analytics.
Click the Analytics drop down and select the API Calls analytic to see a chart of the daily, monthly, and
yearly usage for the RAD Server application’s endpoints.
Figure 38: RAD Server Console API Calls Analytics page with usage chart and statistics.
All of this RAD Server application functionality is available after a wizard, a few menu choices, and mouse
clicks that helped create a starting RAD Server application project. Run the RAD Server Development
Server, set up your configuration file, and you can quickly test your application.
There is a new RAD Server Console UI for RAD Studio 10.3.1 that is built using Sencha’s Ext JS. This new
console is available as a free download via RAD Studio’s GetIt Package Manager (use the Tools | GetIt
Package Manager... menu item). Go to GetIt and search for RADServerConsole and you’ll see the
following entry displays:
Click the Install button and a description with a license agreement will display.
Click the Agree all button. The RAD Server Console Ext JS version will be downloaded and installed.
Start the RAD Server application and click the Open Console button. Click the console’s Open Browser
button. To launch the new Sencha EXT JS based console use the URL
http://localhost:8081/extjs/index.html
After logging in you’ll see a fresher, graphics view of the RAD Server console single page JavaScript app
with menu on the left and content on the right. The menu provides access and management of users,
groups, device installations, EdgeModules, Resource Modules, and Analytics. Here is the screen that
shows a list of users and their information including when the user was created and when the user
information was last modified.
Clicking the Analytics menu item, a drop-down menu opens. You can select from a range of analytics
including total users, active users, API calls, API endpoints called, and more. Analytics can be chosen by
day, month, and year. The analytics can also be filtered by user, group, etc. Analytics results can also be
saved to a CSV file for additional processing by external applications.
The following chart shows an API calls chart for a selected month.
Figure 46: RAD Server Console Ext JS API calls analytics page.
The REST Debugger, included with RAD Studio, is another way to test RAD Server application endpoints.
Launch the REST Debugger from the IDE using the Tools | REST Debugger menu item. Use the GET
method and URL http://localhost:8087/Users to see the JSON result.
You can add database functionality to the RAD Server application using FireDAC and an InterBase
database in two ways:
1. add FireDAC database components to the existing RAD Server resource module
2. add an additional RAD Server resource module.
To keep the database functionality separate from the original endpoints, choose to add an additional
server module to the project. With the first RAD Server application project loaded in the IDE, use the File
| New | Other… menu item and select to add a new RAD Server Module to the existing Delphi and C++
projects.
Click the OK button and the RAD Server module wizard will display. Name the new Resource data module
FireDAC and click the Next button.
For this RAD Server resource module choose to include the default Get and GetItem endpoints.
Add a FireDAC FDConnection component to the resource module. Bring up the FDConnection connection
editor with a right-mouse click on the component. Connect the FDConnection to the InterBase
Employee.gdb sample database. Click the Test button to verify the connection.
Add an FDQuery component to the resource module. Right-mouse click on the component to bring up
the Query editor. Type in the SQL statement “select * from customer” and click the Execute button to
test the query.
Set the FDQuery component’s Name property to CustomerQuery. Add an FDSchemaAdapter component,
set the Name property to CustomerSchemaAdapter, and set the CustomerQuery component’s
SchemaAdpater property. Add a FDStanStorageJSONLink component.
You’re FireDAC resource module will now look something like the following figure:
Before you compile and run the application server, add a few FireDAC libraries to the Requires section of
your project. Right-mouse click on the Requires section and choose the Add Reference… in menu item.
Navigate to the C:\Program Files (x86)\Embarcadero\Studio\20.0\lib\win32\release folder and multi-
select the dbrtl, FireDAC, FireDACCommon, FireDACCommonDriver, and FireDACIBDriver files and click
the OK button.
Add the following code to implement the default Get endpoint for your FireDAC-based RAD Server
resource. This code will provide a JSON version of query result to a browser or some other client
application.
Delphi:
end;
C++:
Compile and run the RAD Server application. Click the Open Browser button and test the new FireDAC
resource module’s Get endpoint using the localhost:8087/FireDAC URL. The response from the Get
endpoint will contain JSON from the SQL query.
Figure 56: FireDAC resource Get endpoint returns JSON database information
and data.
First, add VCL and multi-device client applications to the project group. The client application will call the
FireDAC resource’s GET endpoint (just as the browser did) to receive the query’s JSON response.
To add a new client project to the existing project group, right-mouse click on the project group and
choose the Add New Project… in menu item. From the New Items dialog choose to create a VCL
application and also a blank multi-device application. Follow the steps below for both the VCL and Multi-
Device application projects.
Add an EMSPRovider component to connect each client application to the RAD Server application. Set
the URLHost property to locahost. Set the URLPort property to 8087. Right-mouse click on the
EMSProvider and choose the Test Connection pop-up menu item to make sure the client applications can
connect to the RAD Server application.
The dialog box that displays in the IDE contains the JSON returned by calling the RAD Server application’s
version endpoint.
Add a BackendEndpoint component to allow the client application to access an endpoint in the RAD
server application. Set the BackendEndpoint property name to BackendEndpointGetCustomers and set
the Resource property to FireDAC. Add Button and Memo components to provide the minimal UI for the
client application. The design window for your client application should look something like the
following:
Right-mouse click on the BackendEndpointGetCustomers component and choose the Execute menu item
from the menu. If you’ve set up the EMSProvider and BackendEndpoint correctly you should see the
following dialog window in the IDE.
To complete the client application, add the following code to the OnClick event handler for the Button.
Delphi:
C++:
Compile and Run the VCL and multi-device client applications and see the same JSON result that
displayed in the browser.
Figure 60: RAD Server application JSON result for the Get endpoint call from the
client application.
Congratulations! You have just built your first client application that connects to the RAD Server
application. In the chapter titled “Using the EMSDataSetResource Component”, you’ll learn how to
enhance your RAD Server applications using the new TEMSDataSetResource component. This new
component provides additional flexibility in working with databases and data sets.
See Also
Configuring Your RAD Server Engine or RAD Server Console Server on Windows
http://docwiki.embarcadero.com/RADStudio/Rio/en/
Configuring_Your_RAD_Server_Engine_or_RAD_Server_Console_on_Windows
The configuration setup wizard can also be executed as a standalone application. Open a command
prompt or terminal window and type: EMSDevServer.exe -setup
After the configuration file is created, use the IDE or any text editor to make changes as needed.
Each part of the RAD Server configuration file is defined by a section name string inside square brackets.
The section names (in the order they are usually displayed) are:
• [Server.Packages] - Specifies the path and description for extension packages you create to
register custom resource endpoints.
• [Server.Push.GCM] – Contains settings for Google Cloud Messaging (GCM).
• [Server.Push.APNS] – Includes settings for Apple Push Notification Service (APNs).
• [Server.Authorization] - Defines settings for the authorization requirements for the server
application’s resources and endpoints.
• [Server.Redirect] - Sets up redirects for custom resources to handle client application requests
instead of the resource identified in the URL.
• [Server.EdgeHTTP] - Set up a proxy host, port, username, and password for Edge Module based
requests (if required).
• [Server.Tenants] - Provides the settings for the single and multi tenant configurations for your RAD
Server application.
• [Server.Roots] - Allows for the setting of a root path string for the RAD Server application’s URLs.
• [Server.PublicPaths] - Identifies the directories where static files are located and the URLs they
are mapped to.
The following information explains more about the configuration file sections included in the RAD Server
configuration file (emsserver.ini) that was created by the setup wizard.
Use the Database Configuration section to modify the default information of the RAD Server Database
that the RAD Server Application uses. Included in this section are the following:
• InstanceName – specifies the InterBase instance that hosts the RAD Server database.
• Database – the RAD Server Database file local directory.
• UserName – the user name to access the RAD Server Database.
• Password – the password to access the RAD Server Database.
• SEPassword – the password to connect to an encrypted InterBase database.
• Pooled – enables FireDAC connection pooling to the RAD Server Database to reduce latency.
• PooledMax – use this to set the maximum number of pooled connections allowed to the RAD
Server Database.
[Data]
;# Interbase connection parameters
InstanceName=gds_db
Database=C:\Users\Public\Documents\Embarcadero\EMS\emsserver.ib
UserName=sysdba
Password=masterkey
SEPassword=
;# SEPassword connects to an encrypted database
Pooled=
;# Set Pooled=0 to disable connection pooled, Pooled=1 to enable. Default value is
1.
PooledMax=
;# Set PooledMax=10 to limit maximum pooled connection. Default value is 50.
Use the Server Limits section to modify the default information of the number of simultaneous
connections to the RAD Server database or the maximum number of RAD Server Users. This section
includes:
• MaxConnections – the maximum number of concurrent HTTP requests to your RAD Server.
• MaxUsers – the maximum number of RAD Server users allowed in the RAD Server Database. This
value depends on the type of RAD Server license you have.
[Server.Limits]
MaxConnections=
;# Set MaxConnections=10 to limit maximum concurrent HTTP requests. Default is 32.
MaxUsers=
;# Set MaxUsers=3 to limit the number of users in the EMS database. This value is
only used
;# when less than the maximum users permitted by the EMS run time license.
The Authentication Configuration section allows modification of authentication for your RAD Server. This
section includes:
• MasterSecret – this key authorizes any request to have complete access over all RAD Server
Resources and all RAD Server data that is stored in the RAD Server Database. (update any user in
the RAD Server Database, for example).
• AppSecret – this key authorizes any request to access any authorized RAD Server Resource
endpoints from a RAD Server based client application.
• ApplicationID – the RAD Server will reject any request from a RAD Server based client application
that does not match the ApplicationId. This identifier can be used to differentiate between your
RAD Servers.
[Server.Keys]
MasterSecret=
;# MasterSecret may be blank. If blank then the EMS server will not support
;# MasterSecret authentication.
;# HTTP 401 (Unauthorized) is raised if a request contains an incorrect MasterSecret
AppSecret=
;# AppSecret may be blank. If AppSecret is not blank all requests must include the
AppSecret.
;# HTTP 401 (Unauthorized) is raised if a request does not contain a correct
AppSecret
ApplicationID=
;# ApplicationID may be blank. If ApplicationID is not blank, all requests must
include the ApplicationID.
;# HTTP 404 (not found) is raised if a request does not contain a correct
ApplicationID
The Developer Server Connection contains the default information for the connection to your RAD Server
when used in developer mode. This section includes the following settings:
• Port – defines the connection port for the HTTP request to your RAD Server.
• HTTPS - enables HTTPS support for your RAD Server. If enabled, you need to install OpenSSL, NSS,
LibreSSL, or some other security library and configure the server certification file information.
• CertFile – contains the absolute path to the self-signed certification file (.pem file).
• RootCertFile – has the absolute path to the CA certification file (.pem file). If you use a self-signed
certificate, leave this blank.
• KeyFile – contains the absolute path to the self-signed key file (.pem file).
• KeyFilePassword – contains the password set to use the certification file.
[Server.Connection.Dev]
Port=8080
;# The following options enable HTTPS support.
; HTTPS=1
;# Set HTTPS=1 to enable HTTPS, HTTPS=0 to disable.
; CertFile=
; RootCertFile=
;# When using a self-signed certificate, RootCertFile is left blank.
; KeyFile=
; KeyFilePassword=
Use this section to modify the permission to allow different domains (outside the RAD Server domain) to
make HTTP requests to the public RAD Server API. This section includes:
CrossDomain – specify a list of domains that are allowed to make cross domain HTTP requests to the
RAD Server API. To allow any domain, use the wildcard value *.
[Server.APICrossDomain]
;# Write here the domains allowed to call the API. Used for Cross-Domains
;# Set CrossDomain=* to allow access to any domain.
CrossDomain=
Use the Server.Threads.Dev section of the configuration file to control how the EMSDevServer manages
threads for incoming requests. Included in this section are:
• ThreadPool – set to one to enable the thread pool scheduler, zero to disable.
• ThreadPoolSize – sets the number of threads that are available to handle requests.
• ListenQueue – indicates how many requests can be queued when all threads in the pool are busy.
• KeepAlive – set to one to enable HTTP connections to keep alive, set to zero to disable.
[Server.Threads.Dev]
;# The following options control how EMSDevServer manages threads to handle requests
;#
;# Thread pool options
; ThreadPool=1
;# Set ThreadPool=1 to enable thread pool scheduler, ThreadPool=0 to disable.
; ThreadPoolSize=5
;# ThreadPoolSize indicates how many threads are available to handle requests
;#
;# Queueing options
; ListenQueue=100
;# ListenQueue indicates how many requests can be queued when all threads are busy
;#
;# Connection options
; KeepAlive=1
;# Set KeepAlive=1 to enable HTTP connections to keep alive, KeepAlive=0 to disable.
The Console Login section defines the username and password for using the RAD Server console.
[Console.Login]
UserName=consoleuser
Password=consolepass
This section defines the cookie names for the user and RAD Server console. These two settings can be
left blank if cookies are not used.
[Console.Cookies]
User=
Console=
This setting is used to enable the EdgeModules menu options in the Console UI.
[Console.DisplayOptions]
;# Set ShowEdgeModules=1 to enable EdgeModules menu options, ShowEdgeModules=0 to
disable.
ShowEdgeModules=1
This section contains connection settings for the RAD Server Console Server’s port, HTTPS, CertFile,
RootCertfile, KeyFile, and KeyFile password
[Console.Connection.Dev]
Port=8081
;# The following options enable HTTPS support.
; HTTPS=1
;# Set HTTPS=1 to enable HTTPS, HTTPS=0 to disable.
; CertFile=
; RootCertFile=
;# When using a self-signed certificate, RootCertFile is left blank.
; KeyFile=
; KeyPassword=
This section contains settings for the number of rows and date format to display.
[Console.Browser]
LimitRows=15
DateFormat=mm/dd/yy
This section defines the path settings where the Development RAD Server Console will look for the
Resource Files and Web Files.
[Console.Paths.Dev]
ResourcesFiles=c:\program files (x86)\embarcadero\studio\20.0\ObjRepos\EN\EMS
; WebFiles=
;# When WebFiles is left blank, DevConsole will use ResourcesFiles as WebFiles path
;# If WebFiles is used the Web Server(e.g. IIS) should include in the HTTP-Response-
Header 'Access-Control-Allow-Origin' to allow cross-domain request (e.g 'Access-
Control-Allow-Origin: *')
This section defines the path settings where the IIS production RAD Server Console will look for the
console’s Resource Files and Web Files.
[Console.Paths.ISAPI]
ResourcesFiles=
; WebFiles=
;# When the webresources folder is in the same folder as the .dll, WebFiles is left
blank, otherwise URL to the files (e.g. WebFiles=http://localhost )
;# If WebFiles is used the Web Server (e.g. IIS) should include in the HTTP-
Response-Header 'Access-Control-Allow-Origin' to allow cross-domain request (e.g
'Access-Control-Allow-Origin: *')
Use this section to define the directory path settings where the Apache production RAD Server Console
will look for the console’s Resource Files and Web Files.
[Console.Paths.Apache]
ResourcesFiles=
;WebFiles=
This section specifies the path and description for any extension packages you create to register custom
resource endpoints.
[Server.Packages]
This section is used to configure the Google Cloud Messaging (GCM) settings for your RAD Server
application to support push notifications. In the EMSServer.ini file, go to the [Server.Push.GCM] section.
There is one item in this section:
• APIKey: The API Key obtained when Setting Up the Messaging Service.
[Server.Push.GCM]
;# This section is for Google Cloud Messaging (GCM) settings.
;# These settings are needed to send push notifications to an Android device
ApiKey=
Use this section to configure Apple Push Notification service (APNs) settings for the RAD Server
application to support push notifications to Apple devices. This section includes the following settings:
• CertificateFileName – name of your Apple push notification certificate file (.p12 or .pem file).
• CertificatePassword – contains the password for your certificate file if there is one.
• ProductionEnvironment – this value tells whether the certificate has been created for a
development or production environment.
[Server.Push.APNS]
;# This section is for Apple Push Notification Service (APNs).
;# These settings are needed to send push notifications to an iOS device
CertificateFileName=
;# Name of .p12 or .pem file
CertificateFilePassword=
;# Password of certificate file. Leave blank if file does not have a password.
ProductionEnvironment=
;# Set ProductionEnvironment=1 when the certificate has been created for production.
;# Set ProductionEnvironment=0 when the certificate has been created for
development.
;# Default value is 0 (development).
This section contains settings for the authorization requirements for the server application’s resources
and endpoints. Authorization can be setup up based on built-in resources like Users and on custom
resources that you create. Examples are included with their JSON attributes for Users and Resources.
[Server.Authorization]
;# This section is for setting authorization requirements for resources
;# and endpoints.
;# Authorization can be set on built-in resource (e.g.; Users) and on
;# custom resources.
This section allows you to set up redirects for custom resources to handle client application requests
instead of the resource identified in the URL. Redirects may apply to all endpoints in a custom resource
of to a specific endpoint. Examples are included to redirect all and specific endpoints.
[Server.Redirect]
;# This section is for setting resource redirects.
;# Redirects cause custom resources to handle a client request, rather than the
;# resource identified in the request URL.
;# A redirect may apply to all endpoints in a resource, or to a particular endpoint.
;# The destination resource must have an endpoint that handles the HTTP method
(e.g.; GET, POST, PUT, DELETE) and URL segments of the
;# client request. Endpoint names are not used to resolve the destination endpoint.
;# Examples:
;#
;# Redirect all endpoints of the built-in resource "Users" to the custom resource
"MyUsers"
;Users={"destination":"MyUsers"}
;#
;# Redirect specific endpoints to the custom resource "MyUsers"
;Users.LoginUser={"destination":"MyUsers"}
;Users.SignupUser={"destination":"MyUsers"}
This section sets up a proxy host, port, username, and password for Edge Module requests (if required).
[Server.EdgeHTTP]
;# Configure proxy for edge module requests
;ProxyHost=localhost
;ProxyPort=8888
;ProxyUserName=
;ProxyPassword=
This section provides the settings for tenant configurations for your RAD Server. You can select one of the
following tenant modes: Single Tenant mode and Multi-Tenant mode.
In the EMSServer.ini file, go to the [Server.Tenants] section. Entries in this section include:
• MultiTenantMode: specifies the mode for your RAD Server. To switch to the Multi-Tenant mode,
uncomment this line. If MultiTenantMode=1, the Multi-Tenancy is activated. If
MultiTenantMode=0, RAD Server works in the Single Tenant mode.
• DefaultTenantId: changes the default TenantId to the custom one in the Single Tenant mode.
• TenantIdCookieName: specifies the custom cookie name to store the TenantId in RAD Server
Console.
For more information about multi-tenancy, please see the RAD Server Multi-Tenancy Support docwiki
topic.
[Server.Tenants]
;# This section defines settings for Single or Multi-Tenant modes.
;#
;# The MultiTenantMode option is used to turn on the Multi-Tenant mode.
;# If the Multi-Tenant mode is turned on, then TenantId and TenantSecret is required
to access EMS Server.
;MultiTenantMode=1
;#
;# Default Tenant is used only in the Single Tenant mode.
;DefaultTenantId=00000000-0000-0000-0000-000000000001
;#
;# Define custom cookie name to store TenantId in EMS Console.
;TenantIDCookieName=TenantID
The Resources string setting defines a root path (prefix) for the RAD Server application’s URLs.
[Server.Roots]
;# This section is for specifying root paths
;#
;# Specifies the root path for resources
;Resources=API
Setting Resources=AshlandSoftware (or some other string), for example, defines that all RAD Server
application URLs must be started with that string before the text of any resource strings. For example:
Using the http://localhost:8087/AshlandSoftware/version URL will return the RAD Server version JSON
information.
Figure 61: Using the root path resources string and the version
resource GetVersion endpoint.
Figure 62: Using the root path resources string and the GetItem endpoint.
The Server.PublicPaths section is used to identify the directories where static files are located and defines
a URL path. Each entry is defined as a JSON object and the number of entries is unlimited. In the
EMSServer.ini file go to the [Server.PublicPaths] section. The properties of the JSON object include:
[Server.PublicPaths]
See Also
For RAD Server applications to run on IIS, use the DLL versions of RAD Server Engine and RAD Server
Console. These DLLs (EMSServer.dll and EMSConsole.dll) are located in the following RAD Studio folders:
Use the following steps to install Microsoft IIS 7, the RAD Server or Console, and InterBase 2017 server
with a RAD Server license.
To run InterBase and your RAD Server application on the same machine or on a separate production
machine you’ll need to install and register a new instance of InterBase 2017 using a valid RAD Server
license (instead of the developer license that is included in RAD Studio) by following these steps:
Figure 63: InterBase install setup program – Figure 64: Choose the InterBase 64-bit
choose to install InterBase 2017. version to install.
3. Choose the port number and instance name for InterBase to use. For example, port 3051 and
RADServer.
4. Set the destination folder of the RAD Server Interbase instance (for 64-bit Windows InterBase this
will default to the C:\Program Files\Embarcadero\InterBase folder).
5. Register the RAD Server InterBase instance with a valid RAD Server license.
Figure 70: Register using a valid RAD Figure 71: Registration is successful and the
Server serial number. InterBase 2017 instance has been installed.
6. Start the RAD Server instance of InterBase 2017 server. Choose Start | Programs | Embarcadero
InterBase 2017 | 64-bit instance = RADServer | InterBase Server Manager. If you want InterBase
to run as a Windows service (the default) check that box. If you want InterBase to run when your
computer starts, click the Automatic radio button. Then click the Start button.
7. Follow these steps to prepare the production server to test and use the InterBase RAD Server
instance and use EMSDevServer.EXE to create the RAD Server database and configuration file.
• Copy the 64-bit EMSDevServer.exe to the production server in a folder called c:\installs\
DevServerEXE
• Copy the files in the RAD Studio Redist/win64 folder to the production server in a folder called
c:\Redist
• Edit the system path environment variable on the production server to add the c:\Redist and
c:\Program Files\InterBase\bin folders.
• Copy the RAD Server template and web resources files on the development computer from
C:\Program Files (x86)\Embarcadero\Studio\20.0\ObjRepos\en\EMS to the production server
folder called c:\installs\ObjRepos\EMS (EMSDevServer.EXE will look for the template and web
resource files in an ObjRepos\EMS subfolder under the same parent folder you place the
EMSDevServer folder).
• Make sure that the InterBase server with RAD Server license is started on the production
server.
• Copy the ibclient64.dll from the c:\Program Files\InterBase\bin to the c:\Windows\System32
folder.
8. Run the EMSDevServer.exe (as you did in the first RAD Server development configuration) to
setup the production RAD Server configuration file and InterBase RAD Server database. The
following screens show the steps:
Figure 74: RAD Server Setup Wizard - Set Figure 75: RAD Server Setup Wizard - Choose
connection parameters for RAD Server. to generate sample data.
Figure 76: RAD Server Setup Wizard - Setup the Figure 77: RAD Server Setup Wizard - Review the
console username and password. files and registry key that will be created.
Figure 78: RAD Server Setup Wizard - Figure 79: Windows Firewall - Allow access for
Confirmation of the files that have been created. the RAD Server.
The RAD Server wizard will create two files in the default folder under the Public Documents folder.
Figure 81: RAD Server Setup Wizard - Two files created in the Public
Documents folder.
To instal IIS, open the Windows Control Panel and under Programs and Features, click Turn Windows
features on or off.
Figure 82: Use the Control Panel | Programs and Features | Windows
Features to add IIS.
Next, expand the Internet Information Services node of the Windows Features dialog box and set the
check boxes for the following IIS features:
When all of the required features have been selected, click the OK button to start the IIS installation.
Depending on the speed of your computer, the installation will take approximately 3 minutes. During the
installation, a folder named inetpub (containing several subfolders and files) is created as the starting
point of the web server.
After installing IIS 7, use a browser with the http://localhost/ URL to make sure IIS is running.
Check your firewall settings and add, if necessary, an exception for port 80.
Step 3: Create New Sites for RAD Server Engine and RAD Server
Console
Create a wwwroot subfolder named RADServer. This subfolder will contain the RAD Server run time
libraries and application package files. Create a wwwroot subfolder named RADConsole. This sub-folder
will contain the RAD Server Console run time libraries and required web resources files.
Create a folder, c:\data, for the RAD Server Engine and RAD Server Console to share the RAD Server
InterBase database. Copy the emsserver.ib file from C:\Public\Public Documents\Embarcadero\EMS to
c:\data.
Copy the required binary files (either 32-bit or 64-bit) into the c:\inetpub\wwwroot\RADServer and
RADConsole subfolders. You’ll find these files in a subfolder under your RAD Studio installation:
To use RAD Server Engine with extension application packages, copy the following DLLs and package files
(BPLs) to your c:\inetpub\wwwroot\RADServer subfolder:
If the application packages use FireDAC with a database management system other than InterBase, copy
the additional FireDAC driver package files, such as FireDACSqliteDriver260.bpl for SQLite, to the
wwwroot/RADServer sub-folder.
To use RAD Server console, copy the following DLLs and package files (BPLs) to your c:\inetpub\
wwwroot\RADConsole subfolder:
To use the RAD Server console, copy the webresources folder from C:\Program Files (x86)\Embarcadero\
Studio\20.0\ObjRepos\en\EMS to c:\inetpub\wwwroot\RADConsole.
[Console.Paths.ISAPI]
ResourcesFiles=C:\inetpub\wwwroot\RADConsole
WebFiles=
;# When the webresources folder is in the same folder as the .dll, WebFiles is left
blank, otherwise URL to the files ( e.g.WebFiles=http://localhost )
;# If WebFiles is used the Web Server (e.g. IIS) should include in the HTTP-
Response-Header 'Access-Control-Allow-Origin' to allow cross-domain request (e.g
'Access-Control-Allow-Origin: *')
Whenever changes are made to emsserver.ini, restart the IIS server for the changes to take effect.
The next step is configuring IIS so that the ISAPI DLLs for the RAD Server Engine (emsserver.dll) and RAD
Server console (emsconsole.dll) can be used on your production server.
Open Internet Information Service Manager by using the Control Panel | System and Security |
Administrative Tools (this operation requires Privileged mode). You can also type Inetmgr on the
Windows Search programs and files to open the IIS Manager.
Select the folder RADServer under Sites > Default Web Site.
Right-click on the RADServer folder and select Convert to Application. This brings up the Add Application
dialog box.
Select ISAPI-dll (it appears grayed out). Click Edit from the Actions panel.
On the Executable (optional) field enter the path to the dll file and click the “…” open button and
navigate to the RADServer subfolder where the emsserver.dll is located (or just type in the full path
including the DLL name C:\inetpub\wwwroot\RADServer\emsserver.dll.
Click the Edit Feature Permissions… in Actions panel for the RADServer site. The Edit Feature Permission
dialog opens. Check Execute.
Click OK to commit the changes. You’ll see that ISAPI-dll has now been added to the Handler Mappings
enabled list.
Follow the same IIS site setup steps for the RAD Server Console in the c:\inetpub\wwwroot\RADConsole
folder. The ISAPI DLL to enable is emsconsole.dll.
Click the root node from the Connections tree. Double-click the ISAPI and CGI Restrictions icon.
Figure 96: IIS Root note - double click on the ISAPI and CGI Restrictions icon.
Click Edit Feature Settings … in the Actions panel. Check the Allow unspecified ISAPI modules option. This
option allows any ISAPI dll to be executed under IIS.
Figure 97: IIS ISAPI and CGI Restrictions Edit Feature Settings
Click OK. See that the RAD Server Engine and RAD Server Console DLLs (in their separate folders) are
allowed.
Figure 98: Make sure that RAD Server and RAD Server Console are
allowed.
With the RADServer and RADConsole sites created and enabled for use, you can check the settings in the
IIS applicationHost.config file at C:\Windows\System32\inetsrv\config\applicationHost.config
<isapiCgiRestriction notListedIsapisAllowed="true">
<add path="C:\inetpub\wwwroot\RADServer\emsconsole.dll" allowed="true"
description="RAD Server Console" />
<add path="C:\inetpub\wwwroot\RADServer\emsserver.dll" allowed="true"
description="RAD Server" />
</isapiCgiRestriction>
This step is only required if IIS x64 was installed and 32 bit ISAPI DLL support is required. Follow the next
several steps to use 32-bit versions of RAD Server, RAD Server Console and application packages:
To allow HTTP requests from different domains for a web server that is hosting the web file resources of
RAD Server Console, set up the HTTP-Response-Header.
• Go to C:\inetpub\wwwroot and create a new folder, for example Web files folder.
• Paste the web files resources folders under webfilesresources.
• Note: You can not change the webresources folder name.
• Open Internet Information Service Manager.
• Select the Web files folder (webfilesresources) under Sites > Default Web Site.
• Double-click HTTP Response Headers.
• Click Add in the Actions panel.
• Enter one of the following configurations (Name: Value):
• Access-Control-Allow-Origin: *
• (More restrictive option) Access-Control-Allow-Origin: http://domain:port/
• Click OK to commit the changes.
RAD Server application package files are compiled into folders depending on the project settings. The
default Delphi package output and C++ final output directories are:
• For Delphi:
There are several ways to deploy the required RAD Server application and run-time DLL files to the
production server. Three common transfer methods are:
Copy the Windows 64-bit compiled RAD Server extension package files (for example,
MyFirstDelphiRADServerPackage.bpl) to the production IIS Server’s c:\inetput\wwwroot\RADServer
folder.
On the Windows IIS server, the RADServer folder now contains the following files:
Edit the emsserver.ini file to add each of your RAD Server extension packages under the
[Server.Packages] section.
[Server.Packages]
;# This section is for extension packages.
;# Extension packages are used to register custom resource endpoints
;c:\mypackages\basicextensions.bpl=mypackage description
c:\inetpub\wwwroot\RADServer\MyFirstDelphiRADServerPackage.bpl=First Test Demo
To make sure that the production IIS server and RAD Server are working, use the following URLs in your
browser.
Click the Login link, type in the console username and console password to get to the console home
page.
Continue developing RAD Server package applications now that the production server is set up with IIS,
InterBase, RAD Server Engine, and RAD Server Console. Copy the new (or updated) application BPL files
along with any additional DLLs and BPLs required. Remember to keep the RAD Server configuration file
(c:\wwwroot\radserver\emsserver.ini) [Server.Packages] section up to date.
See Also
Installing the RAD Server or the RAD Server Console on a Production Environment on Windows
http://docwiki.embarcadero.com/RADStudio/Rio/en/
Installing_the_RAD_Server_or_the_RAD_Server_Console_on_a_Production_Environment_on_Windows
Configuring Your RAD Server Engine or RAD Server Console Server on Windows
http://docwiki.embarcadero.com/RADStudio/Rio/en/
Configuring_Your_RAD_Server_Engine_or_RAD_Server_Console_on_Windows
Tech Tip: How do I secure RAD Server for production deployment – by Eli M.
https://community.idera.com/developer-tools/b/blog/posts/tech-tip-how-do-i-secure-rad-server-for-
production-deployment
InterBase Documentation
http://docwiki.embarcadero.com/RADStudio/Rio/en/InterBase
InterBase Downloads
https://downloads.embarcadero.com/free/interbase
• To create a stand-alone RAD Server, see the RAD Server Stand-alone Installation section.
• To create RAD Server for Apache, see the Setting Up RAD Server for Apache section.
Prerequisites
In a terminal window, run the shell script installer for InterBase 2017 Server 64-bit on Linux.
Choose to install the 64-bit edition and click the Next button.
Choose to install the InterBase server and client, and click the Next button.
Choose to install InterBase as a multi-instance. Set a specific TCP port number and Instance Name for
RAD Server to use and click the Next button.
The License Manager will display after the installation completes. Click on the Serial menu and choose
the Add… menu item. In the dialog box that displays, enter your RAD Server Site License file for InterBase
and click the Ok button.
Right-mouse click on the RAD Server key and choose the Register menu item from the menu.
Figure 118: Right mouse click on the RAD Server serial number and select
Register.
Key in your Embarcadero account ID (or email) and password and click the Register button. If everything
is correct, a successful Registration message will display.
INTERBASE=/opt/interbase
Confirm that the RADServer instance and port are defined in the /etc/Services file
To start the InterBase 2017 Server go to the bin directory for the directory created during the installation
process: cd /opt/interbase/bin. Run the Server Manager as root: sudo ./ibmgr. Type start.
InterBase can also be set up as a service so that it runs when Linux is started. Use the following
commands in a terminal window.
Copy the ibserverd script file to a version for the server instance you installed. In the InterBase installed
examples directory:
Setup the automatic service launch by executing the above script as 'sudo' or 'root'.
The 2nd argument is the install folder, and the 3rd argument is the instance name. When you restart the
system, the service should start automatically as long InterBase is properly licensed.
Check to make sure InterBase is set to start as a service on the next reboot or startup.
When running InterBase as a service, the InterBase server starts automatically whenever the machine is
running in a multi-user mode. To remove InterBase as a service, run:
The RAD Server files LinuxEMSServer.tar and ems_install.sh can be found in the following location in the
RAD Studio folder: Linux 64-bit: C:\Program Files (x86)\Embarcadero\Studio\20.0\EMSServer
Figure 123: RAD Server install files in the RAD Studio directory.
Copy this folder and its two files to your Linux server.
◦ rtl\bplFireDACIBDriver260.so
◦ rtl\bplFireDACCommon260.so
◦ rtl\bplxmlrtl260.so
◦ rtl\bplemsserverapi260.so
If the RAD Server application uses FireDAC with other database management systems besides InterBase,
then FireDAC driver packages for those databases, such as bplFireDACSqliteDriver250.so for SQLite, will
be needed.
RAD Server Engine uses the following default paths when you finish setting it up:
Ensure that libcurl3 is installed. To install it using the command: apt install libcurl3
To install a stand-alone RAD Server, run the ems_install.sh shell script file.
The install shell script will create a directory, /usr/lib/ems, containing the EMSDevServerCommand,
EMSDevConsoleCommand along with several run time library (.so) files required for the command files
to execute.
Figure 126: Directory and files created by the RAD Server install shell script.
Start the RAD Server stand-alone server: sudo ./EMSDevServerCommand -start. Starting the
EMSDevServer for the first time will launch the RAD Server configuration wizard to help set up the
emsserver.ini configuration file and emsserver.ib database file.
Figure 127: Starting RAD Server for the first time will create the configuration file.
Type y and enter to continue. Set the Server Instance to RADServer (or whatever the RAD Server
InterBase instance name is called). For all of the other set up options press Enter. The configuration file
wizard will review the configuration options.
Type n if the configuration options are correct. The emsserver.ini and emsserver.ib files are created and
RAD Server starts execution on port 8080. The configuration file can always be manually edited.
Click the Login link and type in the console username and password (consoleuser, consolepass)
EMSDevServerCommand and EMSDevConsoleCommand can be used for developing and testing Linux
RAD Server applications without using Apache. The next step is to set up and test RAD Server and
Delphi/C++ compiled application modules to run in production mode on Linux and Apache.
Use the InterBase iSQL command (in the /opt/interbase/bin directory) to make sure that RAD Server will
be able to connect to the emsserver.ib database file.
Configure the Apache HTTP Server to load the Apache RAD Server (libmod_emsserver.so) and Apache
RAD Server Console (libmod_emsconsole.so) modules. Depending on which distribution of Linux you are
deploying on, follow the steps below.
Edit Apache's httpd.conf file. Add the following lines to load the RAD Server Apache server module
(libmod_emsserver.so) and the RAD Server Apache console module (libmod_emsconsole.so).
Add the Location tags to create a container where you can specify access control rules for a given URL.
<Location /ems-server>
SetHandler libmod_emsserver-handler
</Location>
<Location /ems-console>
SetHandler libmod_emsconsole-handler
</Location>
Create a new file called ems.conf in Apache's mods-available directory, to hold appropriate Location tags,
used to specify access control rules for a given URL.
<Location /ems-server>
SetHandler libmod_emsserver-handler
</Location>
<Location /ems-console>
SetHandler libmod_emsconsole-handler
</Location>
If there is a need to disable the RAD Server modules, use a2dismod: a2dismod ems
Make sure that Apache can find the 64-bit SO file for InterBase. Create a symbolic link for the libgds.so
file to point to the libgds.so.0 version
Restart Apache Server as appropriate to your Linux distribution to load the newly configured RAD Server
settings and modules.
To test that RAD Server is running correctly, use a browser to bring up the RAD Server version number.
Build and test Delphi RAD Server applications on Windows. Change the target platform to Linux and build
the Linux 64-bit version of the package file.
Copy the compiled resource module (e.g. bplMyFirstDelphiRADServerPackage.so) found in the C:\Users\
Public\Documents\Embarcadero\Studio\20.0\Bpl\Linux64 directory to the /usr/lib/ems directory on
Linux.
Copy any required run-time libraries (the files that display in the Requires note of the project) to the
/usr/lib/ems directory on Linux. The redistributable run time libraries for Linux are found in the C:\
Program Files (x86)\Embarcadero\Studio\20.0\Redist\linux64 directory.
The MyFirstDelphiRADServerPackage will need the additional run time libraries copied to the
/usr/lib/ems directory
• bplrtl260.so
• bplemsserverapi260.so
Edit the /etc/ems/emsserver.ini file Server.Packages section and add the custom resource module.
[Server.Packages]
;# This section is for extension packages.
;# Extension packages are used to register custom resource endpoints
/usr/lib/ems/bplMyFirstDelphiRADServerPackage.so=My Linux RAD Server package
Test the first Delphi RAD Server application package (compiled for 64-bit Linux) is running correctly with
RAD Server + Apache using the URL: http://192.168.1.143/ems-server/test/Hello from Delphi for Linux
Now that the production Linux server is set up with RAD Server Engine and RAD Server Console, continue
developing Delphi RAD Server package applications (stay tuned to the Embarcadero Road Map news for
future support for C++). Copy the new (or updated) application package files along with any additional
run time libraries that are required (the list will be found in the Requires node in the project manager).
Remember to keep the RAD Server configuration file (/usr/lib/ems/emsserver.ini) [Server.Packages]
section up to date.
See Also
Installing the RAD Server or the RAD Server Console on a Production Environment on Linux
http://docwiki.embarcadero.com/RADStudio/Rio/en/
Installing_the_RAD_Server_or_the_RAD_Server_Console_on_a_Production_Environment_on_Linux
Configuring Your RAD Server Engine or RAD Server Console Server on Linux
http://docwiki.embarcadero.com/RADStudio/Rio/en/
Configuring_Your_RAD_Server_Engine_or_RAD_Server_Console_on_Linux
Tech Tip: How do I secure RAD Server for production deployment – by Eli M.
https://community.idera.com/developer-tools/b/blog/posts/tech-tip-how-do-i-secure-rad-server-for-
production-deployment
The RAD Server configuration file (emsserver.ini) section labeled [Server.PublicPaths] contains
information and examples for setting up public paths of web content. The entries can include:
By default, the RAD Server configuration file will contain the following:
[Server.PublicPaths]
;# Identify directories that contain public files, such as .html
;#
;# The following entries define two different virtual directories ("images" and
"content")
;# that may be used to access static files. The "directory" value indicates the
physical
;# location of the static files. The optional "default" value indicates a file
;# that will be dispatched by default when browsing to the root of the virtual
directory.
;# The optional "mimes" value is an array of MIME file type masks. And optional
"extensions"
;# value is an array of file extensions. Only these files will be accessible from
this directory.
;# The optional "charset" value specifies default charset for the files in the
directory.
;Path1={"path": "images", "directory": "C:\\web\\images\\", "default": "index.html",
"mimes": ["image/*"]}
;Path2={"path": "content", "directory": "C:\\web\\content\\", "default":
"index.html", "extensions": ["js", "html", "css"], "charset": "utf-8"}
Server Public Paths entries have a unique arbitrary name that precedes the equal sign. The JSON based
entries map a computer directory to the types of web information that a RAD Server application can use.
Each entry contains a “path”: “value”, directory where files are found, optional default file to dispatch
upon browsing, optional array of MIME file type masks, optional array of file extensions, and optional
character set encoding for the files in the directory.
A Simple Example
For this example, add the following path entries to the RAD Server configuration file in the
[Server.PublicPaths] section:
Create the C:\WebAssets\Content and C:\WebAssets\Images directories. Create an index.html file in the
C:\WebAssets\Content directory containing the following HTML:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.ajax({url: "/WebProperties", success: function(result){
$("#div1").html(result);
}});
});
});
</script>
</head>
<body>
<h2>RAD Server JS + Service</h2>
<button>Get RAD Server Content</button>
<P></p>
<div id="div1">RAD Server GET method result will appear here</div>
</body>
</html>
Choose Create package with resource from the RAD Server Package Wizard. Set the resource name to
WebProperties and File type of Data Module. Select the Get and GetItem resource endpoints. Click the
Finish button.
When the wizard finishes, the Delphi and C++ project files will look like the following:
Edit the code in the implementation of the Get and GetItem endpoints. The code for the RAD Server
resource unit is as follows:
Delphi:
unit ResourceUnit;
interface
uses
System.SysUtils, System.Classes, System.JSON,
EMS.Services, EMS.ResourceAPI, EMS.ResourceTypes;
type
[ResourceName('WebProperties')]
TWebPropertiesResource1 = class(TDataModule)
published
procedure Get(const AContext: TendpointContext;
const ARequest: TEndpointRequest; const AResponse: TEndpointResponse);
[ResourceSuffix('{item}')]
procedure GetItem(const AContext: TendpointContext;
const ARequest: TEndpointRequest; const AResponse: TEndpointResponse);
end;
implementation
{%CLASSGROUP 'System.Classes.TPersistent'}
{$R *.dfm}
initialization
Register;
end.
C++:
//---------------------------------------------------------------------------
#pragma hdrstop
#include "ResourceUnit.h"
#include <memory>
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma classgroup "System.Classes.TPersistent"
#pragma resource "*.dfm"
//---------------------------------------------------------------------------
__fastcall TWebPropertiesResource1::TWebPropertiesResource1(TComponent* Owner)
: TDataModule(Owner)
{
}
Run the RAD Server application. The “Public Path” entries show up in the RAD Server application log.
Figure 145: Web Properties Demo - RAD Server application log with public
path entries.
Click the Open Browser button. Change the URL to localhost:8087/content to bring up the index.html file.
Click the Get RAD Server Content button to have the JavaScript code call the GET method and return the
result.
The RAD Server application’s log shows that the WebProperties Get method was executed.
Figure 148: Web Properties Demo - RAD Server application log shows the GET
method executed by the HTML button click.
Chapter 12, Multiple Accept Types with EndpointProduce, contains another example that uses a
[Server.PublicPaths] section path entry.
See Also
Marco Cantu blog: RAD Server Support for Web Files in RAD Studio 10.2.3
http://blog.marcocantu.com/blog/2018-march-rad-server-files-10.2.3.html
• JSON Objects Framework – creates temporary objects to read and write JSON data.
• Readers and Writers JSON Framework – allows you to read and write JSON data directly.
The JSON objects framework requires the creation of a temporary object to parse or generate JSON data.
To read or write JSON data, you have to create an intermediate memory object such as TJSONObject,
TJSONArray, or TJSONString before reading and writing the JSON.
The Readers and Writers JSON Framework, allows applications to read and write JSON data directly to a
stream, without creating a temporary object. Not having to create a temporary object to read and write
the JSON provides better performance and improved memory consumption.
Using JSONValue
Use the JSON Objects Framework to create JSON strings by assembling them in code. JSONValue is the
ancestor class for all the JSON classes used for defining JSON string, object, array, number, Boolean, true,
false, and null values. Included in the RAD Studio JSON implementation are the following classes and
methods:
• Parse – method to parse a JSON data stream and store the encountered JSON pairs into a
TJSONObject instance.
• ParseJSONValue – method to parse a byte array and create the corresponding JSON value from
the data.
• AddPair method – Adds a new JSON pair to a JSON object.
• GetPair method – Returns the key-value pair that has the specified I index in the list of pairs of a
JSON object, or nil if the specified I index is out of bounds.
• GetPairByName method – returns a key-value pair, from a JSON object, that has a key part
matching the specified PairName string, or nil if there is no key matching PairName.
• SetPairs – Defines the list of key-value pairs that this JSON object contains.
• FindValue – Finds and returns a TJSONValue instance located at the specified Apath JSON path.
Otherwise, returns nil.
• Get Value – Returns the value part from a key-value pair specified by the Name key in a JSON
object, or nil if there is no key that matches Name.
• Pairs – Accesses the Key-value pair that is located at the specified Index in the list of pairs of the
JSON object, or nil if the specified Index is out of bounds.
• GetCount – Returns the number of key-value pairs of a JSON object.
• Add – Adds a non-null value given through the Element parameter to the current element list.
• Get – Returns the element at the given index in the JSON array.
• Pop – Removes the first element from the JSON array.
• Size – Returns the size of the JSON array.
• ToBytes – Serializes the current JSON array content into an array of bytes.
• ToString – Serializes the current JSON array into a string and returns the resulting string.
The following RAD Server application implements a Get endpoint that uses several of the JSON classes to
create, parse, and display the results of JSONObject, JSONArray and JSONValue.
Delphi:
JSONColor.AddPair('name', 'red');
JSONColor.AddPair('hex', '#ff0000');
JSONColor.AddPair('name', 'blue');
JSONColor.AddPair('hex', '#0000FF');
JSONArray := TJSONArray.Create();
JSONArray.Add(JSONColor);
JSONObject := TJSONObject.Create();
JSONObject.AddPair('colors', JSONArray);
JSONValue := TJSONObject.Create();
JSONValue := TJSONObject.ParseJSONValue(JSONObject.ToJSON);
AResponse.Body.SetValue(
TJSONString.Create(
JSONColor.ToJSON
+ ','
+ JSONObject.ToJSON
+ ',{"name":"' + JSONValue.GetValue<string>('colors[0].name')
+ '","hex":"'+ JSONValue.GetValue<string>('colors[0].hex')
+ '"}'
), True);
end;
C++:
The following VCL client application uses several of the JSONValue based classes to create, parse, and
display the results of TJSONArray and TJSONObject based operations.
Delphi:
unit MainUnit;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TForm2 = class(TForm)
Button1: TButton;
Memo1: TMemo;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form2: TForm2;
implementation
uses
JSON;
{$R *.dfm}
JSONColor := TJSONObject.Create();
JSONColor.AddPair('name', 'red');
JSONColor.AddPair('hex', '#f00');
JSONColor.AddPair('mBoolean',TJSONBool.Create(mBoolean));
JSONArray := TJSONArray.Create();
JSONArray.Add(JSONColor);
JSONObject := TJSONObject.Create();
JSONObject.AddPair('colors', JSONArray);
JSONObject.AddPair('mBoolean',TJSONBool.Create(mBoolean));
Memo1.Lines.Clear();
Memo1.Lines.Add('JSONColor: '+JSONColor.ToJSON);
Memo1.Lines.Add('');
Memo1.Lines.Add('JSONObject: '+JSONObject.ToJSON);
Memo1.Lines.Add('');
JSONValue := TJSONObject.Create();
JSONValue := TJSONObject.ParseJSONValue(JSONObject.ToJSON);
Memo1.Lines.Add('colors[0]');
Memo1.Lines.Add('name: '+ JSONValue.GetValue<string>('colors[0].name'));
Memo1.Lines.Add('hex: '+ JSONValue.GetValue<string>('colors[0].hex'));
Memo1.Lines.Add('mBoolean: '+JSONValue.GetValue<string>('colors[0].mBoolean'));
end;
C++:
Memo1->Lines->Clear();
Memo1->Lines->Add("JSONColor: "+JSONColor->ToJSON());
Memo1->Lines->Add("");
Memo1->Lines->Add("JSONObject: "+JSONObject->ToJSON());
Memo1->Lines->Add("");
Memo1->Lines->Add("colors[0]");
Memo1->Lines->Add("name: "+JSONValue->GetValue<String>("colors[0].name"));
Memo1->Lines->Add("hex: "+JSONValue->GetValue<String>("colors[0].hex"));
Memo1->Lines→Add(
"mBoolean: "+JSONValue->GetValue<String>("colors[0].mBoolean"));
}
Using JSONWriter
Using JSONWriter simplifies RAD Server application development to craft custom JSON that delivers data
for programming language clients to consume. Use JSONWriter to start your JSON object, write a
property name and a value, and then keep writing properties and values until you finish the JSON object.
Here is an implementation of a Get endpoint that returns data using JSONWriter’s WriteStartArray,
WriteStartObject, WritePropertyName, WriteValue, WriteEndObject, WriteEndArray methods.
Setting the JSONWriter.Formatting property value to Indented will produce a clean looking response in
the Browser.
Delphi:
implementation
{%CLASSGROUP 'System.Classes.TPersistent'}
uses
System.JSON.Types;
{$R *.dfm}
AResponse.Body.JSONWriter.WriteStartObject;
AResponse.Body.JSONWriter.WritePropertyName('Test');
AResponse.Body.JSONWriter.WriteValue('Foo bar');
C++:
AResponse->Body->JSONWriter->WriteStartObject();
AResponse->Body->JSONWriter->WritePropertyName("Test");
AResponse->Body->JSONWriter->WriteValue("Foo bar");
JSONWriter can also be used with rows and columns of database data. Create a RAD Server package
application with Get and GetItem endpoints. Name the resource FireDAC. Add FDConnection, FDQuery,
and FDStanStorageJSONLink components. Connect to the Employee.GDB InterBase database. Set the SQL
property to select * from employee. The resource module should look like the following:
Here are the Get and GetItem endpoint implementations to return custom JSON for a database query.
Delphi:
interface
uses
System.SysUtils, System.Classes, System.JSON,
EMS.Services, EMS.ResourceAPI, EMS.ResourceTypes, FireDAC.Stan.Intf,
FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf,
FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys,
FireDAC.Phys.IB, FireDAC.Phys.IBDef, FireDAC.ConsoleUI.Wait,
FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt,
FireDAC.Stan.StorageJSON, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client,
FireDAC.Comp.BatchMove.JSON, FireDAC.Comp.BatchMove,
FireDAC.Comp.BatchMove.DataSet;
type
[ResourceName('FireDAC')]
TFireDACResource1 = class(TDataModule)
DatabaseConnection: TFDConnection;
EmployeeQuery: TFDQuery;
FDStanStorageJSONLink1: TFDStanStorageJSONLink;
EmployeeQueryEMP_NO: TSmallintField;
EmployeeQueryFIRST_NAME: TStringField;
EmployeeQueryLAST_NAME: TStringField;
EmployeeQueryPHONE_EXT: TStringField;
EmployeeQueryHIRE_DATE: TSQLTimeStampField;
EmployeeQueryDEPT_NO: TStringField;
EmployeeQueryJOB_CODE: TStringField;
EmployeeQueryJOB_GRADE: TSmallintField;
EmployeeQueryJOB_COUNTRY: TStringField;
EmployeeQuerySALARY: TFMTBCDField;
EmployeeQueryFULL_NAME: TStringField;
published
procedure Get(const AContext: TendpointContext;
const ARequest: TEndpointRequest; const AResponse: TEndpointResponse);
[ResourceSuffix('{item}')]
procedure GetItem(const AContext: TendpointContext;
const ARequest: TEndpointRequest; const AResponse: TEndpointResponse);
end;
implementation
{%CLASSGROUP 'System.Classes.TPersistent'}
uses
System.JSON.Types;
{$R *.dfm}
// using JSONWriter to craft custom JSON return for the selected employee row
AResponse.Body.JSONWriter.WriteStartObject;
for FieldIndex := 0 to EmployeeQuery.FieldCount-1 do begin
Aresponse.Body.JSONWriter.WritePropertyName(
EmployeeQuery.Fields[FieldIndex].FieldName);
Aresponse.Body.JSONWriter.WriteValue(
EmployeeQuery.FieldByName(
EmployeeQuery.Fields[FieldIndex].FieldName).AsString)
end;
end;
procedure Register;
begin
RegisterResource(TypeInfo(TFireDACResource1));
end;
C++:
DMUnit.h
#ifndef DMUnitH
#define DMUnitH
//---------------------------------------------------------------------------
#include <System.Classes.hpp>
#include <System.SysUtils.hpp>
#include <EMS.Services.hpp>
#include <EMS.ResourceAPI.hpp>
#include <EMS.ResourceTypes.hpp>
#include <Data.DB.hpp>
#include <FireDAC.Comp.Client.hpp>
#include <FireDAC.Comp.DataSet.hpp>
#include <FireDAC.ConsoleUI.Wait.hpp>
#include <FireDAC.DApt.hpp>
#include <FireDAC.DApt.Intf.hpp>
#include <FireDAC.DatS.hpp>
#include <FireDAC.Phys.hpp>
#include <FireDAC.Phys.IB.hpp>
#include <FireDAC.Phys.IBDef.hpp>
#include <FireDAC.Phys.Intf.hpp>
#include <FireDAC.Stan.Async.hpp>
#include <FireDAC.Stan.Def.hpp>
#include <FireDAC.Stan.Error.hpp>
#include <FireDAC.Stan.Intf.hpp>
#include <FireDAC.Stan.Option.hpp>
#include <FireDAC.Stan.Param.hpp>
#include <FireDAC.Stan.Pool.hpp>
#include <FireDAC.UI.Intf.hpp>
#include <FireDAC.Stan.StorageJSON.hpp>
//---------------------------------------------------------------------------
#pragma explicit_rtti methods (public)
class TFireDACResource1 : public TDataModule
{
__published:
TFDConnection *EmployeeConnection;
TFDStanStorageJSONLink *FDStanStorageJSONLink1;
TFDQuery *EmployeeQuery;
private:
public:
__fastcall TFireDACResource1(TComponent* Owner);
void Get(TEndpointContext* AContext, TEndpointRequest* Arequest,
TEndpointResponse* AResponse);
void GetItem(TEndpointContext* AContext, TEndpointRequest* Arequest,
TEndpointResponse* AResponse);
};
#endif
DMUnit.cpp
//---------------------------------------------------------------------------
#pragma hdrstop
#include "DMUnit.h"
#include <memory>
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma classgroup "System.Classes.TPersistent"
#pragma resource "*.dfm"
//---------------------------------------------------------------------------
__fastcall TFireDACResource1::TFireDACResource1(TComponent* Owner)
: TDataModule(Owner)
{
}
FieldIndex++) {
AResponse->Body->JSONWriter->WritePropertyName(
EmployeeQuery->Fields->Fields[FieldIndex]->FieldName);
AResponse->Body->JSONWriter->WriteValue(
EmployeeQuery->FieldByName(
EmployeeQuery->Fields->Fields[FieldIndex]
->FieldName)->AsString);
}
AResponse->Body->JSONWriter->WriteEndObject();
EmployeeQuery->Next();
}
AResponse->Body->JSONWriter->WriteEndArray();
}
The JSON output of the Get and GetItem method calls display in the browser windows below.
Figure 153: JSON output for the Employee table’s rows and columns.
See Also
JSON
http://docwiki.embarcadero.com/RADStudio/Rio/en/JSON
Tutorial: Using the REST Client Library to Access REST-based Web Services
http://docwiki.embarcadero.com/RADStudio/Rio/en/
Tutorial:_Using_the_REST_Client_Library_to_Access_REST-based_Web_Services
FireDAC includes components to access a database table information and produce the result as a JSON
string. Create a RAD Server application with a resource module. Add a FDConnection component and
connect it with the InterBase sample Employee.gdb database. Add a FDTable component and set its
Table property to the Employee table. Add a FDStanStorageJSONLink component to facilitate creating of
the JSON.
When building a RAD Server Delphi based application, a set of warnings may display and a dialog box will
emerge to allow the application package to be compatible with other installed packages.
Clicking the OK button will add the required package files to the requires section in the project. For C+
+Builder the required packages can be added manually (right-mouse click on the Requires node in the
project manager window and select Add Reference… from the displayed menu).
Figure 157: Delphi RAD Server FireDAC Figure 158: C++ RAD Server FireDAC
Memory Stream JSON project. Memory Stream JSON project.
Here is the RAD Server Get method implementation that uses a memory stream to send the JSON
response with employee table data.
Delphi:
C++:
Use a browser and the URL http://localhost:8087/FireDAC to get the response containing the JSON data
for the database’s employee table. The JSON contains much more information than just the data. Also
included in the response is metadata information about the table, columns, types, etc.
This definitely is not the simple JSON column and value output that other languages could consume
without parsing the response.
For a complex database, using approaches like those mentioned in the previous chapter and above
would involve writing a lot more code. Taking advantage of FireDAC’s FDBatchMove,
FDBatchMoveDataSetReader, and FDBatchMoveJSONWriter components greatly simplifies the creation
of the JSON response.
Use the RAD Server Package Wizard to create a new package project with Data Module Resource named
BatchMove with a Get EndPoint. Add FireDAC FDConnection, FDQuery, FDBatchMove,
FDBatcMoveDataSetReader, and FDBatchMoveJSONWriter components to the resource module. Rename
the FDConnection as DatabaseConnection. Rename the FDQuery as CustomerQuery. Save the project.
Connect the DataBaseConnection component to the InterBase Employee.gdb sample database. Set the
CustomerQuery SQL string to select * from customer. Set the FDBatchMoveDataSetReader’s DataSet
property to CustomerQuery.
Delphi:
C++:
Before you compile and run the application server, you’ll need to add a few FireDAC libraries to the
Requires section of your project. You’ll find these files in the C:\Program Files (x86)\Embarcadero\
Studio\20.0\lib for each of your target platforms.
Figure 161: Delphi BatchMove project. Figure 162: C++ BatchMove project.
Calling the GET method using the URL http://localhost:8087/BatchMove returns the JSON data result:
FDBatchMoveJSONWriter provides multiple options for formatting the JSON result. DataDef’s Formatting
sub-property for TBatchMoveJSONWriter, by default, is set to None.
Set the Formatting sub-property to Indented. Setting this sub-property will result in JSON responses that
are laid out in a more readable form.
Re-run the RAD Server application. Use a browser to call the Get method
(http://localhost:8087/BatchMove) and see the indent formatted JSON output.
The FDBatchMove component also allows you to create mappings to setup source and destination
columns mapping and to get the current source record values.
• Manually at design or run times. This allows to specify custom mappings, conversion expressions,
etc.
• Automatically at Execute call, if it is empty. The source and destination columns matching
performed by the column names. If a destination column has no corresponding source column,
then the destination column will be excluded from mapping and will be not filled at data
movement.
See Also
Marco Cantu blog: DataSet Mapping to JSON - RAD Server web service Delphi example
http://blog.marcocantu.com/blog/2017-december-dataset-mapping-json.html
FireDAC.Comp.BatchMove.TFDBatchMove
http://docwiki.embarcadero.com/Libraries/Rio/en/FireDAC.Comp.BatchMove.TFDBatchMove
FireDAC.Comp.BatchMove.JSON.TFDBatchMoveJSONWriter
http://docwiki.embarcadero.com/Libraries/Rio/en/
FireDAC.Comp.BatchMove.JSON.TFDBatchMoveJSONWriter
FireDAC.TFDBatchMove Sample
http://docwiki.embarcadero.com/CodeExamples/Rio/en/FireDAC.TFDBatchMove_Sample
RTL.JSONWriter
http://docwiki.embarcadero.com/CodeExamples/Rio/en/RTL.JSONWriter
Click the Finish button. After the project is created, rename the declaration and implementation of the
Get and GetItem methods to TestGet and TestItem. For Delphi, add EndPointMethod attributes before
the renamed methods. For C++, in the register function, add Attribute->EndPointMethod assignment
statements for the renamed methods. The declaration and implementation source code should look like
the following.
Delphi:
[ResourceName('Test')]
TTestResource1 = class(TDataModule)
published
[EndpointMethod(TEndpointRequest.TMethod.Get)]
procedure TestGet(const AContext: TendpointContext;
const ARequest: TendpointRequest;
const AResponse: TEndpointResponse);
[EndpointMethod(TEndpointRequest.TMethod.Get)]
[ResourceSuffix('{item}')]
procedure TestItem(const AContext: TendpointContext;
const ARequest: TendpointRequest;
const AResponse: TEndpointResponse);
end;
C++:
ServerUnit.h
ServerUnit.cpp
//---------------------------------------------------------------------------
#pragma hdrstop
#include "ServerUnit.h"
#include <memory>
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma classgroup "System.Classes.TPersistent"
#pragma resource "*.dfm"
//---------------------------------------------------------------------------
__fastcall TTestResource1::TTestResource1(TComponent* Owner)
: TDataModule(Owner)
{
}
Run the example RAD Server App. Note that the new endpoint names for the Test resource display in the
RAD Server log.
Figure 168: RAD Server application log showing the renamed Endpoints.
Use the http://localhost:8087/Test URL to execute the Get EndPoint (now called TestGet).
Use the http://localhost:8087/Test/HelloWorld URL to execute the GetItem EndPoint (now called
TestItem).
The new EndpointMethod attribute allows for the creation of self-describing names for the REST HTTP
verbs in your application server methods. This new feature can also help with the documentation and
implementation of client, web and service applications that call into the RAD Server application.
See Also
Request processing may be delegated to a resource module field of object type. The object type may be
any class (including TComponent descendant), implementing IEMSEndpointPublisher interface. A class is
called the endpoint publisher class. By default, all class endpoints will get resource suffix equal to
resource module field name. This may be overridden by specifying attribute for resource module field:
A class endpoint may be marked with ResourceSuffix attribute. When suffix starts with "./", then
specified suffix will be appended to default resource suffix of resource module field. Any attribute
specified for a resource module endpoint can be specified for a class endpoint. An attribute can be
specified at one of the places in order of priority (less priority at beginning of the list, higher priority
overrides lower priority attribute):
• Class endpoint
• Resource module field. An attribute first argument may be a class endpoint name.
• TEMSResourceAttributes specified at resource module registration. A name used for
TEMSResourceAttributes calls is a <resource module field name>.<class endpoint name>.
Delphi:
Create a component class, TEmpsProvider, that inherits from the IEMSEndpointPublisher interface.
Create the declaration along with ResourceSuffix(s) and implementation for the TEmpsProvider
endpoints. Add a class var to hold the JSONArray. In the public section of the Test resource add a
declaration for the TEmpsProvider. Use the following code for the interface and implementation sections.
The Interface declaration for TEmpsProvider and the Test resource:
interface
uses
System.SysUtils, System.Classes,
System.JSON,
EMS.Services, EMS.ResourceAPI, EMS.ResourceTypes;
type
TEmpsProvider = class(TComponent, IEMSEndpointPublisher)
private
class var
FArray: TJSONArray;
private
function GetItemByID(ARequest: TEndpointRequest): Integer;
class constructor Create;
class destructor Destroy;
public
procedure Get(const AContext: TEndpointContext;
const ARequest: TEndpointRequest;
const AResponse: TEndpointResponse); overload;
[ResourceSuffix('./{id}')]
procedure GetItem(const AContext: TEndpointContext;
const ARequest: TEndpointRequest;
const AResponse: TEndpointResponse); overload;
[ResourceSuffix('./{id}')]
procedure Put(const AContext: TEndpointContext;
const ARequest: TEndpointRequest;
const AResponse: TEndpointResponse);
procedure Post(const AContext: TEndpointContext;
const ARequest: TEndpointRequest;
const AResponse: TEndpointResponse);
[ResourceSuffix('./{id}')]
procedure Delete(const AContext: TEndpointContext;
const ARequest: TEndpointRequest;
const AResponse: TEndpointResponse);
end;
[ResourceName('Test')]
TTestResource = class(TDataModule)
public
Emps: TEmpsProvider;
constructor Create(AOwner: TComponent); override;
end;
uses
System.JSON.Builders, System.JSON.Writers, System.JSON.Readers;
procedure Register;
begin
RegisterResource(TypeInfo(TTestResource));
end;
{ TEmpsProvider }
var
oWriter: TJsonObjectWriter;
oBuilder: TJSONArrayBuilder;
begin
oWriter := TJsonObjectWriter.Create(False);
oBuilder := TJSONArrayBuilder.Create(oWriter);
try
oBuilder.BeginArray
.BeginObject
.Add('id', '1')
.Add('first_name', 'John')
.Add('second_name', 'Smith')
.EndObject
.BeginObject
.Add('id', '2')
.Add('first_name', 'Poll')
.Add('second_name', 'Scott')
.EndObject
.BeginObject
.Add('id', '3')
.Add('first_name', 'Harris')
.Add('second_name', 'Hill')
.EndObject
.EndArray;
{ TTestResource }
initialization
Register;
end.
Compile and Run the RAD Server application. The log will look like the following:
Figure 172: RAD Server application log with Test resource & endpoints with "Emps." prefix.
Note that the resource is named Test and each of the endpoints are prefixed with “Emps.”. The following
requests will be processed by TEmpsProvider methods of Emps object:
Figure 175: RAD Server application log shows the execution of the Emps.Get and Emps.GetItem.
See Also
• EndpointProduce: specifies the MIME types / file extensions that can be produced by this
endpoint as response to a GET method. The endpoint selection will be based on the Accept HTTP
request header.
• EndpointConsume: specifies the MIME types / file extensions that can be consumed by this
endpoint for PUT, POST, PATCH methods. The endpoint selection will be based on Content-Type
HTTP request header.
This chapter shows how RAD Server application resources can use the EndpointProduce attribute for
multiple REST Get requests based on image/jpeg and application/xml MIME types.
A Simple Example
Start a RAD Server project using the project package wizard. Choose the Data Module File type and set
the Resource name to AcceptTypes. De-Select all of the standard EndPoints and click the Finish button.
Delphi:
In the published section of your resource class add two method declarations decorated with
ResourceSuffix and EndpointProduce attributes.
[ResourceName('AcceptTypes')]
TAcceptTypesResource1 = class(TDataModule)
published
[ResourceSuffix ('*')]
[EndpointProduce ('image/jpeg')]
procedure GetImage(const AContext: TEndpointContext;
const ARequest: TEndpointRequest; const AResponse: TEndpointResponse);
[ResourceSuffix ('*')]
[EndpointProduce ('application/xml')]
procedure GetText(const AContext: TEndpointContext;
const ARequest: TEndpointRequest; const AResponse: TEndpointResponse);
end;
In the implementation section add the following code for the GetImage and GetText endpoints.
begin
fs := TFileStream.Create('c:\temp\page\content.jpeg', fmOpenRead);
AResponse.Body.SetStream(fs, 'image/jpeg', True);
end;
C++:
ServerUnit.h
#ifndef ServerUnitH
#define ServerUnitH
//---------------------------------------------------------------------------
#include <System.Classes.hpp>
#include <System.SysUtils.hpp>
#include <EMS.Services.hpp>
#include <EMS.ResourceAPI.hpp>
#include <EMS.ResourceTypes.hpp>
//---------------------------------------------------------------------------
#pragma explicit_rtti methods (public)
class TAcceptTypesResource1 : public TDataModule
{
__published:
private:
public:
__fastcall TAcceptTypesResource1(TComponent* Owner);
void GetImage(TEndpointContext* Acontext,
TEndpointRequest* ARequest, TEndpointResponse* AResponse);
void GetText(TEndpointContext* Acontext,
TEndpointRequest* ARequest, TEndpointResponse* AResponse);
};
#endif
ServerUnit.cpp
Add the following code for the GetImage and GetText endpoints. In the Register function add the
ResourceSuffix(s) and EndpointProduce attributes for the GetImage and GetText endpoints.
//---------------------------------------------------------------------------
#pragma hdrstop
#include "ServerUnit.h"
#include <memory>
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma classgroup "System.Classes.TPersistent"
#pragma resource "*.dfm"
//---------------------------------------------------------------------------
__fastcall TAcceptTypesResource1::TAcceptTypesResource1(TComponent* Owner)
: TDataModule(Owner)
{
}
How can you test the RAD Server application code? If you use a browser and use the resource name in
the URL the second method will be called returning the response or you might get an error message
indicating that none of the available endpoints matches the request.
Here are a few more steps to follow to test the RAD Server application’s implementation:
1) Edit the RAD Server emsserver.ini configuration file. Add a path JSON entry to the [Server.PublicPaths]
section. This entry will identify the directory and HTML file to use when the http://localhost:8087/page
URL is tried.
2) Create a folder named c:\temp\page. Create text and jpeg files with the same names used in the
implementation of the GetText and GetImage methods. Create an index.html file that will connect with
the RAD Server application’s methods based on the different Accept Headers for each request.
index.html:
<html>
<head>
<title>a page for rad server</title>
</head>
<building>
<h1>a page</h1>
<p>an image below</p>
<img src="/AcceptTypes/test.jpeg">
<p> </p>
<h1>some more</h1>
<iframe src="/AcceptTypes/test.txt">
</building>
</html>
3) Run the RAD Server application using the DevEMSServer.exe from the IDE. The log will contain the
following entries (notice the two highlighted lines for the public path and the AcceptTypes resource with
the GetImage and GetText endpoints):
4) Click the Open Browser button to bring up the default browser displaying the RAD Server version
number and server name.
In the RAD Server application log the following request will display showing that the second endpoint
was executed.
{"Request":
{"Resource":"AcceptTypes","Endpoint":"GetText","Method":"GET","User":"(blank)","Time
":"3\/28\/2019 1:05:46 PM","Thread":14740}}
The RAD Server application’s log shows two requests for the GetImage and GetTExt endpoints called in
the index.html file for the img src and iframe src markup.
{"Request":
{"Resource":"AcceptTypes","Endpoint":"GetImage","Method":"GET","User":"(blank)","Tim
e":"3\/28\/2019 1:16:03 PM","Thread":8432}}
{"Request":
{"Resource":"AcceptTypes","Endpoint":"GetText","Method":"GET","User":"(blank)","Time
":"3\/28\/2019 1:16:03 PM","Thread":11376}}
Use the Developer Tools support in Chrome (you can also use the developer tools for FireFox) and click
on the Network and Headers tabs. Then click on the test.jpeg name that was requested in the “img src” to
see the Request Headers Accept string.
Figure 182: Use Chrome's developer tools to see test.jpeg’s Accept Request Header.
Click on the test.txt name that was requested in the “iframe src” to see the Request Headers Accept
string.
Figure 183: Use Chrome's developer tools to see test.txt’s Accept Request Header.
This simple demo shows how a RAD Server application can use the EndpointProduce attribute with a
related MIME type to map the same URL to different methods depending on the HTTP Request Accept
headers. VCL and Multi-Device client applications or another service can also use the same RAD Server
capabilities.
See Also
Marco Cantu’s blog post: New RAD Server Features in RAD Studio 10.3
https://community.idera.com/developer-tools/b/blog/posts/new-rad-server-features-in-rad-studio-10-3
Create a RAD Server application package with a Data Module and no REST methods selected. In the
resource module, add an EMSFileResource component. In the object inspector select the AllowedActions
for List, Get. Set the PathTemplate property to c:\temp\{id}
Add the emsserverresource.dcp package file to the Requires list in your project.
For Delphi, add two ResourceSuffix entries before the EMSFileResource definition in the data module.
[ResourceSuffix('list', '/')]
[ResourceSuffix('get', '/{id}')]
Delphi:
unit ResourceUnit;
// EMS Resource Module
interface
uses
System.SysUtils, System.Classes, System.JSON,
EMS.Services, EMS.ResourceAPI, EMS.ResourceTypes, EMS.FileResource;
type
[ResourceName('files')]
TFilesResource1 = class(TDataModule)
[ResourceSuffix('list', '/')]
[ResourceSuffix('get', '/{id}')]
EMSFileResource1: TEMSFileResource;
published
end;
implementation
{%CLASSGROUP 'System.Classes.TPersistent'}
{$R *.dfm}
procedure Register;
begin
RegisterResource(TypeInfo(TFilesResource1));
end;
initialization
Register;
end.
C++:
For C++, add two resource suffix attribute statements in the Register function code.
ServerUnit.h file
#ifndef ServerUnitH
#define ServerUnitH
//---------------------------------------------------------------------------
#include <System.Classes.hpp>
#include <System.SysUtils.hpp>
#include <EMS.Services.hpp>
#include <EMS.ResourceAPI.hpp>
#include <EMS.ResourceTypes.hpp>
#include <EMS.FileResource.hpp>
//---------------------------------------------------------------------------
#pragma explicit_rtti methods (public)
class TFilesResource1 : public TDataModule
{
__published:
TEMSFileResource *EMSFileResource1;
private:
public:
__fastcall TFilesResource1(TComponent* Owner);
};
#endif
ServerUnit.cpp file
//---------------------------------------------------------------------------
#pragma hdrstop
#include "ServerUnit.h"
#include <memory>
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma classgroup "System.Classes.TPersistent"
#pragma resource "*.dfm"
//---------------------------------------------------------------------------
__fastcall TFilesResource1::TFilesResource1(TComponent* Owner)
: TDataModule(Owner)
{
}
Compile and run the RAD Server application. Notice that the RegResource entry for the files resource
with the List and Get endpoints displays in the RAD Server log:
Figure 188: EMSFileResource demo server log with files resource containing List and Get
Endpoints.
Click the Open Browser button and use the localhost:8087/files URL to return a JSON array with the list
of the files in the PathTemplate property’s directory.
Modify the URL in the browser by adding the name of one of the files in the directory. Adding a
filename to the URL will provide the file to the Get AllowedAction built in endpoint. This was setup by
the matching of the PathTemplate property value, c:\temp\{id}), and the EMSFileResource resource
suffix /{id}.
No code is required to get the files list for the designated folder and to display one of the files. Of course,
additional code for the application server and client application could do much more using
EMSFileResource in more complex applications.
See Also
Copy the FireDac-based RAD Server demo project that has a CustomerQuery component (or build a new
package project using the wizard). Add an EMSDataSetResource component to the server module and
change its name to CustomerDataSetResource.
Set the AllowActions property check boxes for List and Get. Set the DataSet property to the
CustomerQuery. Set the PageSize property to 3.
In the Object Inspector for the CustomerDataSetResource use the ValueFields property Field List Editor to
select CustomerQuery columns to support sorting and return in the JSON response.
Figure 193:
CustomerDataSetResource
ValueFields property fields list editor
with selected query fields.
For the Delphi version of the RAD server application, add resource suffixes before the declaration of the
DataSetResource in your RAD Server application’s resource module:
[ResourceName('DataSetResource')]
TDataSetResourceResource1 = class(TDataModule)
CustomerConnection: TFDConnection;
FDStanStorageJSONLink1: TFDStanStorageJSONLink;
FDGUIxWaitCursor1: TFDGUIxWaitCursor;
FDSchemaAdapter1: TFDSchemaAdapter;
FDPhysIBDriverLink1: TFDPhysIBDriverLink;
CustomerQuery: TFDQuery;
[ResourceSuffix('list', '/')]
[ResourceSuffix('get', '/{CUST_NO}')]
CustomerDataSetResource: TEMSDataSetResource;
published
end;
For C++, add code in the RAD Server package’s Register function to place resource suffixes in the
attributes for the EMSDataSetResource List and Get endpoints:
In both of the above source code examples the {cust_no} string is used for the Get endpoint suffix to
match the primary index column name for the Customer table. If you use a different database and table
set the suffix to the name of that table’s primary index column or columns.
Figure 194: RAD Server application log with DataSetResource endpoints defined.
Click the Open Browser button and try the following URLs:
Figure 197: DataSetResource List endpoint called with parameter for the
first page.
4) If the request goes beyond the number of pages of data that are available, the DataSetResource will
return a null JSON array: localhost:8087/DataSetResource?page=100
5) Use the SortingParamPrefix string with a Field Name to return a JSON response array sorted by
Customer in ascending order: localhost:8087/DataSetResource?sfCustomer=A
6) Use a combination of URL parameters to return a JSON response array sorted by Country (descending
order), State_Province (ascending order), City (ascending): localhost:8087/DataSetResource?
sfCountry=D&sfState_Province=A&sfCity=A
Create a VCL (or a multi-device) client application that uses the same EMSDataSetResource endpoint
functionality. Create a starting client project with the following components.
Connect the components and set the properties. Add 3 buttons and a DBGrid. Connect the DataSource
to the FDMemTable. Use the DataSource for the DBGrid. The following are some of the property settings
used in the client application.
ResourceOptions.AssignedValues = [rvSilentMode]
ResourceOptions.SilentMode = True
UpdateOptions.AssignedValues = [uvCheckRequired, uvAutoCommitUpdates]
UpdateOptions.CheckRequired = False
UpdateOptions.AutoCommitUpdates = True
Adapter = FDTableAdapter1
end
object FDTableAdapter1: TFDTableAdapter
SchemaAdapter = FDSchemaAdapter1
DatSTableName = 'CustomerQuery'
end
Delphi:
C++:
//---------------------------------------------------------------------------
void __fastcall TForm1::Button3Click(TObject *Sender)
{
// get all customers ordered by Country
EMSFireDACClient1->GetEndpoint->Params->Clear();
EMSFireDACClient1→GetEndpoint→Params→AddItem(
"sfCountry", "A", TRESTRequestParameterKind::pkQUERY);
EMSFireDACClient1->GetData();
}
Figure 202: Client UI after clicking Button1 - All customer data ordered
by Primary Key CUST_NO.
Figure 204: Client UI after clicking Button3 - All Customer data sorted by
Country.
See Also
Tutorial: Implementing Your First RAD Server Client Application (using BackendEndpoint)
http://docwiki.embarcadero.com/RADStudio/Rio/en/
Tutorial:_Implementing_Your_First_RAD_Server_Client_Application
Marco Cantu blog: New RAD Server Features in RAD Studio 10.3
https://community.idera.com/developer-tools/b/blog/posts/new-rad-server-features-in-rad-studio-10-3
• Expose JSON in the RAD Server Engine Methods, and make direct AJAX calls.
• Export data, define a matching data model, and build the Web Client UI.
Create a RADServer application (resource name = EmployeeData) with a Get endpoint. Add to the
resource module: FDConnection (employee.gdb), FDQuery (select * from employee), FDBatchMove,
FDBatchMoveDataSetReader, FDBatchMoveJSONWriter, and FDGUIxWaitCursor.
Add the required run time packages using the Add References menu.
Delphi:
C++:
Run the RAD Server Employee Data application. The log will have the following information:
Figure 208: EmployeeData resource running int he RAD Server Development Server.
Click the Open Browser button to see that the URL http://localhost:8087/version returns the JSON object
{"version":"4.0","server":"Embarcadero EMS"}. Use the URL http://localhost:8087/EmployeeData to
return a JSON array of objects containing all of the rows in the employee table.
Use the Sencha Architect IDE and Ext JS library with a commercial license to build a web client
application. You can also do the same development and testing using the Sencha Architect 30 day free
trial available at https://www.sencha.com/products/evaluate/
To build and test the EXT JS web client app use the following steps.
Figure 209: Sencha Architect 4 IDE Figure 210: New Project Template
startup screen. Choices – Choose Blank Project.
Click the Create button. This creates a new Sencha EXT JS 6.5.x Classic project for the Web App.
Add a TAB Panel using the Toolbox search and search for Tab. Double-click the TAB Panel component
from the Toolbox to add it to the Web Application. The TAB Panel provides a layout with multiple tabs.
Select Tab 1 on the designer and in the Toolbox search for “Button”. Drag and drop the Button onto TAB
1. It will display with text that says “MyButton”.
Figure 212: IDE Design window with multiple tab control and button on Tab
1.
Save the project to a folder. The contents of the project folder will include the following files and
subfolders.
Next, right-mouse click on the button to add an event handler and select “Add Event Binding” from the
displayed menu.
Figure 214: Right Mouse Click pop-up menu choices for MyButton.
On the “Create View Controller Event Binding” dialog wizard, for the Event, select “click” from the drop
down. This operation will create a Function Name of onButtonClick. You can choose a different name for
the event handling function.
Next, select MyButton in the Project Inspector and click the Code button to switch from the design to the
source code view. This operation shows the definition of the MyTabPanel and the items created so far
with the MyButton definition highlighted.
In the Project Inspector click on the onButtonClick for the MyButton. The code window now shows the
view controller for the event handler where you can write JavaScript code for the onButtonClick
function(button, e, eOpts). Notice that the onButtonClick function makes one object available, the
button object. This is like the Sender for an event handler in C++ Builder and Delphi. Click the Add
Comment icon in the gutter to add a text comment to describe what the event handler is going to do. To
change the text of the Button when the button is clicked, add the code to the onButtonClick event
handler:
At execution time the code will cause the button’s text to “MyButton was clicked”. Note: setText and
getText need to be written in the lowercase and uppercase as JavaScript is a case-sensitive language. The
view controller code will now look like:
Click the SAVE button on the tool bar (or choose File | Save using the main menu) to save the project.
The project’s App | View subfolder has the JavaScript code.
To prepare to try a preview of the application, use the Edit | Project Settings… menu item to make sure
the setup for the project is correct. Click General in the dialog wizard. Check the Overwrite index file on
save checkbox. Check the Include Architect version in generated JavaScript checkbox. Make sure the URL
prefix has the default string: http://localhost:{port}/{path}
Click Framework in the dialog wizard. Click the Build Tools Enabled button. Select the License Commercial
radio button.
Click the Save button to save the project settings. The Sencha tools can be found in the C:\Users\
<username>\bin\Sencha\Architect\Cmd\6.7.0.63 folder.
Make sure that the Sencha Cmd tools folder is on the System Environment Variables path.
If it is not already running, Sencha Architect IDE will start the Sencha web server to enable previewing
the app. To start the Sencha web server (sencha.exe) type the following in a command window: sencha
web start
Figure 222: Command example for starting the Sencha web server.
With the Sencha tools folder included in the System Environment Variables path, the Preview and Build
web app buttons should be enabled on the tool bar in the IDE.
Figure 223: Sencha Architect IDE with Preview and Build web app enabled on the tool bar.
Clicking the Build web app button in the tool bar will package the application for deployment to a
production web server.
Next, click the Preview App icon on the tool bar to see what the app looks like running as a Web app.
When previewing a project, Sencha Architect IDE provides the option to select a URL Prefix. By default
the Sencha Architect IDE will preview the application using a predefined URL.
Click the Preview button. The JavaScript app will display in the default browser.
Click the MyButton button to execute the button click handler code and see the text or the button
change.
Replace the implementation of the onButtonClick event handler with the code (shown below). The code
makes an Ajax request call to the RAD Server app’s Version endpoint using the
http://localhost:8087/version URL. Cors (Cross-Origin Resource Sharing) is set to true to allow the AJAX
call to make the HTTP request to a different domain, sub domain, port, or protocol. In this case the code
calls from port 1841 (the Sencha web server) to port 8087 (RAD Server). The Ext.Ajax.request success
action contains a function that decodes the JSON responseText and calls setText to set the button’s text
to the JSON object’s version and server values.
For CORS to work, make sure the RAD Server development (or remote production server) emsserver.ini
configuration file’s Server/APICrossDomain section CrossDomain is set to *.
[Server.APICrossDomain]
;# Write here the domains allowed to call the API. Used for Cross-Domains
;# Set CrossDomain=* to allow access to any domain.
CrossDomain=*
Click the Preview button on the IDE tool bar. Click on the MyButton in the browser and if the AJAX call is
successful the button text will include the RAD Server version information.
In this step the JavaScript web client will call the RAD Server EmployeeData resource’s Get method to
return a JSON data object and display the data. Using a browser to call EmployeeData REST Get endpoint
using the http:// localhost:8087/EmployeeData URL, the RAD Server app will return a JSON array for all
of the columns from the EMPLOYEE table via the SQL Statement “select * from Employee”. When the URL
is called from a browser the returned JSON array looks like the following:
Figure 228: Employee Data JSON Array returned from RAD Server app.
The Sencha Architect IDE can be used to create a data model that matches the JSON data returned from
the RAD Server app. The project’s JavaScript code can be modified to display the data on a Grid in Tab 2.
Select the Models node in the Project Inspector. In the Project Inspector, select + and select Model. This
will add MyModel to the Project.
Select the Code button, to see the code for MyModel in the IDE. Right-mouse click on MyModel in the
Project Inspector and choose the View Code item from the pop-up menu.
To set a more descriptive name for the model, go to the Config panel, type use in search box and type
Employees for the useClassName property. Notice that the name of the model is changed in the Project
Inspector and the code.
Figure 231: Model name changed to Employees using the Config panel.
Next, define the fields for the model using the Config panel. Type fields in the search box and click the +
icon to the right of the fields property to add the needed fields (employee table column names)
separated by commas: EMP_NO, FIRST_NAME, LAST_NAME, PHONE_EXT, HIRE_DATE, DEPT_NO,
JOB_CODE, JOB_GRADE, JOB_COUNTRY, SALARY, FULL_NAME
Figure 232: Adding employee table column names to the Fields property
of the model.
Click the Finish button in the Config panel. The fields will now display in the Project Inspector, the code
and the Config panel.
Figure 233: Fields appear in the Project Inspector, Code, and Config panel.
The list of fields gets created with no specific data types to define the model for the data. After defining
the fields, the fields needs a data store. There are many different types of data stores available including:
Array Store, Virtual Store, JSON Store, XML Store, etc. To create a data store for the project, click on the +
icon in the Project Inspector to see the choices.
Choose the JSON Store for the JSON data that will come from the RAD Server application. MyJsonStore
will be defined in the code.
In the Project Inspector select the MyJsonReader node. Since the JSON data returned from the RAD
Server app’s Get endpoint does not have a root property, a rootProperty value in the Config panel is not
required. If there was a root property, use the search box in the Config panel, type in rootProperty and
type in the name of the JSON root property string.
In the IDE Project Inspector, some error indicators (red exclamation icons) might appear next to the
MyJsonStore and MyAjaxProxy nodes. Click on the red exclamation icon for the MyJsonStore.
In the Project Inspector, select the MyJsonStore node. In the Config panel search for the model property.
Use the drop down arrow to select the Employees model.
Figure 238: Selecting the Employees model for MyJsonStore model property.
In the Config panel search for the autoLoad property. Set the check box to turn on Auto Load of data
from the RAD Server application’s EmployeeData resource Get endpoint.
The code for the JSON store now looks like the following:
Select Tab2 from the MyTabPanel. In the tool box search type Grid to see all of the Grid components that
are available. Double click on the Grid Panel to add it to Tab2.
Four sample columns are created for the Grid Panel: String, Number, Date, and Boolean.
Right-mouse click on the Grid Panel in the Project Inspector. Choose Grid Builder from the menu. Click on
the Data Source Existing Model radio button. Select the Employees model. Set the Remove Existing
columns check box.
Change the Title to Employee Data. Use the Columns drop down menu to set which columns will support
sorting. In the Data Store section, select the Use Existing Store radio button. Select MyJsonStore from the
Select Store drop down menu. Click the Generate Button. In the Project Inspector and the Code window
the 11 columns are generated matching the InterBase Employee table.
To customize the UI further select the MyTabPanel and use the Config to set the panel’s height and width
property values to 1000 and 2000 respectively. Select each of the Employee Data column names and set
each width property to ensure that the heading and data fit (you can also set the minWidth and
maxWidth property values). Sencha Ext JS also has a Viewport component that you can add to display
the Grid Panel to fill the available screen space.
An eyeball icon also displays in the Project Inspector. Hover over the icon and see:
Figure 245: Project Inspector eyeball icon next to the employees data store.
The Grid Builder created 30 rows of mock data (if that option was selected). You can click on the icon to
see the JSON array of data.
On Tab1 click the MyButton to call the RAD Server Version endpoint and return the version information.
Switch to Tab2 and see the live RAD Server employee data:
In the RAD Server Development Server log, the EmployeeData resource Get endpoint and the Version
resource GetVersion endpoint display. The EmployeeData Get endpoint appears first because the
autoLoad property was set in the JavaScript client.
Figure 248: RAD Server Development Server log showing that the EmployeeData Get and Version
GetVersion endpoints were executed by the Sencha EXT JS project preview.
Chrome’s developer tools shows the network traffic of the Ajax request with the Get REST response
returning the rows of the Employee table:
Figure 249: Chrome’s developer tools showing Get response with Employee table rows.
That’s how easy it is to use Sencha Architect. Start with a blank Sencha Web Client project, build the UI,
associate the model with data storage, connect to the RAD server application, and Preview the
application. RAD Studio developers should feel very comfortable in the Architect IDE with components,
views, view controllers, and property settings.
See Also
https://www.youtube.com/watch?v=---RFUV1VvQ
RAD Server sample projects are available for Delphi and C++Builder in the C:\Users\Public\Documents\
Embarcadero\Studio\20.0\Samples folder. Each sample folder includes a readme.txt or readme.html file
with information about the sample along with technical details to help explore and test the sample.
Additional details can be found on the Embarcadero DocWiki and in the readme file in each sample
folder.
FireDACResource
This sample demonstrates how to use a RAD Server package to extend the RAD Server to connect to an
SQLite database using FireDAC components. The first part consists of creating a RAD Server Package with
a TDataModule where the FireDAC components are placed. It uses the TFDConnection component to
establish the connection to the SQLite database. Once you run the package, the resource is registered on
the RAD Server Engine and can be accessed by a client application using REST.
The FireDAC client needs a TEMSFireDACClient and a TEMSProvider to connect to the RAD Server Engine
and retrieve the JSON data. This sample shows how to setup a master/detail relationship by setting the
Orders query (qOrders) MasterSource property to the dsCustomer and MasterFields property to
CustomerID.
The RAD Server package defines the database connections for the customers and orders table. There is a
master/detail relationship for the customers query and the orders query based on the Customer ID
column.
The client application uses the EMSProvider and the FireDACClient components to establish the
connection to the RAD Server application. The UI has buttons to get the customers and orders queries
from the server. The UI displays the customers list in upper grid and the orders for the selected customer
in the lower grid.
The client application has a Data Module to set up the client-side data sets for the master/detail
relationship. Components include two FDMemTable for local in-memory storage and two
FDTableAdapter for the Customers and Orders queries. Data changes on the client side are cached in
memory and when the Post Updates button is pushed the cached updates are posted back via the RAD
Server resource to the Customers and Orders tables.
Figure 255: Client application with customers and their orders after
clicking on the Get Tables button. Post Updates will be enabled after data
changes are made.
APIDocAttributes
This sample consists of a RAD Server package that loads a new resource into the RAD Server provided
with RAD Studio. The demo uses FireDAC components to access the Interbase database employee.gdb.
The connection parameters are defined in the TFDConnection component. It requires InterBase to be
installed on the machine or to connect to a remote server. Make sure that the server is running before
you run the example. InterBase is used to store the information about the server connections.
http://docwiki.embarcadero.com/CodeExamples/Rio/en/EMS.APIDocAttributes_Sample
Project Folders:
C:\Users\Public\Documents\Embarcadero\Studio\20.0\Samples\Object Pascal\Database\EMS\
ActiveDirectoryConsole
C:\Users\Public\Documents\Embarcadero\Studio\20.0\Samples\CPP\Database\EMS\
ActiveDirectoryConsole
Figure 257: APIDoAttributes C++ sample - server log with SampleAttributesCpp and
API resources and endpoints.
• http://localhost:8087/api/apidoc.yaml
• http://localhost:8087/api/apidoc.json
To access the API documentation only for the sampleattributes resource for Delphi and C++:
• Delphi:
◦ http://localhost:8087/api/sampleattributesdelphi/apidoc.yaml
◦ http://localhost:8087/api/sampleattributesdelphi/apidoc.json
• C++:
◦ http://localhost:8087/api/sampleattributescpp/apidoc.yaml
◦ http://localhost:8087/api/sampleattributescpp/apidoc.json
Use GetItem to see one specific item of the employee table. To see how to use each specific method, you
can access the API documentation provided.
• Delphi: http://localhost:8087/sampleattributesdelphi/{item}
• C++: http://localhost:8087/sampleattributescpp/{item}
ActiveDirectoryConsole
This example demonstrates how to implement custom Login and Signup endpoints
using Active Directory Services (AD).
Project Folder:
C:\Users\Public\Documents\Embarcadero\Studio\20.0\Samples\Object Pascal\Database\EMS\
ActiveDirectoryConsole
Open ADConsole.dproj. Run. When the checkbox is checked the custom AD Login
and Signup endpoints will be called instead of the standard endpoints in
the Users resource.
The custom AD Login and Signup endpoints validate the user name and password
against Windows users by calling WinApi.Windows.LogonUser requiring valid Windows credentials.
Custom Login:
There are two ways to cause EMS to execute custom login and signup methods:
of the Users.LoginUser and Users.SignupUser endpoints. By checking the box in CustomLoginClient, the
TEMSProvider.LoginResource property is set to "ADLogin".
[Server.Redirect]
Users.SignupUser={"destination":"ADLogin"}
Users.LoginUser={"destination":"ADLogin"}
Figure 261: RAD Server application log wth ADLogin resource and its endpoints.
RAD Server solution series applications are available for Field Services demo, Hospitality demo, and
Nurses Station demo. Each RAD Server solution series application template can be downloaded using the
GetIt package manager (Tools > GetIt Package Manager > Industry Templates) in RAD Studio.
Learn more about each of the template solutions by reading the quick overview blog posts for each
solution.
The RAD Server hospitality sample application includes a mobile client application for collecting survey
data, a back-end server to store data and administer surveys, and a web client for viewing survey results.
The solution includes RAD Server multi-tenancy support for managing surveys from multiple restaurants.
Read more at https://community.idera.com/developer-tools/b/blog/posts/rad-server-solution-series-
hospitality-restaurant-survey-application
The RAD Server Field Service Industry Template provides an end-to-end field service application template
for routing appointments, managing parts, and user administration. It is made up of a REST server
module, a desktop client, and a cross platform mobile client. You can read more information about the
Field Service Application at https://community.idera.com/developer-tools/b/blog/posts/rad-server-
solution-series-field-service-application
YouTube videos are also available that walk through the Field Service Application development and use.
• Setup – https://www.youtube.com/watch?v=cT5tiPDPh3c
• Development Server – https://www.youtube.com/watch?v=paw3nCwd_qs
• Admin Application – https://www.youtube.com/watch?v=Y5Dex1miXj0
• Client Application – https://www.youtube.com/watch?v=SnIMq-s3EHc
• UI Tips and Tricks – https://www.youtube.com/watch?v=GrHdj_4ACxg
See Also
In an IT world that is no longer confined to a desktop, device, server, or data center, RAD Server and RAD
Studio developers can build solutions that cover the wide spectrum of your company's (and customers)
computing needs and business requirements. RAD Server applications can be deployed on top of
Microsoft Windows IIS, Windows Apache web servers, and Linux Intel 64-bit servers.
This e-book is just the start of all that is possible in building RAD Server services-based applications. To
continue learning more about building REST-based RAD Server applications, developers should explore
the See Also links, RAD Studio samples, blog posts, and YouTube videos. As seen in this e-book,
development starts quickly followed by the addition of custom code for specific business requirements.
Sample Projects
The source code for the Delphi and C++Builder projects used in creating this technical paper should be
found in the zip file for this technical paper. If you can’t find the project in the zip file, you can find the
code on the Embarcadero Technologies GitHub site.
Acknowledgments
It takes a great team of software engineers, developer advocates, product managers, software
consultants, and Embarcadero MVPs to put together a technical paper that covers the broad spectrum of
RAD Server application development opportunities. I am grateful to the many Embarcadero and Idera
team members who helped in creating this paper including (in alphabetical order by first name): Al
Mannarino, Bruno Babet, Calvin Tang, Craig Chapman, Dan Gallo, Daniella Villalobos, Espada, David
Millington, Dmitry Arefiev, Eli M., Fernando Rizzato, Jim McKeeth, Marco Cantu, Rebekah Dumouchelle,
Sarina Dupont, Sriram Balasubramanian, and Steve Axtell. I also want to especially thank my wife,
Martha, for her help in reviewing the chapters.
Additional Resources
There is an abundance of information available about RAD Server application development in addition to
the See Also lists included at the end of each chapter. Below you will find links to help documents,
YouTube videos, and more.
REST
https://community.idera.com/developer-tools/tags/rest
REST API
https://community.idera.com/developer-tools/tags/REST%2bAPI
FireDAC
https://community.idera.com/developer-tools/tags/FireDAC
JSON
https://community.idera.com/developer-tools/tags/json
RAD Studio
https://community.idera.com/developer-tools/tags/RAD%2bStudio
Ext JS
https://community.idera.com/developer-tools/tags/Ext%2bJS
GetIt
https://community.idera.com/tags/GetIt
Getting Ahead with RAD Studio 10.3 Architect Edition [Dec 28, 2018]
https://www.youtube.com/watch?v=ojGAH7q010Y
Make Your Apps Scalable and Web Enabled [Sep 16, 2018]
https://www.youtube.com/watch?v=q2nNMEwVyNc
Fast and Simple IoT Development with RAD Studio and RAD Server – CASE 29 Conference 2017 – Croatia
[Mar 4, 2017]
https://www.youtube.com/watch?v=slRSBJXYYIM
RAD Server: The Perfect Back-end for your Apps [Jul 19, 2016]
https://www.youtube.com/watch?v=HY0JRJPvjsU
RAD Server Application Deep Dive – Creating a Department Store Retail Solution [June 16, 2016]
https://www.youtube.com/watch?v=f8rAGLnop4s
The RAD Server Field Service Industry Template provides an end-to-end field service application template
for routing appointments, managing parts, and user administration. It is made up of a REST server
module, a desktop client, and a cross-platform mobile client. Learn more about the RAD Server Field
Service Sample application by visiting:
https://community.idera.com/developer-tools/b/blog/posts/rad-server-solution-series-field-service-
application
RAD Server Field Service Application: Development Server [Jun 25, 2018]
https://www.youtube.com/watch?v=paw3nCwd_qs
RAD Server Field Service Application: Admin Application [Jun 25, 2018]
https://www.youtube.com/watch?v=Y5Dex1miXj0
RAD Server Field Service Application: Client Application [Jun 25, 2018]
https://www.youtube.com/watch?v=SnIMq-s3EHc
RAD Server Field Service Application: UI Tips and Tricks [Jun 25, 2018]
https://www.youtube.com/watch?v=GrHdj_4ACxg
RAD Server Application Deep Dive Playlist (15 videos) [Jun 20, 2016]
https://www.youtube.com/playlist?list=PLwUPJvR9mZHgccq4EfTcsCngRqpTmm_wn
RAD Server Application Deep Dive - Creating a Department Store Retail Solution [Jun 20, 2016]
https://www.youtube.com/watch?v=f8rAGLnop4s
David Intersimone, known to many as “David I”, is a passionate and innovative software industry
veteran who extols and educates the world on developer tools, software development and software
architectures. David I joined Borland Software in 1985 where he practically invented Developer
Relations. During David I’s forty-five years as a developer, development manager, developer
community executive, development cheerleader, and developer advocate, he has created a
thriving global developer community, thousands of articles, videos and blog posts.
Before Embarcadero acquired the developer tools business from Borland Software, David spent
more than 20 years with Borland in various evangelism, engineering, and development capacities,
including creating the company’s developer relations program.
Today, David I shares his visions and insights as a pioneer in developer relations with program
managers, directors and developers where he gives workshops, webinars, guidance and advice
on developer communities, developer advocacy and software development. David I is also an
Embarcadero MVP.