Do-Say-See Tutorial: Use Delphi XE8 to build EMS e-mail checker service and client


Two weeks ago I was doing the EMS demo session for Delphi developers in London. That was good fun!
Would you like to do it yourself?
In this post you will find detailed steps of my demo. Enjoy!
The source code of this demo can be downloaded from Embarcadero Code Central.
There were some comments on social media, so I think that a disclaimer is in place. The demo “E-mail Checker” service does not check if a given e-mail address actually exists. The service is only as good as the regular expression used to validate if a given string looks like a valid e-mail address or not. It will for example tell that “hello@hello.c” is not a good one, because “c” is not a valid domain name. It is not perfect, you can use in production environment at your own risk only. It is just a simple EMS demo. Nothing more:-) Thanks Andrea Raimondi for bringing this up.
Do-Say-See Steps
Enterprise Mobility Services (EMS) is a new turnkey solution for today’s interconnected, distributed apps, offering an easy to deploy middleware server that hosts loadable custom API and data access modules. Based on open and standard technologies, including REST HTTP calls and JSON data formats, and providing major SQL database drivers along with an encrypted embedded and server SQL database. With its user management and authentication with user and API analytics, Enterprise Mobility Services is ideal for enabling secure access from mobile apps to Enterprise Databases. EMS is a middleware solution that is stateless, restful, scalable, and secure.
This step-by-step tutorial will walk you through the process of building an email checker app using Enterprise Mobility Services and Delphi XE8. The mobile app is going to be very simple. It will just contain an edit and a button. When the end user presses the button, the contents of the edit will be sent to the EMS service REST API that will validate if a given string is a valid email address using regular expressions.
First we need to create an EMS service and then we are going to create a multi-device app project for it.
Start Delphi XE8. From the “File” menu select “New” and then “Other”. In the “New Items” dialog click on the “Delphi Projects -> EMS”. Double-click on the “EMS Package” icon. That should display “EMS Package Wizard” window.

Each EMS package can contain zero or more resources with endpoints that extend the REST API of the EMS server.
On the “Package” tab of the wizard select the second option “Create package with resource”. Click on “Next” button.

In the second step of the wizard we need to give a new EMS resource a name and decide what file type to use for a class that is going to implement this resource. If we plan to use any non-visual components in the implementation of our resource it is handy to choose for a data module.
In the “Resource name” field enter “EmailChecker”. Keep “Data module” as selected file type. Click on “Next” button.

In the last step of the wizard we need to decide which endpoints to add to our resource. Each endpoint handles a different kind of HTTP request. We are going to keep the default selection: a generic HTTP GET request plus an HTTP GET request for a specific “item” in the resource. In case of our server we are going to use “Get” endpoint to return just the name of the service and the “GetItem” to perform the actual check if a given string is a valid email address.
In the “Endpoints” tab of the resource keep the default selection of “Get” and “GetItem”. Click on “Finish” button. That should generate a new EMS package project.

Now we need to save the project generated by the wizard in a location that makes sense to us and to give the unit and the project meaningful names. Notice that the project has the “bpl” extension, which means that this is a Delphi package that can be loaded into the executable and cannot be run standalone.
Click on the “File” and “Save All” menu option. Create “C:demosXE8EMSEmailChecker” directory on your hard drive. Save the resource unit as “uEmailCheckerRes” and the package project as “EmailChecker”.

The EMS package is loaded by the “EMS Development Server” that is located in the “bin” directory of our Delphi XE8 installation. We can verify this by going to “Debugger” tab in “Project Options”.
From the “Project” menu select the last item “Options”. Click on the “Debugger” node and highlight “Host application” option. Verify that it points to “EMSDevServer.exe”.

The actual code to check if a given string is a valid email address has already been written. We need to add the “RegExpressionsUtil” unit to our EMS server project.
Download the “RegExpressionsUtil.pas” file from the following URL:
Copy this file to the directory where you have saved the EMS package project (C:demosXE8EMSEmailChecker). Right click on the “EMailChecker.bpl” node in the Project Manager at the top right corner of the IDE. Select “Add…” from the context menu to add “RegExpressionsUtil.pas” file to the project.

In order to be able to use methods of the “TRegularExpressionsEngine” type in our EMS resource code, the first thing is to add “RegExpressionsUtil” unit to the “uses” clause. We could write this manually in the editor, but it is much faster and more fun to it with the wizard.
Make sure that the “uEmailCheckerRes” unit is open in the editor. In the “File” menu select “Use Unit…” to add to the “uses” clause of the EMS resource unit. Select “RegExpressionsUtil” and click on “OK”.

sWe need to modify the implementation of the “GetItem” method in our EMS resource to take the parameter “item” from the HTTP request sent by a client application and pass it to “TRegularExpressionEngine.IsValidEmail” method. If the method returns true, then we are returning “TJSONTrue” or “TJSONFalse” in the HTTP response body otherwise.
Replace the body of the “TEmailCheckerResource1.GetItem” method with the following code:
procedure TEmailCheckerResource1.GetItem(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse);
var LItem: string;
LItem := ARequest.Params.Values[‘item’];

