Watch, Follow, &
Connect with Us

Embarcadero Blogs

Latest Posts


Using Azure Translator Services with Delphi

Often when building IoT applications there is benefit in linking to 3rd party services. e.g. Heating control systems may link to weather services to help detect external influences that may effect their operation. Typically these services are exposed via JSON and REST providing multi-platform access.

Microsoft Azure data services offer access to a wide range of datasets and services and in this blog post I will take you over my journey connecting to the Azure translator data service and achieving translation of text on Windows, Mac OS X, iOS and Android thanks to the REST components and helper classes in RAD Studio XE8.

About Microsoft Azure Translator Data

Microsoft Translator is a WEB API that enables Automatic Translation (Machine Translation) of text between any of the 50 supported languages

The Azure Translator data is used by Microsoft Office, Visual Studio, Bing and many more Microsoft products. It works over REST using a mix of JSON and XML to provide a number of services including translation and text to audio.

To use the Azure Translator data service you must be registered to use the market place and have an app registered to get the required credentials.

Once registered it uses 2 step authentication to provide a token (valid for 10 minutes from issue) that is then used for API calls. It does this with separate URLS’s for the security and the data services.

A great link to steps and URL’s (incase any change) is the Getting Started using Translator API page

Step 1) – Signing up with Microsoft Translator

As with most services, you need to be registered to use them. Documentation of signing up for Translator is found in steps 1 and 2 of this blog post.
http://blogs.msdn.com/b/translation/p/gettingstarted1.aspx 

Once registered, Ensure you sign Up for the $0.00 per month option to get your free translation credits.

Step 2) Registering an App

Now you are signed up, you need to register your application. (ok we don’t have one yet, so we will just make one up for testing). To register your application for use with the Translation service visit https://datamarket.azure.com/developer/applications and choose Register.

On the registration screen you need to enter in a Client ID (no longer than 20 characters or it will not work from my experience) and also enter a name for your application and a description (anything will do as you can change it later) Finally a redirect URL (your website home page will do, its not used with the REST component setup, but is required)

Azure_Translator_Register_Delphi

 

At this point you will need to copy down the two parts of data I have highlighted on the reg form. The Red part is what you have typed in (Client ID) and the blue part (Client Secret) which is  generated for you by Azure. These two are used to get your session token later on that allows you to talk to the API’s. – Don’t worry if you hit create before you make a note of them as you can open it back up from the applications page at a later point.

Step 3) Building the app using Azure Translation Service in Delphi

Click here for the API documentation for Azure Translator that I’ll be referencing to.

To use a REST service you first need to know what API’s the service exposes, the parameters it requires and then the response to expect. So lets start there…

With REST the API comes in the form of a URL base that then has methods (resources) appended. Each resource has parameters to define the data exchanged, but there are a few ways of passing parameters. The most typical is a URL Segment, but there are also Body and Header parameters. You achieve this easily in Delphi use the parameter property of the TRESTRequest component. (I will get to this shortly).

3.1 – Getting the access token

It is common practice with REST that there is an authorisation step that provides you a session token for subsequent calls. The first stop to using Translator is obtaining an Access Token to use with your API calls.  From reading the documentation and scanning the C# example I was able to locate the Base URL,

 https://datamarket.accesscontrol.windows.net/v2

and the resource for authentication

OAuth2-13

For the resource there are a number of parameters, all of them URL segment parameters and as described in the document this is a HTTP post method.

Parameter Description
client_id Required. The client ID that you specified when you registered your application with Azure DataMarket.
client_secret Required. The client secret value that you obtained when you registered your application with Azure DataMarket.
scope Required. Use the URL http://api.microsofttranslator.com as the scope value for the Microsoft Translator API.
grant_type Required. Use “client_credentials” as the grant_type value for the Microsoft Translator API.

The first two are linked to the data that we generated when registering the application in Step 2 above while the other two always have the same, but required, values.

So now we know what to call, how do we setup the components to call this?

We are going to use 3 components.

TRESTClient – To define where the Base URL is.
TRESTRequest – To define the resource we want to use and the parameters we are passing
TRESTResponse – To collect and store the reply

