<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Middleware &#8211; Xojo Programming Blog</title>
	<atom:link href="https://blog.xojo.com/tag/middleware/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.xojo.com</link>
	<description>Blog about the Xojo programming language and IDE</description>
	<lastBuildDate>Mon, 12 Jun 2023 11:44:56 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>
	<item>
		<title>Guest Post: Adding Language Translation to Your Xojo Apps</title>
		<link>https://blog.xojo.com/2019/05/13/guest-post-adding-language-translation-to-your-xojo-apps/</link>
		
		<dc:creator><![CDATA[Tim Dietrich]]></dc:creator>
		<pubDate>Mon, 13 May 2019 10:00:17 +0000</pubDate>
				<category><![CDATA[Guest Post]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[API]]></category>
		<category><![CDATA[App Localization]]></category>
		<category><![CDATA[CURL]]></category>
		<category><![CDATA[Google]]></category>
		<category><![CDATA[Middleware]]></category>
		<category><![CDATA[Monkeybread Software]]></category>
		<category><![CDATA[Plugins]]></category>
		<category><![CDATA[Translation]]></category>
		<category><![CDATA[Web Service]]></category>
		<guid isPermaLink="false">https://blog.xojo.com/?p=5735</guid>

					<description><![CDATA[I've been amazed at the speed and accuracy of the Amazon Translate service. And after developing the AWSTranslator class, I was able to quickly and easily add language translation to my client's middleware app.]]></description>
										<content:encoded><![CDATA[<p>Recently, I was asked by a client if it would be possible to build language translation functionality into a Xojo-based middleware solution that I had developed for them. The Xojo app obtains product information (including product names, descriptions, and other marketing-related information) from suppliers via a SOAP call, and returns the data in a JSON-encoded response. They wanted to be able to translate the product information, which is provided in English, to other languages (such as French, German, etc). The client wanted something similar to <a href="https://translate.google.com/">Google Translate</a>. However, they wanted the translation function to be built directly into the app and to be performed &#8220;on demand.&#8221;</p>
<p>I did some research and found that Amazon provides a service that does exactly what the client was asking for. The service, called <a href="https://aws.amazon.com/translate/">Amazon Translate</a>, is available as one of many services that are available through Amazon Web Services.</p>
<p>In this post, I&#8217;ll walk you through the process of getting signed up for Amazon Translate, and then share some code that you can use to add language translation to your own Xojo projects. We&#8217;ll use the MBS Xojo CURL Plugin, which makes calling the Amazon Translate API easy. But first, let&#8217;s learn a little about Amazon Translate.</p>
<p><span id="more-5735"></span></p>
<h3><b>Amazon Translate</b></h3>
<p>Amazon Translate is an API that can be used to translate text on demand. You send it text in a &#8220;source language,&#8221; tell the API what that source language is, as well as the &#8220;target language&#8221; that you want the text translated to. The API responds with the translated text.</p>
<p>Amazon Translate uses machine learning and neural networks that have been designed specifically for language translation. When performing a translation, the service reads the text one sentence at a time, and reads each word individually, to determine the meaning of a sentence. In other words, the service doesn&#8217;t just translate words. Instead, it&#8217;s acting as an interpreter. This results in translations that are extremely accurate.</p>
<p>In order to use Amazon Translate, you&#8217;ll need an <a href="http://aws.amazon.com/">AWS account</a>. If you already have an AWS account, log into the account.</p>
<p>Next, you&#8217;ll need to create an &#8220;Identity and Access Management&#8221; (IAM) user. To do so, under Services, select &#8220;IAM&#8221; (which can be found in the &#8220;Security, Identity, &amp; Compliance&#8221; category). This will present you with the IAM Dashboard.</p>
<p>Under Groups, create a new group and give it a recognizable name. For example, you might call the group &#8220;translate.&#8221; As you are creating the group, give it the &#8220;TranslateFullAccess&#8221; permission.</p>
<p>Next, create an IAM user. Under Users, click the &#8220;Add user&#8221; button. Give the user a name such as &#8220;XojoTranslater.&#8221; For the &#8220;AWS access type&#8221; be sure to select &#8220;Programmatic access.&#8221; Add the user to the &#8220;translate&#8221; group that you created above. There&#8217;s no need to assign any tags to the user, so you can skip that step.</p>
<p>And finally, create an Access key for the user. Be sure to make note of both the &#8220;Access key ID&#8221; and &#8220;Secret access key&#8221; values that are automatically assigned. You&#8217;ll need these in order to make API calls.</p>
<h3><b>The MBS Xojo CURL Plugin</b></h3>
<p>If you don&#8217;t already have the <a href="https://www.monkeybreadsoftware.de/xojo/plugin-curl.shtml">MBS Xojo CURL Plugin</a>, download it and install it. To install the plugin, simply drag it into the Xojo &#8220;Plugins&#8221; folder.</p>
<p>The project will work with an unlicensed version of the MBS Xojo CURL Plugin. In this case, you&#8217;ll occasionally see a popup message reminding you to purchase a license. However, I highly encourage you to purchase a license. You can license the plugin individually, or as part of the MBS Complete plugin bundle.</p>
<h3><b>The Xojo Example Project</b></h3>
<p>To demonstrate the Amazon Translate service, I&#8217;ve put together an example Xojo desktop project (<a href="https://s3.amazonaws.com/tdietrich-opensource/aws-translate-demo.xojo_binary_project.zip">project file</a>). Before running the application, be sure to set the three App-level properties: AWSAccessKeyId, AWSSecretAccessKey, and the AWSRegion. For the AWSAccessKeyId and AWSSecretAccessKey properties, use the values that you set when you created the Access key for the user. For the AWSRegion, refer to <a href="https://docs.aws.amazon.com/general/latest/gr/rande.html">this</a> and use the value that makes the most sense for you.</p>
<p>Once you&#8217;ve configured the app, run it, and it will look something like this.</p>
<p> </p>
<h3><b>The Xojo Code</b></h3>
<p>Let&#8217;s take a look at some of the code.</p>
<p>The AWSTranslator class is a subclass of the CURLSMBS class. The class does two important things: It provides access to a list of the languages that are supported, and provides a method for calling the Amazon Translate API.</p>
<p>The &#8220;Languages&#8221; property is a dictionary that you can use to get the names of the languages that Amazon Translate supports and the corresponding language codes. The example app uses this dictionary to populate the &#8220;Translate From&#8221; (SourcePopupMenu) and &#8220;Translate To&#8221; (TargetPopupMenu) popup menus.</p>
<p>The Translate method creates the payload that gets sent to the Amazon Translate API, and sets special HTTP headers that are needed in order to call the API. But most importantly, it uses the CURLSMBS class&#8217;s &#8220;SetupAWS&#8221; method to configure the CURL instance so that all of the steps that are required to &#8220;sign&#8221; the API request are done automatically. This is an amazingly convenient function of the MBS Xojo CURL Plugin. You can get a sense of what&#8217;s involved in signing the request <a href="https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html">here</a>.</p>
<p>To translate text using the AWSTranslator class, you create an instance, configure it with your IAM credentials and AWS region, pass it the source language text, the source language code, and the target language code. In the example app, this all handled in the Window1.Translate method. The values are pulled from the App-level properties, as well as the various window controls. Finally, you call the AWSTranslator instance&#8217;s Translate method. If the translation is successful, the translated text will be available via the TranslatedText property. If any errors occur, the ErrorType and ErrorMessage properties will be set.</p>
<p>The &#8220;Estimated Translation Cost&#8221; is calculated whenever the Source Text changes. The value is calculated by taking the length (number of characters) of the Source Text and multiplying it by 0.000015 (the average cost for translating a single character).</p>
<h3><b>Wrapping Up</b></h3>
<p>I&#8217;ve been amazed at the speed and accuracy of the Amazon Translate service. And after developing the AWSTranslator class, I was able to quickly and easily add language translation to my client&#8217;s middleware app.</p>
<p>I hope you&#8217;re equally impressed by the Amazon Translate service, and that you find the AWSTranslator class to be helpful in your own Xojo projects.</p>
<p><i>Tim Dietrich is a custom software developer based in Richmond, Virginia. To learn more, visit: <a href="https://timdietrich.me/" target="_blank" rel="noopener noreferrer" data-saferedirecturl="https://www.google.com/url?q=https://timdietrich.me&amp;source=gmail&amp;ust=1552488320387000&amp;usg=AFQjCNEDiwUxo_XLnpKX-Bt3nL8FIQTxZA">https://timdietrich.me</a></i></p>


<figure class="wp-block-image"><img fetchpriority="high" decoding="async" width="1024" height="711" src="https://blog.xojo.com/wp-content/uploads/2019/05/Screen-Shot-2019-04-01-at-4.21.01-PM-1024x711.png" alt="" class="wp-image-5753" srcset="https://blog.xojo.com/wp-content/uploads/2019/05/Screen-Shot-2019-04-01-at-4.21.01-PM-1024x711.png 1024w, https://blog.xojo.com/wp-content/uploads/2019/05/Screen-Shot-2019-04-01-at-4.21.01-PM-300x208.png 300w, https://blog.xojo.com/wp-content/uploads/2019/05/Screen-Shot-2019-04-01-at-4.21.01-PM-768x533.png 768w, https://blog.xojo.com/wp-content/uploads/2019/05/Screen-Shot-2019-04-01-at-4.21.01-PM.png 1532w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Web Services Part II: Xojo Web, at your service</title>
		<link>https://blog.xojo.com/2018/11/08/web-services-part-ii-xojo-web-at-your-service/</link>
		
		<dc:creator><![CDATA[Javier Menendez]]></dc:creator>
		<pubDate>Thu, 08 Nov 2018 10:00:10 +0000</pubDate>
				<category><![CDATA[Cross-Platform]]></category>
		<category><![CDATA[Learning]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[HTTPSocket]]></category>
		<category><![CDATA[Middleware]]></category>
		<category><![CDATA[Web Service]]></category>
		<category><![CDATA[webdev]]></category>
		<category><![CDATA[Xojo Programming Language]]></category>
		<guid isPermaLink="false">https://blog.xojo.com/?p=5118</guid>

					<description><![CDATA[In a previous entry we started to dig into web services with Xojo. The first post focused on the backend (server side), creating the Xojo&#8230;]]></description>
										<content:encoded><![CDATA[<p>In a <a href="https://blog.xojo.com/2018/09/26/web-services-xojo-web-at-your-service/">previous entry</a> we started to dig into web services with Xojo. The first post focused on the backend (server side), creating the Xojo app acting as middleware between the clients and the database that holds your data. We are using SQLite as the backend engine but it would not be difficult to change to other supported database engines like PostgreSQL, MySQL (MariaDB), Oracle or SQL Server, and even ODBC; all of these are supported by Xojo!<span id="more-5118"></span></p>
<p>In this second post on the topic we will focus on the client side desktop app that will be in charge of creating the requests using the web service published API. This desktop app will send new data to our web server app so it can be added to the backend database.</p>
<p>The main topics are:</p>
<ul>
<li>Creating a subclass from the <code>URLConnection</code> class</li>
<li>Dealing with the data received from the server as result for the request</li>
<li>Encoding a <code>JSONItem</code> for sending data to the web service</li>
</ul>
<p>As stated in the previous entry, the example doesn&#8217;t include the normal (and recommended) verifications on the data provided and received or the check on possible errors; we are only focused on the main topic.</p>
<h2>Creating an URLConnection subclass</h2>
<p>Let&#8217;s start by creating a new desktop project. Add a new Class using <code>Insert &gt; Class</code> and use the Inspector to assign <code>URLConnection</code> as the <b>Super Data Type</b> as shown in the picture:</p>
<p><img decoding="async" class="size-full wp-image-11609 aligncenter" src="https://blog.xojo.com/wp-content/uploads/2018/11/URLConnectionSubclass.png" alt="" width="602" height="300" srcset="https://blog.xojo.com/wp-content/uploads/2018/11/URLConnectionSubclass.png 602w, https://blog.xojo.com/wp-content/uploads/2018/11/URLConnectionSubclass-300x150.png 300w" sizes="(max-width: 602px) 100vw, 602px" /></p>
<p>With the just added class still selected in the Navigator (the leftmost column in the IDE Window), add a new property to it (<code>Insert &gt; Property</code>). We will use this property so it points to a DesktopListBox in our user interface, and so we can update it with the data received from our web service. With the just added property still selected, use the Inspector to set its Data Type and Name (text label used from our code to refer to such property) as follows:</p>
<ul>
<li><b>Name</b>: List</li>
<li><b>Type</b>: DesktopListBox</li>
<li><b>Scope</b>: Private</li>
</ul>
<p>Note that we set the scope as <b>Private</b>. This means that this property can be accessed only from the instances of the class, and not those that are created from other data types or even those created as subclasses from this class.</p>
<h2>URLConnection: Asynchronous communications</h2>
<p>Why would we want to maintain a reference to a ListBox control in our URLConnection class? As with any kind of problem, we can take several approaches in order to solve it. In this case, is a very convenient way to get a reference to the control we want to update as we will be using the URLConnection asynchronously.</p>
<p>Once we call the request against our web service, the execution of the app will not be paused until we receive a response, this allows the user to do other operations if they want. In this case the class instance, via the <code>ContentReceived</code> event, will be responsible to receive the new data from the web service, so we can use it.</p>
<p>In fact, this is our next step. With our <code>URLConnection</code> subclass still selected in the Navigator, add a new Event Handler to it (<code>Insert &gt; Event Handler…</code>). In the resulting window, choose the <code>PageReceived</code> option from the list and confirm the selection, so the event will be added to the class under the <b>Event Handlers</b> section.</p>
<p><img decoding="async" class="size-large wp-image-11610 aligncenter" src="https://blog.xojo.com/wp-content/uploads/2018/11/URLConnection-ContentReceived-1024x563.png" alt="" width="1024" height="563" srcset="https://blog.xojo.com/wp-content/uploads/2018/11/URLConnection-ContentReceived-1024x563.png 1024w, https://blog.xojo.com/wp-content/uploads/2018/11/URLConnection-ContentReceived-300x165.png 300w, https://blog.xojo.com/wp-content/uploads/2018/11/URLConnection-ContentReceived-768x423.png 768w, https://blog.xojo.com/wp-content/uploads/2018/11/URLConnection-ContentReceived.png 1236w" sizes="(max-width: 1024px) 100vw, 1024px" /></p>
<p>Now, with the just added Event Handler still selected, write the following snippet of code in the associated Code Editor:</p>
<pre>#Pragma Unused url

If HTTPStatus = 200 Then // We received an OK as the status for our request
  If Content.Length &lt;&gt; 0 Then // And we have data to process as part of the reply
    List.RemoveAllRows // So we delete previous existing entries in the associated ListBox Control
    content = content.DefineEncoding(Encodings.UTF8) // We set the encoding for the received data
    
    Var items As Dictionary = ParseJSON(content) // And proceed to create a new dictionary from the received data in JSON format
    items = items.Value("AllAlbums") // We get all the items for the key 'AllAlbums'…
    For Each item As DictionaryEntry In items // …iterating on them…
      Dim tempDict As Dictionary = item.Value // …and retrieving the dictionary (JSON item) for it…
      Dim title As String = tempDict.Value("title") // …so we finally access the desired value
      list.AddRow title
    Next
  End If
End If</pre>
<p>The code is commented so you can follow what happens in each line in the process; but it is worth it to point out that the <code>ContentReceived</code> event gives us all the parameters we need in order to work with the data sent from the web service:</p>
<ul>
<li><b>URL</b>: The URL returned as the reply for our request</li>
<li><b>HTTPStatus</b>: The HTTP status code that you <b>should</b> read to verify the success of the request</li>
<li><b>Content</b>: This is a String that can contain the data associated with the reply.</li>
</ul>
<p>In addition, you can also add an extra event handler to our subclass: <code>Error</code>. This will be fired when an error is produced while dealing with requests sent from the instance.</p>
<p>With the events and property already set, it is time to add a couple of methods in charge of commanding our URLConnection subclass to launch the requests. For our example, those method names are directly related to the operations we want to do on the web service API created on the first part of this tutorial.</p>
<p>So, with our URLConnection class still selected in the Navigator, add a new method (<code>Insert &gt; Method</code>), using the following data in the associated Inspector. This is the method in charge of requesting our web service for the name of all the available albums. Of course, we expect to receive the reply through the <code>ContentReceived</code> event:</p>
<ul>
<li><b>Method Name</b>: GetRequest</li>
<li><b>Parameters</b>: theList As DesktopListBox, theURL as String</li>
<li><b>Scope</b>: Public</li>
</ul>
<p>As you can see, this method expects to receive the reference to a <b>DesktopoListBox</b> control, and the text to the URL that should be the end point of our web service. Now put the following code in the associated Code Editor for the just added Method:</p>
<pre>List = theList
self.send("GET", theURL)</pre>
<p>Simple, isn&#8217;t? As you can see, we save the reference to the DesktopListBox control in the instance property so we can use it later for updating its contents with the received data. Then we use the <code>Send</code> method from the class with the <code>GET</code> verb and the URL where our web service should be listening for incoming requests. As previously stated, this is an async operation, so we will let our object to react through the <code>ContentReceived</code> or <code>Error</code> events.</p>
<h2>URLConnection: Sending data as part of a request</h2>
<p>Add a new method to the subclass, using the following values in the resulting Inspector. This is the method allowing us to send data to the web service so they can be added to the backend database:</p>
<ul>
<li><b>Method Name</b>: SendItem</li>
<li><b>Parameters</b>: Item As JSONItem, theURL As String</li>
<li><b>Scope</b>: Public</li>
</ul>
<p>This time, the method expects to receive and JSONItem object (pointed via the variable <code>Item)</code> and a String instance that should be the web service endpoint URL. Put the following code in the associated Code Editor for the method:</p>
<pre>Self.SetRequestContent( item.ToString, "application/json" )
self.Send("POST", theURL)</pre>
<p>The URLConnection instances allow us to associate additional information (data) for a request sending, in addition to those added through the HTTP headers (<code>Head</code>), using for that the <code>SetRequestContent</code> method. This method expects two parameters: a String with the real data to attach, and the definition of the type of data we are sending (this is, the <b>MIME</b> Type) as a String instance.</p>
<p>Finally, we launch the request in the second line of code, using for that the URL assigned to the <code>theURL</code> parameter and using the verb <code>POST</code>.</p>
<h2>Designing the User Interface</h2>
<p>We have already finished all the logic behind our example app, via our URLConnection subclass. So now it&#8217;s time to design a minimal user interface so we can verify the correct functionality of our client agains the web service.</p>
<p>Select the <code>Window1</code> object and add the required control so it looks like the one displayed here (from top to bottom): a DesktopListBox, a couple of DesktopTextFields in addition of two DesktopLabels, and two DesktopPushButtons named &#8220;Request&#8221; and &#8220;Send&#8221;.</p>
<p><img loading="lazy" decoding="async" class="size-large wp-image-11611 aligncenter" src="https://blog.xojo.com/wp-content/uploads/2018/11/DesktopWebServiceTest-1024x744.png" alt="" width="1024" height="744" srcset="https://blog.xojo.com/wp-content/uploads/2018/11/DesktopWebServiceTest-1024x744.png 1024w, https://blog.xojo.com/wp-content/uploads/2018/11/DesktopWebServiceTest-300x218.png 300w, https://blog.xojo.com/wp-content/uploads/2018/11/DesktopWebServiceTest-768x558.png 768w, https://blog.xojo.com/wp-content/uploads/2018/11/DesktopWebServiceTest.png 1382w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></p>
<p>Next, add an instance of the created URLConnection subclass. For that, simply drag the created subclass from the Project Browser to the Window Layout Editor and a new instance will be added to the Tray in the lower section of the Editor, as shown in the following picture:</p>
<p><img loading="lazy" decoding="async" class="size-full wp-image-11612 aligncenter" src="https://blog.xojo.com/wp-content/uploads/2018/11/MyConnection.png" alt="" width="596" height="272" srcset="https://blog.xojo.com/wp-content/uploads/2018/11/MyConnection.png 596w, https://blog.xojo.com/wp-content/uploads/2018/11/MyConnection-300x137.png 300w" sizes="auto, (max-width: 596px) 100vw, 596px" /></p>
<p>The only code present in the user interface is the one that we will add to both PushButtons. Double click the one labeled &#8220;Request&#8221;, and add the following line of code to its <code>Pressed</code> Event Handler:</p>
<p><code>MyConnection1.getRequest(AlbumListbox, "http://127.0.0.1:8081/GetAll")</code></p>
<p>It calls the <code>getRequest</code> method on the instance based on our subclass, sending as parameters the control &#8220;ListBox1&#8221; and the text for the (local) URL where the web service should be listening.</p>
<p>Double click the PushButton labeled &#8220;Send&#8221; in order to add the <code>Pressed</code> Event Handler and write the following fragment of code into the associated Code Editor:</p>
<pre>Var d As New Dictionary
d.Value("Title") = TitleField.Text
d.value("ArtistId") = ArtistIDField.Text
Var item As New JSONItem
item.Value("newAlbum") = d

MyConnection1.sendItem(item,"http://127.0.0.1:8081/AddAlbum")</pre>
<p>As you can see, there is nothing magic in it. We simply create a new dictionary using the keys expected from our web server to access the underlaying data for the record. In addition, you can see how easy it is to create a new JSONItem from a Dictionary!</p>
<p>Then, we simply call the <code>sendItem</code> method on our URLConnection subclass instance, passing along the expected parameters: a JSONItem instance and the web service endpoint URL that should include the method we want to call in the remote API.</p>
<h2>Ready to listen for your requests!</h2>
<p>We have finished our client app! Launch the web service created in the first part of the tutorial (make sure it is listening using the port 8081). Then, run the desktop client app and push the buttons for &#8220;sending&#8221; or &#8220;requesting&#8221; the information. You will see how with the request you&#8217;ll receive all the albums available in the example database, while with the &#8220;Send&#8221; button you&#8217;ll be able to add new records to the database with the data provided in both TextFields.</p>
<p><img loading="lazy" decoding="async" class="size-large wp-image-11613 aligncenter" src="https://blog.xojo.com/wp-content/uploads/2018/11/AppRunning-1024x777.png" alt="" width="1024" height="777" srcset="https://blog.xojo.com/wp-content/uploads/2018/11/AppRunning-1024x777.png 1024w, https://blog.xojo.com/wp-content/uploads/2018/11/AppRunning-300x228.png 300w, https://blog.xojo.com/wp-content/uploads/2018/11/AppRunning-768x582.png 768w, https://blog.xojo.com/wp-content/uploads/2018/11/AppRunning.png 1424w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></p>
<p>In conclusion, Xojo allows us to create both the backend and the multiplatform clients in record time and in a really easy way! Obviously, the examples used in these two articles are not, by far, complete solutions you can use &#8220;As Is&#8221;, but they give the basics you can use to construct more robust and complete solutions for your own needs.</p>
<p><em>Javier Rodri­guez has been the Xojo Spanish Evangelist since 2008, he’s also a Developer, Consultant and Trainer who has be using Xojo since 1998. He manages <a href="http://www.aprendexojo.com">AprendeXojo.com</a> and is the developer behind the GuancheMOS plug-in for Xojo Developers, Markdown Parser for Xojo, HTMLColorizer for Xojo and the Snippery app, among others</em></p>
<p>*<a href="https://www.aprendexojo.com/2016/06/crear-servicio-web-con-xojo-parte-ii/">Read this post in Spanish</a></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Web Services: Xojo Web, at your service</title>
		<link>https://blog.xojo.com/2018/09/26/web-services-xojo-web-at-your-service/</link>
		
		<dc:creator><![CDATA[Javier Menendez]]></dc:creator>
		<pubDate>Wed, 26 Sep 2018 10:00:59 +0000</pubDate>
				<category><![CDATA[Learning]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[API]]></category>
		<category><![CDATA[Middleware]]></category>
		<category><![CDATA[OOP]]></category>
		<category><![CDATA[REST]]></category>
		<category><![CDATA[Web Service]]></category>
		<category><![CDATA[webdev]]></category>
		<category><![CDATA[Xojo Programming Language]]></category>
		<guid isPermaLink="false">https://blog.xojo.com/?p=4950</guid>

					<description><![CDATA[In this two part tutorial we will see how easy it is to create a basic web service using Xojo Web. In the second part, we will create a Desktop client to talk with the web service (you may want to add iOS to the list).]]></description>
										<content:encoded><![CDATA[<p>Using Xojo Web to create complete web apps and solutions means not having to learn a bunch of interpreted languages and dozens of ever-changing frameworks. I&#8217;m looking at you: HTML, CSS (is that even a language?), JavaScript, PHP, et al. Of course, <a href="http://xojo.com/products/web.php">Xojo Web</a> not only makes it possible to create your own web apps, but it also acts as the perfect middleware that your desktop and iOS apps can communicate with. Learn about <strong>APIs</strong> and web services with Xojo in the tutorial blog post.<span id="more-4950"></span></p>
<p>In this two part tutorial you will see how easy it is to create a basic web service using Xojo Web. In the second part, we will create a Desktop client to talk with the web service (you may want to add iOS to the list).</p>
<p>Before we start, let me point out that this tutorial leaves out some details related to error checking, validation, data sanitizing and other specifics related to inputs and outputs in order to focus on the central topic. In addition, if you want to follow and reproduce the steps of this tutorial, then you need to download the <a href="https://github.com/lerocha/chinook-database/raw/master/ChinookDatabase/DataSources/Chinook_Sqlite.sqlite">Chinook Database, </a>named &#8220;test.sqlite&#8221; in this tutorial.</p>
<h2>Services in practice</h2>
<p>Let&#8217;s start creating a web service! Open the Xojo IDE, create a new <b>Web project</b>, and name it <code>WebService</code>. The first thing you&#8217;ll notice is that Xojo adds a web page to the project by default &#8211; even when our web service does not display a UI. The good part is that you can mix both worlds, adding the webservice part to your regular Web app!.</p>
<p>In fact this tutorial will put all the logic in the App object. Start by adding a new <b>property</b> in charge of the reference to our <b>SQLite</b> database (of course, it will work also with <b>PostgreSQL</b> or <b>MySQL</b> engines). Select the <code>App</code> object from the <b>Navigator</b> (the left panel in the Xojo IDE), choosing the <code>Insert &gt; Property</code> option from the contextual menu. With the new property selected, go to the <b>Inspector</b> to set the name, type and scope using these values:</p>
<ul>
<li><b>Name: </b>Database</li>
<li><b>Type: </b>SQLiteDatabase</li>
<li><b>Scope: </b>Private</li>
</ul>
<p>Next, we will add the Chinook Database to the Resources folder of our Web App. For that, select the deployment target under Build Settings (it can be macOS, Windows, Linux or Xojo Cloud, for example), and add a Copy Files build step to it. In the resulting Editor, add the Chinook database SQLite file and make sure you select the &#8220;Resources Folder&#8221; entry in the Destination popup menu, and the &#8220;Both&#8221; entry in the Applies To popup menu.</p>
<p>Now is time to create a new SQLiteDatabase instance and assign it to this property, so it will point to the SQLite database file when the app is running. For that, make sure the <code>App</code> object is selected and add the <code>Opening</code> <b>Event Handler</b> to it using the <code>Insert &gt; Event</code> option. Write the following code in the resulting <b>Code Editor</b>:</p>
<pre>#Pragma Unused args

Var f As FolderItem = SpecialFolder.Resource("Chinook_Sqlite.sqlite")

If f.Exists Then
  
  Try
    database = New SQLiteDatabase
    database.DatabaseFile = f
    
    Call database.Connect
  Catch e As DatabaseException
    MessageBox "Error connecting to the database"
  End Try
  
End If</pre>
<p>As you can see, it is pretty much the same code we already use when creating <b>SQLiteDatabase</b> instances in our Desktop apps, <em>linking</em> to our SQLite database file and stablishing the connection so we can operate with the database engine from our app.</p>
<h2>All the Magic of HandleURL</h2>
<p>Xojo Web projects offer a simple way to handle the request received. It is using the <code>HandleURL</code> event. This is the one that fires every time a client app (it may be a Web Browser, desktop or mobile app) connects to the URL associated with the <b>IP address and port combination</b> that is <em>listening</em> for incoming requests.</p>
<p>For example, a valid URL that can be <b>trapped</b> and processed by <code>HandleURL</code> is:</p>
<pre>http://www.nice-web-domain.com/getCustomers</pre>
<p>Where <code>getCustomers</code> is in this case one of our API methods.</p>
<p>So, with the <code>App</code> object selectd, choose <code>Insert &gt; Event</code> in order to add the <code>HandleURL</code> event.</p>
<p>As we will see, once the event has been added to a web app, it will receive the <code>Request</code> parameter (a <code>WebRequest</code> data type), waiting from us to send back a <code>Boolean</code> value as response: <code>True</code> to process the request or <code>False</code> (the default value) to ignore the response.</p>
<h2>Introducing Request, where the information lives!</h2>
<p>In fact, we will find in the <code>Request</code> object everything we need to process and (if it is the case) respond to the request from our Web service. For example, through we can get the interesting component from the <code>Path</code> property. If we consider this URL:</p>
<p><code>http://www.nice-web-domain.com/getCustomers?spain</code></p>
<p>The <code>Request.Path</code> property will return the <code>getCustomers</code> string; so our web service can process it acordingly from this point on.</p>
<h2>Receiving and Sending JSON data</h2>
<p>In order to keep this tutorial brief, our web API only has two methods in it: <code>GetAll</code> and <code>AddAlbum</code>. Using the first one, the client app will get the album name in the database wrapped in JSON format. With the second method, our client app will ask the web service to add a new record (a new album) to the right table on our example database.</p>
<p>How can we process the request associated data inside the <code>HandleURL</code> event? Here is where we will find very useful another of the <code>Request</code> object properties. The <code>Body</code> property includes the sent data as part of the request that are not already present in the headers. Generally speaking, it includes additional data via the <b>PUT</b> and <b>POST</b> verbs.</p>
<p>Now we can put the following code into our <code>HandleURL</code> Event Handler:</p>
<pre>Select Case Request.Path // What is the method received as part of the request? (URL)
Case "GetAll"
  Var output As JSONItem = GetAllAlbums // Assign the processed data to the output variable, if the received method is 'GetAllAlbums'
  
  Response.Header("charset") = "utf-8"
  Response.MIMEType = "application/json"
  Response.Status = 200
  response.write( output.ToString ) // And send it back to the client that made the request, converting the JSON to a String in first place
  
Case "AddAlbum"
  Var data As String = Request.Body.DefineEncoding(encodings.UTF8) // We have to apply the right encoding to the received data
  Var Input As JSONItem = New JSONItem( data ) // Creating a new JSON object from it
  addNewAlbum( Input.Value("newAlbum") ) // In this case, the request is to add a new Album to the database; passing thus the received data as part of the input
End Select

Return True</pre>
<p>The main point here is that we assign the received data to the <code>data</code> variable (if any), and define a known encoding to them so we won&#8217;t get into trouble while processing them afterwards. Of course, our example always expects to receive the additional data in JSON format, so this is why we create a new JSON instance from this data.</p>
<p>We use the <code>Select…Case</code> command to decide what method has to execute the web service, and that is based on the component stored in the <code>Path</code> property as you recall. So, if the request uses the <code>GetAll</code> method in the URL, we will call the real method <code>GetAllAlbums</code> in our Xojo code. After processing the information it will return a new <code>JSONItem</code> as the response we will send to the client.</p>
<p>How can we send the response to the request? Really simple: calling the <code>Write</code> method on the Response object, passing as parameter the text we want to send back. In our example, this is the <code>JSONItem</code> referenced by the <code>Output</code> variable. We also use the Response object to set the character encoding to UTF-8 and the MIME type to &#8220;Application/json&#8221;, in addition of setting the status value to 200 (that is, the request has been successfully handled).</p>
<p>If we receive a request with the <code>AddAlbum</code> method of our API, then we call the real <code>addNewAlbum</code> method in our Xojo code, passing as parameter the <code>JSONItem</code> object in charge of store the received data from the request (this is the one referenced by the <code>input</code> variable). In fact, the record structure is stored inside the <code>newAlbum</code> root node of the JSONItem.</p>
<h2>When it comes to the Database</h2>
<p>While <code>HandleURL</code> is in charge of processing the received request, we will use a couple of methods in our example app that will act as a <em>link</em> between the API and the database in the backend, both for retrieving and storing the requested information. (In a real world app it is very advisable to introduce checks and data sanitization before dealing with the database!)</p>
<p>Choose the <code>App</code> object again and use the <code>Insert &gt; Method</code> option in order to add the <code>GetAllAlbums</code> method, using the following method signature for that:</p>
<ul>
<li style="list-style-type: none;">
<ul>
<li><b>Method Name: </b>getAllAlbums</li>
<li><b>Return Type: </b>JSONItem</li>
<li><b>Scope: </b>Private</li>
</ul>
</li>
</ul>
<p>This is the code in charge of generating the JSONitem that we will <em>write </em>as part of the request response, including the <b>node</b> for every expected database record from the <code>Album</code> table in our example database:</p>
<pre>Var rc As RowSet = database.SelectSQL("Select * from album order by title asc") // Get the Recordset as result of the SQL selection: all the records
Var item As New JSONItem

If rc.RowCount &gt; 0 Then // We have records on the RecordSet
  
  While Not rc.AfterLastRow // so lets iterate them!
    Var d As New Dictionary // creating a new dictionary for each record, and that we will convert in a node
    d.Value("artistid") = rc.Column("artistid").StringValue // assingning the record ID to the name 'ArtistId' of the JSONItem
    d.Value("title") = rc.Column("title").StringValue // and the Title value to the 'Title' field of the JSONItem
    item.Value(rc.Column("albumid").StringValue) = d // You know you can assign a Dictionary as the value for a JSONItem node. Very useful!
    
    rc.MoveToNextRow
  Wend
  
  rc.Close
  
End If

var output As New JSONItem

output.Value("AllAlbums") = item // Then let's hang all these records form a main Node

Return output // And return it to the caller</pre>
<p>Next, create a new method named <code>addNewAlbum</code>. This is the one our web service will use to add a new record to the database, using for that the received data as part of the request. Use the following signature for the method definition:</p>
<ul>
<li style="list-style-type: none;">
<ul>
<li style="list-style-type: none;">
<ul>
<li><b>Method Name: </b>addNewAlbum</li>
<li><b>Paramters: </b>item as JSONItem</li>
<li><b>Scope:</b> Private</li>
</ul>
</li>
</ul>
</li>
</ul>
<p>And put the following code in the associated Code Editor:</p>
<pre>Var title As String = item.Value("Title") // get the data associated to the "Title" field
Var artistid As String = item.Value("ArtistId") // and the 'ArtistID'

database.ExecuteSQL("insert into album(title,artistid) values(?, ?)", title, artistid ) // and insert that data as a new record into the database table
</pre>
<p>As you can see, the code is very simple: it gets the values for the received keys in the JSONitem nodes and uses them as part of the SQL sentence in order to add a new record to the database.</p>
<h1>A Web service… ready to serve!</h1>
<p>As you have seen, the code and app structure are really minimal! Of course, this is just a simple example but it gives you a good idea of the kind of possibilities web services offer and how fast you can put it together using Xojo and <strong>OOP</strong> concepts you already know! Of course, you can run your web app (and services) right from the IDE (just make sure to select 8081 as the Debug Port)… what is probably the recommended way to follow this simple example. For other more complex web apps, remember that you can use the one click solution <a href="https://www.xojo.com/cloud/"><strong>Xojo Cloud</strong></a> and of course any compatible Linux, Windows or Mac server.</p>
<p><em>Javier Rodri­guez has been the Xojo Spanish Evangelist since 2008, he’s also a Developer, Consultant and Trainer who has be using Xojo since 1998. He manages <a href="http://www.aprendexojo.com">AprendeXojo.com</a> and is the developer behind the GuancheMOS plug-in for Xojo Developers, Markdown Parser for Xojo, HTMLColorizer for Xojo and the Snippery app, among others</em></p>
<p>*<a href="https://www.aprendexojo.com/2016/06/crear-servicio-web-con-xojo/">Read this post in Spanish</a></p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