if TRegularExpressionEngine.IsValidEmail(LItem) then
AResponse.Body.SetValue(TJSONTrue.Create, True)
AResponse.Body.SetValue(TJSONFalse.Create, True);
Select “Save All” from “File” menu.

Now our EMS resource is ready and we can start creating a client for it. Before we do it let’s see if it works as expected. Let’s run it without debugging.
Click on the green arrow to run the project without debugging.

EMS Development Server has started and in the log window we can see useful information about loaded resources.
Verify that the EMS Development Server has been started.

We are going to test our EMS. If just click on the “Open Browser” button, the default web browser would start and invoke the built-in “version” resource. Any application that knows how to make an HTTP request can be a client for the EMS server. In our case this is a web browser. Later on we are going to build a mobile client app for the service.
Click on the “Open Browser” button in the EMS Development Server window. Verify that the web browser displays JSON text with EMS version information.

Let’s test our “EmailChecker” endpoint. First we are going to pass to it a string that is not a valid email address. For example “hello”. The server should return “false”.
In the web browser replace “version” with “EmailChecker/hello” and press enter. Verify that the web browser displays “false” string.

Let’s try again, but this time we are going to pass to our “EmailChecker” resource a string that looks like a valid email address. For example This time we should see “true”.
Replace “hello” with and press enter. Verify that the web browser displays “true” string.

Now we are going to build a client application for our EmailChecker EMS resource. We do not need to stop the server. Let’s keep it running. Just right-click on the “Project Group” and select “Add New Project”.
Right-click on the “Project Group” icon in the Project Manager in the top right corner of the Delphi IDE and select “Add New Project” from the context menu.

We are going to create a new Delphi multi-device application that can be compiled for iOS, Android, Windows and Mac from the same code.
In the “New Items” dialog select “Multi-device Application” in the “Delphi Projects” category. Click on OK.

We are going to use an empty application template for our client app.
Select “Blank Application” template in the new “Multi-device Application” wizard and click OK.

It is always a good idea to save your work. We are going to save the new project in the same directory as our EMS service to keep things simple.
Click on “Save All…” in “File” menu. Save the main unit of the new project as “uFormClient”, the project as “EmailCheckerApp” and the project group as “EmailCheckerGrp”.

Don’t forget about giving meaningful names to forms in your application! The name of the form will be “FormClient” and the caption “Email Checker”.
Click on the form to select it in the Object Inspector. Change the “Name” property of the form to “FormClient” and the “Caption” property to “Email Checker”.

We need an edit and a button in our application, so the end user can enter text into an edit and click on the button to verify if it is a valid email address or not. The fastest way of adding components to the form is via “IDE Insight”. I just need to press “Ctrl” and “.” keys at the same time to move focus to the IDE Insight and I can just start typing the name of the component I want to add.
Press “Control” and “.” on the keyboard to switch focus to the “IDE Insight” and start typing “TEdit”. Double click on the “TEdit” in the drop down list to add an edit control to the form. Move the control towards to the top left corner of the form.

In the same way we are going to add a button to the form.
Click on the red cross in the “IDE Insight” edit and type “TBut”. Double click on the “TButton” component to add it to the form.

The user interface of our application is going to be super simple. Just an edit and a button. We need to give a proper caption to the button.
Move the button under the edit control on the form, make it a bit wider and change its “Text” property to “Verify e-mail address”. Make the whole form a little bit smaller.

It is always a good practice to give controls meaningful names. Our user interface is ready. Now it is time to add some code to invoke the EMS EmailChecker resource.
Change the “Name” property of the edit control to “edtEmail”. Change the “Name” property of the button to “btnVerify”.

Let’s keep the structure of our client application clean. It is typically not a good idea to add non-visual components and data access logic directly to a form. It is better to put them in a separate data module. In this way the code is more maintainable. Let’s add a data module to our project for the components and code that is going to access our EMS resource.
In the “File” menu click on “New” and “Other”. In the “New Items” dialog select “Delphi Files” node in the tree view at then “Data Module”. Click OK to add it to the project.

We need to give proper names to the data module unit and to the data module itself. What about “DMEmailChecker”?
In the “File” menu click on “Save All”. Save the data module as “uDMEmailChecker”. In the Object Inspector change the “Name” property of the date module to “DMEmailChecker”.

The key component that provides access to the EMS server is “TEMSProvider”. Let’s add it to the data module.
Drop on the data module a “TEMSProvider” component.

We need to specify in the EMS provider component the host name and the port of our EMS server. In our simple demo the server is running locally, so we are going to enter “” as host and “8080” as the port number. In a real situation that would be the actual IP address of the machine which hosts the EMS server.
Change the “URLHost” property of the “EMSProvider” component to “” and the “URLPort” property to “8080”.