Compoents for REST call

Adding the three components to your data module or application form should link them all together.

On the REST Client I set the base URL (see above for value) and on the REST Request I set the resource to OAuth2-13 and checked to make sure that the method was a rmPOST. Opening the Params property on the TRESTRequest I also added in the 4 parameters.

RESTAuthParams

You can either set the Client ID and Client Secret in the parameter at design time, or you can define that in code using the TRESTRequest.Params.ParamByName(‘name’).value property e.g.

RequestAuthToken.Params.ParameterByName(’client_secret’).Value := ‘MyClientSecret’;

RequestAuthToken.Params.ParameterByName(’client_id’).Value := ‘MyAppID’;

If you set the values at design time you should be able to right click on the Request and Execute to populate the Response.content. Alternatively, call the Request.Execute at runtime.

3.2 – Finding and extracting the Token

So now we know how to ask for the token, how do we extract it and work with it? What comes back?

The documentation defines the response properties that are returned. These can be queried or using the TRESTResponse instance GetSimpleValue method.

Property Description
access_token The access token that you can use to authenticate you access to the Microsoft Translator API.
token_type The format of the access token. Currently, Azure DataMarket returns http://schemas.xmlsoap.org/ws/2009/11/swt-token-profile-1.0 , which indicates that a Simple Web Token (SWT) token will be returned.
expires_in The number of seconds for which the access token is valid.
scope The domain for which this token is valid. For the Microsoft Translator API, the domain is http://api.microsofttranslator.com.

AuthCode

In the code example above (click to make bigger), you can see the

Client secret and Client ID get set at run time.
The request is executed by calling .Execute;
The response is checked for the access_token return parameter.
The request components that I will use to call the API’s (RESTRequestTranslate and RESTRequestPlay) now I am authorised have the returned access token set as the value for use.  – I’ll cover the setup of these shortly)

New – System.TNetEncoding

The final two lines use TNetEncoding (a really useful class with class functions) to show a decoded Token. No value other than curiosity, but it does show how to decode a URL value (there is also HTML and Base64 decoding helper methods) .

I wouldn’t recommend that for a live application.

3.3 – Calling the Translate API with the Token

To recap. I have used the TRESTClient to point to the BaseURL of the service. Used the TRESTRequest to define the resource and parameters that need to be passed, set the parameters and fetched and retrieved the token, which has been set into the Authorization parameter of another TRESTRequest that I have called RESTRequestTranslate.

So there are a few things to cover here still.

The setup of RESTRequestTranslate and its associated components, especially the parameters
And what comes back from the Translate API

3.3.1 Component Setup to call the API with the Access token.

In a very similar way to getting the Access token, we use the same components to call the live API. Using the same process as before its possible to identify the Base URL and parameters – full list of methods here https://msdn.microsoft.com/en-us/library/ff512419.aspx

Base URL

http://api.microsofttranslator.com/v2/Http.svc

and resources I have used

Translate

to convert text from one language to another and

Speak

to create an audio file based on text passed in.

Both have separate parameter lists so I’m just going to concentrate on translate for this post, however the sample has both in there.

Because all the resources share the same base URL, the TRESTRequests can share the same TRESTClient instance.  (see the green section in the diagram below.

In the documentation for the Translate API method, it defines the parameters that are required, but also the type of parameter required.

Most are segment URL values, but the authorization token must be a HTMLHeader defined as ‘bearer ‘+token.

To create the parameters for URL Segments its easy to define them as part of the resource.  – see image below.

TranslateAPI_Delphi_Component_Setup

Translate?text={text}&from={from}&to={to}

The {brackets} define a parameter name when part of the resource. They automatically get added as URL segment. (or you can add them manually yourself)

Finally. Add in the Authorization token by clicking on the Add icon on the Parameters editor. Making sure to select Kind pkHTTPHEADER.

Typically Parameters are encoded automatically for us so we don’t need to mess around with encoding values, however because the token returned is already encoded, we need to set the option to DoNotEncode on the Authorization token.

Authorization Delphi REST Param HTTPHeader

So we are now all set up with the components.

In code now, we just need to set the language from and to (these are specified in the documentation or can be collected from another API call) and the text to translate. (see below – The Text is set using LiveBindings however – see further down for that setup or just do it in code)

SettingParams_Delphi_Rest_in_code

3.3.2 – What comes out?

So here is that application at run time. I’ve selected Auth already and now choose Translate

LiveBindings_Setting_Params_Delphi_Rest

You will see that the Response Content is actually an XML data packet. For that you can use the XML Document interfaces to extract the value, (I’ll cover that in another post) but there we have it! Translated text :-)

Now as this is a FMX (FireMonkey) application, I can now go and use this on iOS, Android or Mac OS X as well as my local windows machine.

Translator Code Example – Download

The code I cover in this blog is available for download. however I have made it even easier to use…

Must have – BONUS DOWNLOAD

Included in the download is a set of classes I have created to

Encapsulate fetching and managing the token (inc lifespan)
Manage setting the parameters
Conversion of return data from XML to text.

see Project TranslateCompsExample in the project group – enabling code like…

procedure TForm15.btnTranslateClick(Sender: TObject);
var
Translator : TAzureTranslator;
Str : string;
begin
Translator := TAzureTranslator.Create(Self);
try
Translator.SourceLanguage := ‘en’;
Translator.TargetLanguage := ‘da’;
Translator.AccessToken := TokenManager;
Str := Translator.Translate(‘Delphi Rocks!’);
memo1.Lines.Text := Str;
finally
Translator.Free;
end;
end;

Get the code now, and start adding translation and playback of audio into your applications! http://bit.ly/ccAzureTranslatorDelphi

Happy Coding!

The post Using Azure Translator Services with Delphi appeared first on Stephen Ball's Technical Blog.


posted @ Tue, 30 Jun 2015 10:48:37 +0000 by Stephen Ball


Google’s Project Brillo, Weave, and Delphi

If you followed Google I/O then you no doubt heard about Google’s announcements in the Internet of Things space: Project Brillo and Weave. Brillo is Google’s new operating system for Internet of Things devices, and Weave is the language for … Continue reading

posted @ Mon, 29 Jun 2015 21:10:08 +0000 by Jim McKeeth


RAD Studio and Delphi XE8 BOGO and Discount End Tuesday June 30, 2015

Last chance for some of these offers on RAD Studio XE8, Delphi XE8 and C++Builder XE8.


posted @ Mon, 29 Jun 2015 09:55:00 +0000 by Tim Del Chiaro


The question is: Will the latest Xcode (6.3.2) work with Delphi XE8 Update 1?

I received an email just now from another David, saying "I haven’t found this information on your website…The question is: Will the latest Xcode (6.3.2) work with Delphi XE8 Update 1?". I have installed RAD Studio XE8 Subscription Update 1, installed the updated PAServer on my Mac to match the IDE, and I have Xcode version 6.3.2 running on my Mac. I am running iOS 8.3 on my iPhone 6 and iPad Air 2. To answer David (I also replied to his email): All is good with my development, testing and deployment of iOS and OSX apps.

Here are the screen grabs of my about boxes for both tools:

RAD Studio XE8 Subscription Update 1 about box

Xcode 6.3.2 about box

My guidance to developers is always, when you learn that there is a platform update, stay tuned to our blogs and wait until you hear from us that it is safe to go in the water before installing updates to the underlying platforms and devices we are using and targeting.  We give general platform version guidance at "Supported Target Platforms" pages (and links to specific target platforms) at http://docwiki.embarcadero.com/RADStudio/XE8/en/Supported_Target_Platforms.

I will work with our team to create a single spot where we can always update the version number dependencies and support we have, especially given that the platform vendors are making impactful changes these days even in what would normally be considered minor updates.  Stay tuned for a permanent URL.

 


posted @ Fri, 26 Jun 2015 19:14:53 +0000 by David Intersimone


Project Management in Rapid SQL - DBA and Developer Skill Sprints

In this Skill Sprint, Scott Walz covers how to manage projects in Rapid SQL. This functionality is also available in DBArtisan. Learn how to create a new project and intialization options (from a database, existing file or version control). Then learn about the wizard options and how to complete the project setup. Then learn how to work with the project including Build Order, creating new Subfolders, adding files and objects, working with version control, updating project properties and more.