Now we can check if the EMS Provider component can connect to EMS server. We can just right-click on the provider and select “Test Connection”. Alternatively we can click at the “Test Connection” option at the bottom of the Object Inspector.
Right-click on the “EMSProvider1” component and select “Test Connection” from the context menu.

If we can connect to the EMS server, we should see a message with the EMS version information.
Verify that the connection is working. You should see the message with JSON-formatted EMS server version.

In order to invoke a resource in the EMS, we need to have a “backend endpoint” component. Let’s add it to the data module. In the “Resource” property we need to specify the URL resource we want to access. We also need to specify the “ResourceSuffix”, because we want to execute the GET endpoint that takes the “(item}” parameter. We can even check at design time if the resource is accessible right-clicking on the backend and selecting “Execute”.
Drop on the data module “TBackendEndpoint” component. Change the “Resource” property of the backend endpoint component to “EmailChecker”. Change the “ResourceSuffix” property to “{item}”. Right-click on the backend endpoint component and select “Execute”.

If we have not misspelled the resource name, we should get HTTP response code “200”, which means “OK”.
Verify that the endpoint can be executed. There should be a message “Response 200 – OK” displayed.

We need one last component in our data module – “REST Response”. This component needs to be connected to the endpoint backend and is used to store the response received from our backend. In our case that would be “true” or “false”.
Add to the data module “TRESTResponse” component. Change the “Response” property of the “BackendEndpoint1” component to “RESTResponse1”.

We also need to define the parameter that our “EmailChecker” endpoint expects. That’s why need to add an item to “Params” property of the endpoint component.
Select “BackendEndpoint1” component and click on the ellipsis button next to the “Params” property.

Let’s define a parameter. The “Value” property of the parameter is what is going to be sent to the email checker for validation. Let’s put here a string that looks like a valid email. We also need to set the “Name” property to “item”.
Click on the “Add New” button in the params editor window to add a new parameter to the collection. Set its “Name” property to “item”. Set its “Value” property to

We can test execute our email checker at design-time. If we execute the endpoint again, we should see what was sent back from the EMS service in the “Content” property of the response component. Yes. “” appears to be a valid email address.
Right-click on the “BackendEndpoint1” component and select “Execute” from the context menu. There should be a message “Response 200 – OK”. Click on the “RESTResponse1” component. Click on the ellipsis button next to the “Content” property. Verify that it contains text “true”.

Our components are all setup for invoking the email checker endpoint. Before starting with writing some code let’s remove the parameter value and the response data. Clearing the response data can be done very easily from the context menu of the REST response component.
Right-click on the “RESTResponse1” component and select “Clear Response Data” from the context menu.

REST response needs to be really sure that you really want to clear the response data. Yes. We want to clear it.
Click on OK to confirm that you want to clear the response data.

In the moment we are going to write code that will provide the “Value” of the parameter from the edit control.
In the “Structure” view click on the parameter “item” to select it in the Object Inspector. Clear the contents of the “Value” property.

Now we are going to implement public method “IsValidEmail” in our data module that will execute the “EmailChecker” endpoint. This is the method we are going to call from the user interface of our EmailCheckerApp.
Switch to code editor by pressing F12. In the “public” section of the data module type declaration of the “IsValidEmail” method as follows:
function IsValidEmail(s: string): boolean;
Press “Ctrl+Shift+C”. In the generated skeleton of the implementation of the method type the following three lines of code:
BackendEndpoint1.Params[0].Value := s;
Result := RESTResponse1.Content = ‘true’;
Save All.

Before we can use the data module in the code of the application form, we need to add it to its “uses” clause. The fastest way to do so is with the “Use unit” wizard.
Make sure that the “uFormClient” unit is active in the code editor. In the “File” menu click on “Use unit…”. Select the “uDMEmailChecker” unit and click on OK.

The last step is to add code to the form that will be executed when button will is pressed. The contents of the edit will be passed to “IsValidEmail” method of the data module and depending of the result appropriate message is displayed.
Double-click on the button component on the form and type in the following code in the generated “OnClick” event handler:
if DMEmailChecker.IsValidEmail(edtEmail.Text) then
ShowMessage(‘”‘ + edtEmail.Text + ‘” is a valid email address’)
ShowMessage(‘”‘ + edtEmail.Text + ‘” is NOT a valid email address’);
Save All.

The client application is now complete! Let’s run and verify that it works as expected.
Press the green arrow icon to run the client app without debugging. Enter to the edit control. Press on the button and verify that the message that the email is valid is dislayed.

That’s it! We have managed to create the complete system made of the EMS email checking service and a multi-device client app.
The source code of this demo can be downloaded from Embarcadero Code Central.
Share This | Email this page to a friend

Comments are closed.