[embed=videolink]{"video":"https://www.youtube.com/watch?v=PpQauWuWUu8","width":"undefined","height":"undefined"}[/embed]

Embarcadero® Rapid SQL® is the intelligent SQL IDE empowering database developers and DBAs the ability to create high-performing SQL code on all major databases from a single interface. This toolset simplifies SQL scripting, query building, object management, debugging and version control with intuitive, innovative tools.


posted @ Wed, 24 Jun 2015 20:43:56 +0000 by Tim DelChiaro


What’s new and fixed in RAD Studio, Delphi and C++Builder XE8 Subscription Update 1

Two articles on our DocWiki and Community site provide the details about what is new and fixed in the recently released RAD Studio, Delphi and C++Builder XE8 Subscription Update 1. The update is available via the registered user downloads are (both in ISO and Web install versions). You can tell if you have Update Subscription by using the Help | License Manager menu item.  Select your registered XE8 release and look in the center panel of the License Manager window and you will see the following text - "Is Subscription: Yes" .

For my RAD Studio XE8 original release, my License Manager displays the following (serial # edited out):

Title:  RAD Studio XE8 Architect Named User
License file name:  .8216_52.1427845488219.slip
Trial license:  No
License Expiration Date:  3/1/2016
Days Left:  256
Is Subscription: Yes
Subscription Expiration Date: xx/xx/xxxx
License Type:  Workstation
Serial number:  xxxx-xxxxxx-xxxxxx-xxxx
Registered:  Yes
Platform:  Windows
Commercial use:  Yes

Before you install XE8 Subscription Update 1, you need to uninstall the original XE8 release. You can choose to keep your registry settings so that your known packages and IDE settings will be kept when you do the update 1 install.

What’s new in Delphi and C++Builder XE8 Subscription Update 1 - http://docwiki.embarcadero.com/RADStudio/XE8/en/What%27s_New_in_Delphi_and_C%2B%2BBuilder_XE8#What.27s_New_in_XE8_Subscription_Update_1

Subscription Update 1 Fix List for RAD Studio XE8, Delphi XE8, and C++ Builder XE8 - http://edn.embarcadero.com/article/44470


posted @ Wed, 24 Jun 2015 20:41:21 +0000 by David Intersimone


On-Demand Webinar: Become Agile with Data Modeling

On-Demand Webinar:
Become Agile with Data Modeling

The world of data has drastically changed over the past decade, and we’re now living and working in the time of big data, NoSQL and self-service BI. Today’s data architects must respond and adapt to new Agile development approaches in their modeling environment. However, it’s not the technique that makes it Agile, it’s the approach to the model itself. In this on-demand webinar, Rick van der Lans, an international consultant and data modeling expert, shares his insights on several aspects of Agile data modeling, including:

The urgent need for Agile data modeling and how to use it to understand data
The impact of big data, self-service BI and NoSQL on data modeling
Tips for designing Agile data models and linking business concepts to them

Ensure that your data models stay relevant within an Agile development environment. Learn and share the value of Agile data modeling.

CLICK HERE TO VIEW

About the presenter:

Rick van der Lans is an independent analyst, consultant, author and lecturer specializing in data warehousing, business intelligence, database technology and data virtualization. He works for R20/Consultancy. Rick is chairman of the annual European Enterprise Data and Business Intelligence Conference (organized annually in London). He writes for Techtarget.com, B-eye-Network.com and other websites. He has written several successful IT books.


posted @ Wed, 24 Jun 2015 09:54:13 +0000 by mohammad


Linking object/TValue to a control, VCL to FireMonkey

In this post, Tag properties and using Rtti.TValue data property as an alternative in FireMonkey / FMX.

Click / Select… now what?

One common challenge we face as developers is that the user clicks on something, we now need to find the object that is required to do the next task based on the item selected.

Sometimes this is from a dataset linked to the control and it may be taken care of for us, other times, we may need to find a specific object that then has the data we need.

Most of us have done it at some time….

Yes… that naughty little trick of using the tag property of a TComponent to store a pointer to an instance of an object that you want a quick way of reaching.

I remember doing this in a POS system where buttons that represented different stock items were linked to dynamically created screens. I also remember often using the TListView and thankfully, the TListViewItem in VCL had a Data property (of type Pointer) that you can set at runtime to an instance of an object. This was a little less naughty when moving to 64bit coding when Integer and Pointer all of a sudden became different sizes, (and if it wasn’t for some insight from the Delphi team to swap tag to NativeInt – lots of code would have broken).

The problem with a pointer property (or using a NativeInt to achieve the same goal) is that it leaves a lot of typecasting in your code, which never sat easy with me.

Avoiding tag / pointer properties….

A number of years ago, (probably when I was still using Delphi 5) I started to avoid using the tag property as a pointer holder by replacing the components I was creating with a new class that descended from the original component. e.g.

TMyButton = class(TButton)
strict private
FFoo : TFoo;
public
property Foo : TFoo read FFoo write FFoo;
end;

This approach reduced errors from typecasting, I had exactly what I was looking for and could write nicer code with less typecasting. I also often added the object to the constructor to make it easier and less lines of code.

Problems?

I also had times that I needed access to a number of objects, so would end up with multiple objects listed, when in reality I only needed to get to one or two properties of each objects.

I also had times that I had objects of different type (something a pointer is fine for), but it was always to get the ID value or something that was common.

FireMonkey Tag, TagObject, Data

FireMonkey components have not only a Tag property (that mimics the VCL, but it also provides 3 extra Tag’s

Tag Properties

Tag
TagObject
TagFloat
TagString

This can be easier to use, but there are sometime other values you want to pass and this is where the Data property comes into its own.

Data Property

Data is a TValue (from System.Rtti) and can be used to store pretty much anything. There are a load of helper classes for working with it, and some components even provide Data as an array with a string name.. (e.g. see the TListViewItem).

An example of using this is as follows

type
TMyEnum = (Foo, Fee);
procedure TForm14.FormCreate(Sender: TObject);
var
I: TListViewItem;
begin
I := ListView1.Items.Add;
I.Data['Foo'] := TValue.From(‘Hello’);
I.Data['MyEnum'] := TValue.From(TMyEnum.Fee);
end;
procedure TForm14.ListView1ItemClick(const Sender: TObject; const AItem: TListViewItem);
var
Value : TMyEnum;
begin
ShowMessage(AItem.Data['Foo'].ToString);
Value := AItem.Data['MyEnum'].AsType<TMyEnum>;
ShowMessage(TRttiEnumerationType.GetName<TMyEnum>(Value));
end;

You can see that even Enums can be passed using the Data property.

Using RTTI and the Data.TValue option provides a lot of flexibility in FMX for linking to objects or data.  Sometimes you may not need to create an instance of an object just to store the one or two lines of data that you required which can be useful and provides less memory to manage.

Summary

Thinking back to my POS screen, just having a string tag would have reduced a class that I needed to write test and manage the memory for.

Personally, for me, the data property is much more useful that an old style pointer – the TListViewItem with an array of TValues is also very useful.

The post Linking object/TValue to a control, VCL to FireMonkey appeared first on Stephen Ball's Technical Blog.


posted @ Wed, 24 Jun 2015 09:54:13 +0000 by Stephen Ball


InterBase XE7 – Update 3

InterBase XE7 – Update 3

InterBase XE7 update 3 is now available for general release.

What’s new in InterBase XE7 – Update 3?

In my post about InterBase XE7 Update 2 I mentioned about the new reserve words that are used by Change Views and how to work with reserved words by using “quotes”.

CHANGE,
CHANGED,
INSERTED,
UPDATED
DELETED

With update 3, InterBase XE7 only adds these words to the reserved list once Change Views are active in the database. This will make it easier for users to migrate to InterBase XE7 and take advantage of the other cool features like partial data dumps, improved index handling etc.

What’s fixed in InterBase XE7 update 3?

The resolved defects are documented on the InterBase XE7 DocWiki resolved defects page .

 

Downloading InterBase XE7 update 3

Embarcadero CodeCentral “Registered Users” can download the patch binaries (Server/Desktop/Developer/Trial) for Windows and Linux, and, ToGo Edition. You can find the downloads at http://cc.embarcadero.com/reg/interbase

For new users, the trial and developer editions are available for free at http://www.embarcadero.com/products/interbase/downloads

The post InterBase XE7 – Update 3 appeared first on Stephen Ball's Technical Blog.


posted @ Wed, 24 Jun 2015 09:54:13 +0000 by Stephen Ball


Exploring the new TListView Platform Options on iOS in RAD Studio XE8

Options

FireMonkey’s underlying visual control architecture has been significantly overhauled in XE8 to enable multiple presentation implementations per control called “ControlTypes” - in particular, native OS control presentations can be utilized. The new underlying architecture is MVC based and is backward compatible enabling developers to choose at design time between Styled and Platform control types on a per control* basis (*for controls that include both control types). This allows you to select whether a control will be implemented at runtime by FireMonkey’s GPU driven rendering or implemented by the underlying operating system.

Image

In XE8 for Universal iOS 32-bit and 64-bit apps, six key performance critical controls now have iOS native platform control types built–in, including TEdit, TListView, TMemo, TSwitch, TCalendar and TMultiView. In the future we plan to add platform control types for other operating systems and components.

Today, I thought I would highlight some of the new iOS native platform options for TListView.

TListView has a ControlType property. If you set it to Platform, you will get the iOS platform native rendering at runtime using the underlying OS. This also allows you to take advantage of the NativeOptions property. If you set it to Styled, it will use the bitmap-based FireMonkey styles (either using the default built-in styles or custom styles applied via a StyleBook) and the control will be implemented by FireMonkey’s GPU driven rendering at runtime.

The default TListView item appearance modes such as ListItem, ImageListItem and ImageListItemBottomDetail are supported in both the Styled and Platform modes. Custom appearance modes are supported in the Styled mode.

  1. Grouped 
    1. This adds grouping support to the ListView like you see in the iOS settings dialog, for example. This option expects headers to be set up. 
  2. Indexed
    1. This adds alphabetical sorting (displayed via letters on the right). This option expects headers to be set up to add indexing (i.e. by enabling this property and binding ListView1.ItemHeader.Text into FDMemTable1.FoodName).
  3. Styled    
    1. If you enable this setting while using ControlType=Platform, you get the platform native Listview rendering at runtime on iOS with the custom font settings that you have set. This will override teh default platform native font settings for TListView on iOS and allow you to define your own custom fonts, sizes and attributes (as long as you are using one of the default item appearance modes).

Below is an example application that I built that showcases the 3 platform native options for TListView on iOS using some sample data. The ListView is bound into sample data using the LiveBindings Designer.

LiveBindings Delphi XE8

In this demo, I added three buttons styled as segmented controls to toggle the platform native options:

procedure TFoodList.GroupedClick(Sender: TObject);
begin
 if TListViewNativeOption.Grouped in ListView1.NativeOptions then
    ListView1.NativeOptions := ListView1.NativeOptions - [TListViewNativeOption.Grouped]
  else
    ListView1.NativeOptions := ListView1.NativeOptions + [TListViewNativeOption.Grouped];
end;

procedure TFoodList.IndexedClick(Sender: TObject);
begin
 if TListViewNativeOption.Indexed in ListView1.NativeOptions then
    ListView1.NativeOptions := ListView1.NativeOptions - [TListViewNativeOption.Indexed]
  else
    ListView1.NativeOptions := ListView1.NativeOptions + [TListViewNativeOption.Indexed];
end;

procedure TFoodList.StyledClick(Sender: TObject);
begin
 if TListViewNativeOption.Styled in ListView1.NativeOptions then
    ListView1.NativeOptions := ListView1.NativeOptions - [TListViewNativeOption.Styled]
  else
    ListView1.NativeOptions := ListView1.NativeOptions + [TListViewNativeOption.Styled];
end;

end. 

 


posted @ Tue, 23 Jun 2015 18:39:20 +0000 by sarinadupont


Server Response from: BLOGS1