<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sebastian Krempel on Medium]]></title>
        <description><![CDATA[Stories by Sebastian Krempel on Medium]]></description>
        <link>https://medium.com/@sebastian-krempel?source=rss-15f59cd3d285------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-6_4BDwQCx1cY1Ch9VJHFA.jpeg</url>
            <title>Stories by Sebastian Krempel on Medium</title>
            <link>https://medium.com/@sebastian-krempel?source=rss-15f59cd3d285------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 00:13:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sebastian-krempel/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Efficient bulk data handling in OutSystems]]></title>
            <link>https://itnext.io/efficient-bulk-data-handling-in-outsystems-07f70a6bc410?source=rss-15f59cd3d285------2</link>
            <guid isPermaLink="false">https://medium.com/p/07f70a6bc410</guid>
            <category><![CDATA[advanced-sql]]></category>
            <category><![CDATA[bulk-data]]></category>
            <category><![CDATA[outsystems]]></category>
            <category><![CDATA[low-code]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[Sebastian Krempel]]></dc:creator>
            <pubDate>Fri, 23 May 2025 12:39:05 GMT</pubDate>
            <atom:updated>2025-10-18T11:55:49.278Z</atom:updated>
            <content:encoded><![CDATA[<h4>Reducing database roundtrips for bulk actions using JSON</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y-I5GzwFGTCaQeDcS3wZyw.png" /></figure><p>For health and other reasons, unfortunately it’s been a while since I published my last article. In the meantime, starting my blog at <a href="https://lowcoding.eu/">lowcoding.eu</a>, a job change, several OutSystems certifications and preparing a speech for the ONE Conference 2025 in Lisbon have dominated my agenda. Although my presentation wasn’t selected for the ONE Conference 2025, I’m excited to share the content with you earlier than planned, right here on my blog.</p><h3>What is it about?</h3><p>In OutSystems, the challenge often arises of having to process multiple data records at once. In my previous articles you can find some examples of how to efficiently load lists from the database and display them on the screen (i.e. filtering, pagination, nested data structures). But what if you need to manipulate multiple data records?</p><p>If you have a look at the OutSystems documentation, you can find a very important recommendation regarding performance:</p><blockquote>Avoid database operations within loops.</blockquote><p>Obviously, every time an action flow in Outsystems accesses the database, a connection must be established via the network and the system has to wait for the response, a so-called database round trip. This takes time, and when repeated in a loop, the delays accumulate significantly.</p><h3>The Simple but Limited Solution</h3><p>As a solution, the OutSystems documentation recommends using an <em>Advanced SQL</em> with a bulk script. Examples mentioned there are:</p><h4>Bulk Delete</h4><p>If you want to delete all data records or only those to which a specific condition applies, you don’t have to be a great SQL expert to find the solution. For example, you can use the following statement to completely empty an entity:</p><pre>DELETE FROM {Entity}</pre><p>Or use the following to delete all data records that were created before the specific date @DeleteDate:</p><pre>DELETE FROM {Entity} WHERE {Entity}.[CreatedOn] &lt; @DeleteDate</pre><p>The task becomes more complex if you want to delete a list of data records based on their Ids. The first approach that comes to mind, which also can be found in some exercises, creates a round trip for each entry to be deleted and should therefore not be used:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*qqF1ODB2j7wXeM4AcVHSyw.png" /></figure><p>More elegant is to use the following <em>Advanced SQL</em> with an IN clause based on the parameter @IdLiterals with <em>Expand Inline</em> set to <em>Yes</em>:</p><pre>DELETE FROM {Entity} WHERE {Entity}.[Id] IN (@IdLiterals)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gz53C67_4h3nYLIE4yhqeQ.png" /></figure><p>However, there is a restriction to consider that you may only come across during later tests or, even worse, during productive operation. The underlying DBMS has a specific limit for the IN clause (e.g. 1000 items in Oracle) or max. statement length, which can become a problem depending on the number or format of the Ids.</p><p>Of course you could still process the bulk deletion in batches to reduce the number of roundtrips, but what if your statement is to delete all records except the specified list (NOT IN(@IdLiterals))?</p><h4>Bulk Update</h4><p>Another example for a bulk action is updating records. The following statement, for instance, sets the IsArchive flag for all entries that were last changed before the specific date @ArchiveDate:</p><pre>UPDATE {Entity} SET {Entity}.[IsArchive] = 1<br>WHERE {Entity}.[UpdatedOn] &lt; @ArchiveDate</pre><p>You could also set values dynamically based on a calculation or sub query, but what if you need to pass over individual values from your server action?</p><h3>A Smarter Approach with JSON</h3><p>To overcome the hurdles we’ve discovered so far, there is a very handy feature on the database side, which can be combined nicely with an integrated function in OutSystems. The magic word is JSON.</p><p>Both MS SQL and Oracle (used by O11) as well as Aurora PostgreSQL (used by ODC) support JSON functions. This allows us to serialize the list of Ids on the OutSystems application server into JSON and safely pass it over to the database as SQL parameter of type <em>Text</em>.</p><h4>Bulk Delete</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*Cj-gcDxGm6XssIS5zecgBg.png" /></figure><p>The SQL parameter @JSON contains a valid JSON string generated by the OutSystems platform, <em>Expand Inline</em> is not necessary so we do not need to sanitize with BuildSafe_InClause….</p><pre>[1,2,3]</pre><p>Unfortunately, all three DBMS use different syntax to parse the JSON, so we need to implement depending on the environment. We also should strongly type the parsed JSON values, which especially is important for SQL Server that has a known limitation to bind the dynamic rowset metadata properly at execution time. Please find the corresponding <a href="https://success.outsystems.com/documentation/11/reference/outsystems_language/data/database_reference/database_data_types">Database Data Types</a> in the OutSystems documentation.</p><pre>-- O11 with SQL Server<br>DELETE FROM {Entity} WHERE {Entity}.[Id] IN (<br>    SELECT CAST([value] AS BIGINT)<br>    FROM OPENJSON(@JSON)<br>)<br><br>-- O11 with Oracle<br>DELETE FROM {Entity} WHERE {Entity}.[Id] IN (<br>    SELECT value<br>    FROM JSON_TABLE(@JSON, &#39;$[*]&#39; COLUMNS(value NUMBER(20) PATH &#39;$&#39;))<br>)<br><br>-- ODC with PostgreSQL<br>DELETE FROM {Entity} WHERE {Entity}.[Id] IN (<br>    SELECT CAST(value AS BIGINT)<br>    FROM jsonb_array_elements_text(@JSON::jsonb) AS t(value)<br>)</pre><h4>Bulk Insert/Update</h4><p>You probably already guessed it, these JSON functions are not limited to parsing a flat array of Ids, but can also parse structured data objects with multiple attributes, even nested objects. This allows us to transfer several data records in a single database roundtrip and use them for a bulk insert or update.</p><p>First, we create a structure in OutSystems that defines the format of the data to be transferred. Even if it is possible to only refer certain attributes or sub-objects in SQL, for performance reasons it is advisable to optimize the structure to a minimal number of attributes. In this way, not only the network traffic to the database can be reduced, but also the size of the database transaction log. As these identifiers must be hard-coded in the SQL statement, I also recommend explicitly setting the “Name in JSON” property to avoid errors when structure attributes are renamed at a later date.</p><pre>[<br>  { &quot;id&quot;: 1, &quot;name&quot;: &quot;A&quot; },<br>  { &quot;id&quot;: 2, &quot;name&quot;: &quot;B&quot; },<br>  { &quot;id&quot;: 3, &quot;name&quot;: &quot;C&quot; }<br>]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MqMbT1J5gq3c61i2u2lCuw.png" /></figure><pre>-- O11 with SQL Server<br>INSERT INTO {Entity} (Id, Name)<br>SELECT * FROM OPENJSON(@JSON) WITH (<br>    Id   BIGINT       &#39;$.id&#39;,<br>    Name NVARCHAR(50) &#39;$.name&#39;<br>)<br><br>-- O11 with Oracle<br>INSERT INTO {Entity} (Id, Name)<br>SELECT * FROM JSON_TABLE(@JSON, &#39;$[*]&#39; COLUMNS (<br>    Id   NUMBER(20)   PATH &#39;$.id&#39;,<br>    Name VARCHAR2(50) PATH &#39;$.name&#39;<br>))<br><br>-- ODC with PostgreSQL<br>INSERT INTO {Entity} (Id, Name)<br>SELECT <br>    CAST(elem-&gt;&gt;&#39;id&#39; AS BIGINT),<br>    elem-&gt;&gt;&#39;name&#39;<br>FROM jsonb_array_elements(@JSON::jsonb) AS elem</pre><p>And of course, bulk updates can be implemented in the similar way:</p><pre>-- O11 with SQL Server<br>UPDATE {Entity} SET<br>    {Entity}.[Name] = J.Name<br>FROM {Entity} JOIN OPENJSON(@JSON) WITH (<br>    Id   BIGINT       &#39;$.id&#39;,<br>    Name NVARCHAR(50) &#39;$.name&#39;<br>) AS J ON {Entity}.[Id] = J.Id<br><br>-- ODC with PostgreSQL<br>UPDATE {Entity} E SET<br>    Name = J.Name<br>FROM (<br>    SELECT <br>        CAST(elem-&gt;&gt;&#39;id&#39; AS BIGINT) AS Id,<br>        elem-&gt;&gt;&#39;name&#39; AS Name<br>    FROM jsonb_array_elements(@JSON::jsonb) AS elem<br>) AS J WHERE E.Id = J.Id</pre><p>Oracle does not support UPDATE … FROM … statements. Here you need to implement sub queries per attribute you want to set. As this quickly becomes a little cluttered, especially if there are several attributes to be set, I do not want to give an example here. In such cases, I recommend using the solution described in the following.</p><h3>The Ultimate Bulk Handling Strategy</h3><p>Everything described so far sounds nice, but what do you need it for in real life? Bulk deletes are suitable for data purging, bulk inserts can be used for classic data imports, bulk updates might be helpful when updating master-detail data (e.g. items of an order or invoice). But for me, the method shown above will really pay off when synchronizing data. An example of this scenario is integration services that cache data from external sources in an own entity. Wouldn’t it be nice if we could even let the database decide whether a record is to be added or updated?</p><h4>Merge</h4><p>Let me introduce the SQL MERGE statement, which allows to compare two tables based on a match condition and execute different data manipulations based on whether there is a match or a record is only found on one side of the comparison.</p><pre>MERGE [Target] USING [Source] ON [MatchCondition]<br>WHEN MATCHED THEN ...<br>WHEN NOT MATCHED BY Target THEN ...<br>WHEN NOT MATCHED BY Source THEN ...;</pre><p>Please notice the semicolon at the end, which is mandatory to close the MERGE statement. If necessary, you can include additional execution conditions: WHEN MATCHED AND … THEN. However, these should not be confused with the match condition:</p><ul><li>The match condition defines how records are to be considered a match in the comparison.</li><li>The execution conditions define whether the corresponding data manipulation should actually be executed in the event of a (non-)match.</li></ul><p>So how to adopt this to our small sample? Here we go:</p><pre>-- O11 with SQL Server<br>MERGE {Entity} AS Target USING (<br>    SELECT * FROM OPENJSON(@JSON) WITH (<br>        Id   INT          &#39;$.id&#39;,<br>        Name NVARCHAR(50) &#39;$.name&#39;<br>    )<br>) AS Source ON Source.Id = Target.Id<br>WHEN MATCHED THEN<br>    UPDATE SET Target.Name = Source.Name<br>WHEN NOT MATCHED BY Target THEN<br>    INSERT (Id, Name) VALUES (Source.Id, Source.Name)<br>WHEN NOT MATCHED BY Source THEN<br>    DELETE;</pre><p>Looks cool, doesn’t it? But what’s about O11 with Oracle and ODC with PostgreSQL? Oracle cannot distinguish whether it’s NOT MATCHED BY target or by source in the MERGE statement. So it can only handle inserts and updates:</p><pre>-- O11 with Oracle<br>MERGE INTO {Entity} Target<br>USING (<br>    SELECT * FROM JSON_TABLE(@JSON, &#39;$[*]&#39; COLUMNS (<br>        Id   NUMBER(20)   PATH &#39;$.id&#39;,<br>        Name VARCHAR2(50) PATH &#39;$.name&#39;<br>    ))<br>) Source ON (Target.Id = Source.Id)<br>WHEN MATCHED THEN<br>    UPDATE SET Target.Name = Source.Name<br>WHEN NOT MATCHED THEN<br>    INSERT (Id, Name) VALUES (Source.Id, Source.Name)</pre><p>Please notice, that there is no tailing semicolon, as this is handled by OutSystems automatically for Oracle. For the deletes we need to implement a second statement. Unfortunately, the Advanced SQL node for Oracle does not allow separating several statements by a semicolon. Thus we are forced to do the deletion in a separate SQL node and end up with two database roundtrips:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4btqlf6Dai1XpKoiSQTcDw.png" /></figure><pre>DELETE FROM {Entity} WHERE {Entity}.[Id] NOT IN (<br>    SELECT Id<br>    FROM JSON_TABLE(@JSON, &#39;$[*]&#39; COLUMNS (Id NUMBER(20) PATH &#39;$.id&#39;))<br>)</pre><p>PostgreSQL only supports the MERGE statement starting with version 15, but ODC uses an earlier version. The workaround at hand is using a combined INSERT/UPDATE with a DELETE following in the same Advanced SQL - so it is still just one roundtrip:</p><pre>-- ODC with PostgreSQL<br>INSERT INTO {Entity} (id, name)<br>SELECT <br>    CAST(elem-&gt;&gt;&#39;id&#39; AS BIGINT),<br>    elem-&gt;&gt;&#39;name&#39;<br>FROM jsonb_array_elements(@JSON::jsonb) AS elem<br>ON CONFLICT (id) DO UPDATE<br>SET name = EXCLUDED.name;<br><br>DELETE FROM {Entity}<br>WHERE id NOT IN (<br>    SELECT CAST(elem-&gt;&gt;&#39;id&#39; AS BIGINT)<br>    FROM jsonb_array_elements(@JSON::jsonb) AS elem<br>);</pre><blockquote>By leveraging JSON and MERGE statements in Advanced SQL, you can reduce database roundtrips to a single call, significantly boosting performance and scalability for bulk data operations in OutSystems.</blockquote><p>I hope this article was to your liking and will be of practical help for your future OutSystems projects. I would be pleased if you follow me on <a href="https://www.linkedin.com/in/sebastian-krempel/">LinkedIn</a> and leave some claps on medium. In case you have any questions left open or have tips for me to improve, please contact me via LinkedIn, medium or my <a href="https://www.outsystems.com/profile/enrntqhemy/">OutSystems profile</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=07f70a6bc410" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/efficient-bulk-data-handling-in-outsystems-07f70a6bc410">Efficient bulk data handling in OutSystems</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Communicate real-time in OutSystems]]></title>
            <link>https://itnext.io/communicate-real-time-in-outsystems-5ff9f279d70c?source=rss-15f59cd3d285------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ff9f279d70c</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[realtime]]></category>
            <category><![CDATA[appsync]]></category>
            <category><![CDATA[outsystems]]></category>
            <category><![CDATA[websocket]]></category>
            <dc:creator><![CDATA[Sebastian Krempel]]></dc:creator>
            <pubDate>Fri, 26 Jul 2024 07:37:47 GMT</pubDate>
            <atom:updated>2024-07-26T08:14:00.508Z</atom:updated>
            <content:encoded><![CDATA[<h4>Leveraging AWS AppSync and websocket connections</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X_LIz2ak2Eo8ZOjHQLwOGQ.png" /></figure><p>It’s been a little while since I published my last article. I moved to a new home with my family and also had priorities in customer projects that were more time-critical. Time-critical communication is precisely what this article is about: Communication from client to server is no challenge using simple HTTP requests. However, it is a different story in the opposite direction.</p><h3>What you need</h3><p>If you want to follow up the content of this article on your own, you need:</p><ul><li>An Amazon Web Services account (<a href="https://aws.amazon.com/free/">free tier</a> is sufficient for first year)</li><li>An OutSystems 11 account (a <a href="https://www.outsystems.com/free-edition/">free personal environment</a> is sufficient) or access to an <a href="https://www.outsystems.com/low-code-platform/developer-cloud/">OutSystems Developer Cloud</a> tenant</li><li>OutSystems Service Studio or ODC Studio</li><li>AWS AppSync Connector (available for free from the O11 or ODC Forge)</li></ul><h3>The challenge</h3><p>In web applications, communication between client and server usually takes place via webservices (REST or SOAP). OutSystems uses so-called screen aggregates or data fetch actions to update information in the UI. In the background, these are simply REST webservices based on the HTTP protocol as well. HTTP is short for Hyper Text Transfer Protocol and, as its name indicates, was developed at the beginning of the web to allow HTML documents (Hyper Text Markup Language) and related resources like images to be transferred from the web server to the client. Therefore, it is designed as stateless, unidirectional communication:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*pR5UNDH7mX6y0Ld_tdrILg.png" /></figure><p>As shown in the diagram above, communication always starts with a request from the client and is then concluded with a response from the server. This fits in very well with the design of the web, in which servers offer their information and services at a publicly known address. Clients, on the other hand, are typically located behind a firewall and precisely should not be called from an outside party.</p><p>As long as the triggering event for an update always occurs on the client side, e.g. by clicking a button, this is sufficient. However, if the triggering event takes place on the server side, e.g. because a new message is to be delivered in a messaging system, the request would have to be made from the server to the client, which is not intended and supported.</p><h3>Three approaches</h3><blockquote>There are reverse web communications on the internet, so how is it done?</blockquote><h4>Polling</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*X7aNf-9w_nvttELV8rSxvw.png" /></figure><p>The simplest and probably most obvious solution is for the client to regularly check with the server whether new data is available. This process is called polling and can be implemented with a small JavaScript which calls the data fetch action periodically. The disadvantage of this approach is that the client requests data even when there is no new data available. This leads to an unnecessarily high load on the server and can only be counteracted by a longer polling interval. But this also means the time between availability of a data update and its arrival at the client lasts longer. Therefore, this solution is not suitable for scenarios that require real-time communication.</p><h4>Long-lasting request / streaming</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*8xFnrpE8wVsKj7ZaFk1mGA.png" /></figure><p>The issue with polling is that the connection between client and server is closed after each response. Wouldn’t it make sense if the connection could remain open to allow the server to send a response whenever new data is available? This method is known as long-lasting requests. Although there are timeouts for the HTTP connection within which the request must be completed, the transmission of a response with large amounts of data can certainly take longer. In addition, there is a wait status defined in the protocol, which the server can use to inform the client to wait a little longer for the result. So the client could make such a long-running request and the server needs to keep the connection open and periodically either send a wait status or “stream” the next data update. If the connection is interrupted, the client can simply initiate the next request. The disadvantage of this approach is that, by default, each browser can only send a limited number of simultaneous requests to the same server and a web server can only process a limited number of requests at a time. In order to not negatively affect the performance for other requests, separate web servers must be provided for such a solution. In addition, bidirectional communication is not possible within an open connection.</p><h4>Websocket</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*JRu3LgSEwWPlRqml7yF9WA.png" /></figure><p>In scenarios where bidirectional real-time communication is essential, websocket connections are ideal. They are not based on the simple request/response principle described above, but work in a similar way to a telephone call: Although the client still establishes the connection to the server, it remains open until one of the two parties disconnects. During an open connection, both sides can send messages to the opposite partner. Despite transmission latency, this enables real-time communication. While there is definitely a need for one or more separate websocket servers in addition to the web server delivering the website, these servers can exclusively take care of maintaining the real-time connections without affecting the webserver(s).</p><h3>The solution</h3><blockquote>Looks like websocket is the way to go, right?</blockquote><p>If you ask me, all three approaches mentioned have their raison d’être:</p><ul><li>As polling is very easy to implement, it can be a cost-effective solution for a long polling interval or for short-term use with only a few simultaneous clients.</li><li>Long-lasting requests are also suitable for a smaller number of simultaneous connections and, in contrast to websockets, work with normal HTTP webservers. Similar to polling, this solution can be realized with OutSystems, although holding the very long requests can be a bit tricky and the use of a custom code extension is advisable.</li><li>Websockets overcome the disadvantages of the first two approaches and enable free bidirectional message exchange.</li></ul><p>Unfortunately, you cannot implement a websocket server natively with OutSystems, so we need a little external help. But where do you get it from if we don’t have such a server?</p><p>In the cloud, of course! In one of my recent projects, I stumbled across API Gateway in the Amazon Web Services and noticed that it also supports websocket connections. Implementing a simple messaging system with corresponding logic in AWS Lambda shouldn’t be too difficult. For a classic Pub/Sub pattern, we would need the ability to receive and distribute messages. Obviously, this also includes managing subscribers. And maybe we should also allow subscribers to subscribe only to certain events.</p><blockquote>This sounds like quite a lot of implementation work and not at all quick and easy with LowCode!</blockquote><p>That’s right, we’re doing low-code and want to configure functionality where possible rather than writing a lot of textual code. This is where AWS AppSync steps on the scene. It is a managed service that allows developers to create GraphQL and Pub/Sub APIs to connect applications to multiple data sources and real-time events.</p><p>The heart of AppSync’s working principle is GraphQL. Unlike traditional REST APIs where the server defines the response structure, the Graph Query Language allows clients to specify exactly what data they need. This reduces over- and under-fetching of data. It uses a strong type system to define the capabilities of the API including types and structures of data that can be queried. Furthermore, GraphQL allows fetching multiple resources in a single request, which also minimizes the number of network requests necessary.</p><h3>AWS AppSync</h3><p>Let’s start configuring the websocket server in AWS AppSync:</p><ul><li>Log into your <a href="https://aws.amazon.com/console/">AWS console</a> and navigate to the AppSync console. You can find this in the <em>Services</em> menu in category <em>Front-end Web &amp; Mobile</em> or by typing AppSync in the search box.</li><li>Please make sure you have selected the correct region in the top bar where you want to deploy the service before clicking on <em>Create API</em>.</li><li>For our use case, select API type <em>GraphQL API</em> and in section GraphQL API Data Source choose <em>Create a real-time API</em>. Click <em>Next</em>.</li><li>Enter a name for for your API that makes sense to you (e.g. OS-AWS-AppSync-Connector-Demo-API). Leave the checkbox <em>Use private API features</em> unchecked and click <em>Next</em>.</li><li>AWS AppSync provides a simple Pub/Sub configuration that allows clients to subscribe to channels. As we want to configure a GraphQL API from scratch, please uncheck the checkbox and click <em>Next</em>.</li><li>On the last page of the creation wizard you can review all settings and click <em>Create API</em> to finish the process.</li></ul><h4>Schema</h4><p>For an AppSync API we need to define the schema in GraphQL. Beside the object types that define the structure of information to be processed, there are three special types to be included into the schema:</p><ul><li><strong>Query</strong> to define how information can be queried by clients,</li><li><strong>Mutation</strong> to specify how information can be changed, and</li><li><strong>Subscription</strong> to describe the events a subscriber can hook on.</li></ul><p>For our sample we will go with the following, very basic schema:</p><pre>type Message {<br>  message: String<br>}<br><br>type Mutation {<br>  sendMessage(msg: String): Message!<br>}<br><br>type Query {<br>  dummy(param: String): String<br>}<br><br>type Subscription {<br>  subscribeToMessages: Message<br>    @aws_subscribe(mutations: [&quot;sendMessage&quot;])<br>}<br><br>schema {<br>  query: Query<br>  mutation: Mutation<br>  subscription: Subscription<br>}</pre><ul><li>First, we define the object type Message that will represent a basic message for the real-time communication. It only has one field of type String to hold the message text.</li><li>Next is the special type Mutation that will allow clients of the API to sendMessage by passing a String as parameter msg. The API will then return with the modified Message.</li><li>The special type Query is mandatory in AppSync. As we only want to send a message and having this mutation reflected as a subscription, we just define a dummy here.</li><li>The interesting part of the schema is the special type Subscription because this will allow our clients to subscribeToMessages sent with the mutation sendMessage and being actively notified with the Message object transferred via the websocket connection.</li><li>At the end we tell AppSync which types to use as the query, mutation, and subscription.</li></ul><p>Don’t forget to click <em>Save Schema</em> before you proceed.</p><h4>Data sources</h4><p>One advantage of GraphQL is that information can be obtained from multiple sources. The next step is to make these sources known to AppSync. In our case, we only have messages which we don’t want to query or store in a database, but only distribute via the subscription. So we don’t actually need a real data source in the background. For this purpose, there is the data source type NONE in AppSync. Let’s now create such a data source:</p><ul><li>Switch to <em>Data sources</em> in the navigation and click <em>Create data source</em>.</li><li>Type in a name for the data source (e.g. NoneDataSource), select Data source type <em>NONE</em> and click <em>Create</em>.</li></ul><h4>Resolvers</h4><p>The connection between data fields within the schema and data sources is made via resolvers in AppSync. To add functionality to our sendMessage mutation, we need to attach a resolver to it:</p><ul><li>Navigate back to the <em>Schema</em>.</li><li>Find the field sendMessage in type Mutation and click on the <em>Attach</em> button in the <em>Resolver</em> column.</li><li>Select resolver type <em>Unit resolver</em> and under <em>Additional setting</em> select <em>Velocity Template Language (VLT)</em>.</li><li>As data source select the data source we created before (e.g. NoneDataSource) and click <em>Create</em>.</li><li><em>Configure the request mapping template</em> by copying the following snippet:</li></ul><pre>{<br>  &quot;version&quot;: &quot;2017-02-28&quot;,<br>  &quot;payload&quot;: {<br>    &quot;message&quot;: $util.toJson($context.arguments.msg)<br>  }<br>}</pre><ul><li>For the response mapping template use:</li></ul><pre>$util.toJson($context.result)</pre><ul><li>Click on <em>Save</em>.</li></ul><h4>Test AppSync API</h4><p>🎉 Congratulations, we have now successfully configured our websocket server. To test this, we navigate to <em>Queries </em>in the menu and run the following query:</p><pre>subscription MySubscription {<br>  subscribeToMessages {<br>    message<br>  }<br>}</pre><p>In a second browser window, we now also open the <em>Queries</em> page of our AppSync API and run the following query:</p><pre>mutation MyMutation {<br>  sendMessage(msg: &quot;Hello World!&quot;) {<br>    message<br>  }<br>}</pre><p>As a result, we see the message object returned by sendMessage:</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;sendMessage&quot;: {<br>      &quot;message&quot;: &quot;Hello World!&quot;<br>    }<br>  }<br>}</pre><p>As well as the message received in the first window with the started subscription:</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;subscribeToMessages&quot;: {<br>      &quot;message&quot;: &quot;Hello World!&quot;<br>    }<br>  }<br>}</pre><h4>Connection parameters</h4><p>For consuming the AppSync API we just created, we need some connection parameters which can be found on the <em>Settings </em>page in the menu. So please copy and save the following information for later:</p><ul><li><strong>GraphQL endpoint</strong> is the URL of the REST endpoint to send GraphQL query and mutation requests.</li><li><strong>Real-time endpoint</strong> is the URL for the websocket connection to send subscription requests and receive subscription messages.</li><li><strong>API key</strong> is required for authentication against both endpoints.</li></ul><h3>OutSystems App</h3><p>Now that we have the websocket server up and running, we want to consume it in an OutSystems application. As I wrote above, OutSystems is not supporting websocket natively. But one of the advantages I really like a lot about OutSystems is that you can extend the framework with custom code. Here we need some functionality for the client-side, so the language to go is JavaScript. If you read through the <a href="https://docs.aws.amazon.com/appsync/latest/devguide">AppSync documentation</a>, you find everything that needs to be implemented for doing real-time communication via websocket connection. This includes a handshake to initialize the connection, how to start and stop subscriptions and how to send and receive messages. The following diagram shows the whole communication process:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*rZkzzQkZcK26R5zE0og8RQ.png" /></figure><p>Luckily, you don’t have to implement the websocket consumer on your own and can just install my AWS AppSync Connector component from the forge for free:</p><p><a href="https://www.outsystems.com/forge/component-overview/19309/aws-appsync-connector-o11">AWS AppSync Connector</a></p><p>The connector is also available for OutSystems Developer Cloud (ODC). Just search for AWS AppSync Connector by Telelink Business Services EAD and install it to your tenant.</p><h4>Client implementation</h4><p>Can you remember the initial challenge? We want a message from the server to trigger some processing at the client side. This means we need event-driven programming for the client. In OutSystems, this can be achieved using events of web blocks. The connector contains a widget called <em>AWSAppSyncClient</em> that encapsulates the websocket connection and manages all active subscriptions for us. The widget is accompanied by client actions in order to invoke commands to the contained client implementation.</p><p>Of course, we need to tell the widget the connection parameters to the AppSync API. For this, there are the following input parameters:</p><ul><li><strong>SubscriberId</strong> is mandatory to identify the instance (called the subscriber). This later needs to be passed to the client actions. You can use any text you wish as long as it’s unique. I recommend naming the widget and using the widgets id as <em>SubscriberId</em>.</li><li><strong>RealtimeHost</strong> must be set to the host name of the AWS RealTime endpoint without protocol ( wss://) and path (/graphql).<br>Format: [api-host].appsync-realtime-api.[region].amazonaws.com</li><li><strong>GraphQLHost</strong> must be set to the host name of the AWS GraphQL endpoint without protocol ( https://) and path (/graphql).<br>Format: [api-host].appsync-api.[region].amazonaws.com</li><li><strong>ApiKey</strong> is the AWS AppSync API key for authentication.</li></ul><p>Additionally there is the optional input parameter</p><ul><li><strong>IsAutoReconnect</strong> to enable automatic reconnect (True by default). When this feature is enabled, the component is automatically reconnecting to the websocket when the connection is lost and also resubscribing to all subscriptions that were active.</li></ul><p>If the browser is not supporting websocket, during its initialization the widget triggers the event</p><ul><li><strong>OnWebSocketUnsupported</strong> which should be handled if real-time communication is to be used. Otherwise, the event can be ignored.</li></ul><p>After the widgets initialization you can already send GraphQL requests to query or mutate data by using the client action</p><ul><li><strong>AWSAppSyncClient_SendGraphQLRequest</strong> as it is using the GraphQL endpoint via HTTPS.</li></ul><p>Hence the websocket connection is only required for subscriptions and receiving real-time messages, it is not established automatically. You can do so by using the client action</p><ul><li><strong>AWSAppSyncClient_Connect</strong> to open the connection and initialize the handshake.</li></ul><p>Whenever the connection state changes, the widget will trigger the event</p><ul><li><strong>OnConnection</strong> with the new state being passed as text parameter:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/1*j7GKhVcGx2GPyIaHg3jf5w.png" /></figure><p>After the connection is successfully established, you can subscribe und unsubscribe to the Subscriptions you defined in the AppSync API schema by using the following client actions:</p><ul><li><strong>AWSAppSyncClient_StartSubscription</strong> starts new subscription based on the GraphQL query and variables you provide as input parameters.</li><li><strong>AWSAppSyncClient_StopSubscription</strong> stops the subscription identified by the <em>SubscriptionId</em> you provide as input parameters.</li></ul><p>Whenever the state of a subscription changes, the widget triggers</p><ul><li><strong>OnSubscription</strong> with the <em>SubscriptionId</em> and the new state being passed as text parameters:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*l0OQoHhFY8pDQfp8FlBYRA.png" /></figure><p>During one or multiple active subscription(s) the widget triggers the event</p><ul><li><strong>OnMessage</strong> with the <em>SubscriptionId</em> and the received data as JSON text whenever a new message is received.</li></ul><p>The last event that can be triggered by the widget is</p><ul><li><strong>OnError</strong> which is passing over the source of the error (appsync or websocket) and additional details as JSON text.</li></ul><p>As you may have noticed in the introduction to this article, currently AWS AppSync is only free of charge within the free tier for the first twelve months and only to a limited extent. Amazon charges based on the number of query and mutation requests, the number of real-time messages delivered and the connection time. Thus, for most people, it should be in their economic interest to terminate connections that are no longer required. The client action</p><ul><li><strong>AWSAppSyncClient_Disconnect</strong> stops all active subscriptions and then closes the websocket connection.</li></ul><p>At any given time, you can call the client action</p><ul><li><strong>AWSAppSyncClient_GetDetail</strong> to check the current connection state, auto-reconnect setting and list of subscriptions.</li></ul><p>The remaining client action</p><ul><li><strong>AWSAppSyncClient_SendRealtimeMessage</strong> allows to send a custom message to the real-time endpoint via the websocket connection.</li></ul><h4>Server implementation</h4><p>The still missing piece of the puzzle is the server side. After all, we want to actively send a message from the server to the client. As you have already experienced in section “Test AppSync API” of this article, we can push a message to subscribed clients by running a GraphQL mutation. For this purpose, the connector contains the server action</p><ul><li><strong>AWSAppSync_SendGraphQLRequest</strong> which sends a request to the AWS AppSync GraphQL endpoint via HTTPS.</li></ul><h4>See everything in action</h4><p>You have just learned everything you need to know to implement real-time communication with AWS AppSync in OutSystems. Maybe you’ve already built your first app while reading this? If not, you can download my demo app from the OutSystems forge and try it out with the AppSync API you set up above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qyG9_SQWuzzG4-01sr-I4Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ny9eYGK-hN8bDobCjiS58g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bd_JWR3naWstGYxkJgg9ZQ.png" /></figure><p>For O11 you can find the demo here:</p><p><a href="https://www.outsystems.com/forge/component-overview/19309/aws-appsync-connector-o11">AWS AppSync Connector</a></p><p>You can find the ODC variant in your ODC portal by searching for “AWS AppSync Connector Demo” from Telelink Business Services EAD in the forge.</p><p>For this article I decided not to write a step-by-step guide on how to implement in OutSystems, but rather to describe the background for choosing the technology and an overview of how to use the AWS AppSync Connector. I hope this format is to your liking. I would love to hear your feedback and am curious whether and how you use the component in your projects.</p><p>If you liked the article, feel free to follow me on <a href="https://www.linkedin.com/in/sebastian-krempel/">LinkedIn</a> and Medium or leave a few claps and/or a coffee 😉. In case you have any questions left open or have tips for me to improve, please contact me via Medium, LinkedIn or my <a href="https://www.outsystems.com/profile/enrntqhemy/">OutSystems profile</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ff9f279d70c" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/communicate-real-time-in-outsystems-5ff9f279d70c">Communicate real-time in OutSystems</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hierarchical data in OutSystems]]></title>
            <link>https://itnext.io/hierarchical-data-in-outsystems-8ee689e09cbf?source=rss-15f59cd3d285------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ee689e09cbf</guid>
            <category><![CDATA[tree-view]]></category>
            <category><![CDATA[outsystems]]></category>
            <category><![CDATA[hierarchical-data]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[recursion]]></category>
            <dc:creator><![CDATA[Sebastian Krempel]]></dc:creator>
            <pubDate>Tue, 23 Jan 2024 11:13:18 GMT</pubDate>
            <atom:updated>2024-01-24T15:04:41.455Z</atom:updated>
            <content:encoded><![CDATA[<h4>A self-referencing entity, recursive SQL statement and a tweaked tree view</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-uaBSIoZXwzuUQwYHVa5TA.png" /></figure><p>Hierarchical data is a structure of data that references itself to represent a tree. You can think of its individual elements as parents and children. A single element can have several children and itself can be the child of exactly one other element. In practice, you often find such structures for mapping organizational hierarchies, folders or taxonomies. Although OutSystems knows the language construct of structures, these can only have attributes of a primitive data type or a different structure, but not themselves. This means that hierarchical data cannot be mapped one-to-one. In this article, I describe how you can nevertheless work with hierarchical data in OutSystems, from persistence in the database to processing it in the core service and displaying it in the UI.</p><h3>What you need</h3><p>If you want to follow up the implementation on your own, you need:</p><ul><li>An OutSystems account (a <a href="https://www.outsystems.com/free-edition/">free personal environment</a> is sufficient)</li><li>OutSystems Service Studio</li></ul><p>I would like to illustrate the topic using a simple sample application for storing organizational units.</p><h3>Core Service: Where to store hierarchical data</h3><p>The easiest way to store data in OutSystems is within the database, i.e. the entities. From an architectural point of view, we therefore start again with a core service called <em>OrgUnit_CS</em>. For the sake of simplicity of our sample application, this encapsulates the persistence layer and the business logic layer. So we can omit a separate BL module. This also allows to keep the entities private so we can control any access to the data inside the core service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/190/1*ha_vIJ_fylZ5pkoStkNyug.png" /><figcaption>Entity Relationship Model</figcaption></figure><p>The minimal data model shown here only consists of a single entity for the organizational unit. In addition to the primary key <em>OrgUnitId</em>, we also provide a <em>Name </em>attribute of type <em>Text</em>, in which we can store a user-friendly display name. The hierarchy is created by the foreign key <em>ParentOrgUnitId</em>, which points to the entity itself and can hold the reference to the respective superior organizational unit (parent element). For top-level units that are not subordinate to any other organizational unit, the attribute therefore remains empty (<em>NullTextIdentifier</em>). We also add the standard audit attributes for creation and last modification date and the respective user. For this sample, we also want to ensure the name of an organizational unit within the same direct parent is unique. We can enforce this at database level using an index. The entity now looks the following:</p><pre>/**<br> * @entity OrgUnit<br> * Organizational unit<br> * Public: No<br> *<br> * @attribute {Text} OrgUnitId<br> * Id of the organizational unit<br> * Length: 36<br> *<br> * @attribute {Text} Name<br> * Name of the organizational unit<br> * Length: 100<br> *<br> * @attribute {OrgUnit Identifier} [ParentOrgUnitId]<br> * Parent of the organizational unit (Null = root level)<br> * Delete Rule: Protect<br> *<br> * @attribute {Date Time} CreatedOn<br> * Timestamp of creation<br> *<br> * @attribute {User Identifier} CreatedBy<br> * User who created the record<br> *<br> * @attribute {Date Time} UpdatedOn<br> * Timestamp of last update<br> *<br> * @attribute {User Identifier} UpdatedBy<br> * User who last updated the record<br> *<br> * @index UX_Parent_Name<br> * Unique: Yes<br> * Attribute 1: ParentOrgUnitId<br> * Attribute 2: Name<br> */</pre><p>Note the lengths of the text attributes here, as these will become relevant later. We use GUIDs as identifiers (<em>OrgUnitId</em>), hence the length 36. The length of the name attribute and the delete rule of <em>ParentOrgUnitId </em>have also been chosen with care, but more on this later.</p><h4>Trading storage space for performance</h4><p>As we can already see from the data model, the foreign key relationship to the own entity results in a referential chain that gets longer with the number of hierarchy levels. As mentioned above, this parent reference is empty for top-level entities. Both root elements as well as all direct child elements of a specific organizational unit can therefore be selected very easily by filtering on the <em>ParentOrgUnitId </em>attribute. However, if you want to select all elements of one hierarchy level or elements across multiple levels, you have to recursively trace the tree starting from one or more parent elements. This means you must first select all child elements of the initial element followed by their respective child elements and so on. But this process is quite IO and computing intensive. In addition, this procedure can result in an endless loop when a circular reference occurs in the chain, i.e. when an element is defined as a parent element of an own (grand)parent element. Fortunately, circular references like this hardly ever show up in practical requirements. It is therefore far better to avoid such a constellation in the first place so as not to have to deal with infinite loops later.</p><p>Usually, data is read much more often than it is written. Wouldn’t it be nice if we could create a more performant solution that allows us to avoid recursions at least when selecting data? For the reasons mentioned above, we have to accept them for validation purposes at writing time anyways. This is why we create some additional attributes in the database:</p><pre>/**<br> * @entity OrgUnit<br> * Organizational unit<br> * Public: No<br> *<br> * [...]<br> *<br> * @attribute {Integer} [HierarchyLevel]<br> * Zero-based level of the organizational unit in hierarchy tree<br> *<br> * @attribute {Text} [HierarchyIds]<br> * Concatenated OrgUnitId path of the organizational unit in hierarchy tree<br> * Length: 722<br> *<br> * @attribute {Text} [HierarchyNames]<br> * Concatenated name path of the organizational unit in hierarchy tree<br> * Length: 1954<br> */</pre><p>So what are these attributes for and where do the weird text lengths come from? All <em>Text</em> fields in entities must have a defined length. As described below, this results in a technical requirement for our application. OutSystems <a href="https://success.outsystems.com/documentation/11/reference/outsystems_language/data/database_reference/database_data_types/">maps the data types to database types</a> on publishing. Up to a length of 2000 characters, <em>Text</em> is mapped to the NVARCHAR (SQL Server) resp. VARCHAR2 (Oracle) type, values above that to the less performant binary type NVARCHAR(MAX) resp. CLOB. Therefore we need to limit the maximum allowed depth of the hierarchy — in our case to 19 levels:</p><ul><li><strong>HierarchyLevel </strong>allows selections and calculations based on the hierarchical depth of an element</li><li><strong>HierarchyIds </strong>contains the sequence of <em>OrgUnitIds </em>from the root to the respective element and thus enables queries and checks for parenthood. As we will see later, this also helps prevent circular references. The length is calculated by the depth limit:<br>19 levels * Length(&quot;{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}&quot;)</li><li><strong>HierarchyNames </strong>contains a user-friendly representation of the organizational units name path separated by backslashes, which leads to the length: 19 levels * 100 + 18 separators * Length(&quot; \ &quot;)</li></ul><p>Now we need a little more storage space in the database, but we can perform many queries with simple selections that would normally only be possible recursively. Basically, it’s a similar deal as with indexes.</p><h4>Maintaining consistency</h4><p>But wait, the three new attributes contain information that is redundant to the <em>ParentOrgUnitId </em>relationship, don’t they. In addition to increased memory requirements, this also means a risk of data inconsistency. For example, if someone changes the <em>ParentOrgUnitId </em>or the name of an element but does not adjust the <em>Hierarchy…</em> attributes, the database contains contradictory information. This gets even worse because both attributes <em>HierarchyIds </em>and <em>HierarchyNames </em>contain concatenated information originating from other records, the own parent element chain.</p><p>At this point, the chosen software architecture comes to our aid: All organizational units are stored and managed within our core service. This is why we have created the entity with <em>Public </em>set to <em>No</em>. It is therefore only available within the core service and can only be accessed using our own logic. By doing so, the logic can ensure consistent changes across all attributes and even multiple records. As a general rule, it is good practice to keep entities private or at least only expose them for read-only access.</p><p>So let’s start with the first server action <em>OrgUnit_UpdateHierarchy </em>of the core service. Its job is to recursively build the tree after changes to organizational units, recalculate the three <em>Hierarchy…</em> attributes for all elements and write them back to the database. This can be accomplished with a single advanced SQL call:</p><pre>WITH HIERARCHY_CTE AS<br>(<br>    SELECT<br>        {OrgUnit}.[OrgUnitId],<br>        {OrgUnit}.[ParentOrgUnitId],<br>        0 AS HierarchyLevel,<br>        CONVERT(VARCHAR(MAX),{OrgUnit}.[Name]) AS HierarchyNames,<br>        &#39;{&#39; + CONVERT(VARCHAR(MAX),{OrgUnit}.[OrgUnitId]) + &#39;}&#39; AS HierarchyIds<br>    FROM {OrgUnit} WHERE {OrgUnit}.[ParentOrgUnitId] IS NULL<br>    UNION ALL<br>    SELECT<br>        self.[OrgUnitId],<br>        self.[ParentOrgUnitId],<br>        parent.[HierarchyLevel] + 1 AS HierarchyLevel,<br>        parent.[HierarchyNames] + &#39; \ &#39; + CONVERT(VARCHAR(MAX),self.[Name]) AS HierarchyNames,<br>        parent.[HierarchyIds] + &#39;{&#39; + CONVERT(VARCHAR(MAX),self.[OrgUnitId]) + &#39;}&#39; AS HierarchyIds<br>    FROM {OrgUnit} self<br>    INNER JOIN HIERARCHY_CTE parent ON parent.[OrgUnitId] = self.[ParentOrgUnitId]<br>)<br><br>UPDATE {OrgUnit} SET<br>    {OrgUnit}.[HierarchyLevel] = HIERARCHY_CTE.[HierarchyLevel],<br>    {OrgUnit}.[HierarchyNames] = HIERARCHY_CTE.[HierarchyNames],<br>    {OrgUnit}.[HierarchyIds] = HIERARCHY_CTE.[HierarchyIds]<br>FROM {OrgUnit} JOIN HIERARCHY_CTE ON {OrgUnit}.[OrgUnitId] = HIERARCHY_CTE.[OrgUnitId]</pre><p>As you can see there is no input parameter and also no output generated. Nevertheless, OutSystems forces us to add an output structure to the SQL element, so we can just use the entity <em>OrgUnit </em>here. Should you not be that familiar with SQL, I would like to explain what the above script is doing:</p><ul><li>The script is split into two parts. The first one is a so called common table expression to recursively select the tree of organizational units as a flat list containing the <em>OrgUnitId</em>, <em>ParentOrgUnitId </em>and the three <em>Hierarchy…</em> columns.</li><li>It starts with selecting only the root level elements by filtering WHERE {OrgUnit}.[ParentOrgUnitId] IS NULL, returning <em>HierarchyLevel </em>being zero (indicating root level) and “initializing” <em>HierarchyNames </em>and <em>HierarchyIds </em>with name and parenthesized GUID of the respective unit.</li><li>This is then combined by using UNION ALL with the selection of direct child elements (alias self) by joining with the already selected common table expression result HIERARCHY_CTE (alias parent) on the join condition parent.[OrgUnitId] = self.[ParentOrgUnitId]. <em>HierarchyLevel </em>is increased by selecting parent.[HierarchyLevel] + 1 AS HierarchyLevel while <em>HierarchyNames </em>and <em>HierarchyIds </em>are extended on the right-hand side by concatenating parent.[Hierarchy...] with the corresponding string &#39; \ &#39; + self.[Name] resp. &#39;{&#39; + self.[OrgUnitId] + &#39;}&#39;.</li><li>The second part of the script uses the first part’s result to update the records in <em>OrgUnit </em>with the data corresponding by <em>OrgUnitId</em>.</li></ul><p>To indicate that these attributes in the entity are calculated, I recommend to extend their description in OutSystems with a hint like “(calculated in OrgUnit_UpdateHierarchy)”.</p><h4>Validating incoming data</h4><p>The second server action we implement is used to validate organizational units before they are saved. For receiving data to be saved, we define the structure <em>OrgUnit_Save </em>with attributes for the name and the <em>ParentOrgUnitId</em>. The easiest way to do this is to copy the entire entity and paste it under <em>Structures</em>. The advantage with doing so is OutSystems not only takes over the individual attributes but also their configuration such as description, data type, lengths and so forth. Afterwards, you can simply delete attributes that are not required and make any necessary adjustments.</p><pre>/**<br> * @structure OrgUnit_Save<br> * Details of an organizational unit to be saved<br> * Public: Yes<br> *<br> * @attribute {Text} Name<br> * Name of the organizational unit<br> * Length: 100<br> *<br> * @attribute {OrgUnit Identifier} [ParentOrgUnitId]<br> * Parent of the organizational unit (Null = root level)<br> */</pre><p>The service action has two input parameters <em>OrgUnitId </em>and <em>OrgUnitSave</em>, validates the data and throws a <em>ValidationException </em>if a check fails:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*3DKlSzve8o9g1g0u6gDDJw.png" /><figcaption>Server action OrgUnit_Validate</figcaption></figure><ul><li>First we check if the name is not empty as it should be a mandatory information so an organizational unit always has a name to be displayed: Trim(OrgUnitSave.Name) &lt;&gt; &quot;&quot;</li><li>In <em>GetSiblingByName</em> we try to select another organizational unit (OrgUnit.OrgUnitId &lt;&gt; OrgUnitId) that is a direct sibling in the tree (OrgUnit.ParentOrgUnitId &lt;&gt; OrgUnitSave.ParentOrgUnitId) and has the same name (OrgUnit.Name = OrgUnitSave.Name). Giving aggregates a <em>Max. Records</em> value is recommended by OutSystems AI Mentor Studio for performance reasons. Since there cannot be more than one result due to our <em>UX_Parent_Name </em>index, and we only need the result to check for at least one conflict, we can set it to one.</li><li>If no name conflict is found and the organizational unit is on root level OrgUnitSave.ParentOrgUnitId = NullTextIdentifier() we can end the validation. Otherwise we also need to validate the parent relationship.</li><li>To do so, we need to <em>GetParentById</em> (OrgUnit.OrgUnitId = OrgUnitSave.ParentOrgUnitId). If the parent cannot be found (GetParentById.List.Empty), the own level would be to deep (GetParentById.List.Current.OrgUnit.HierarchyLevel &gt;= 18) or the parent would be an own child (Index(GetParentById.List.Current.OrgUnit.HierarchyIds, &quot;{&quot; + OrgUnitId + &quot;}&quot;) &lt;&gt; -1) we throw an exception.</li></ul><p>Here for the first time we see the advantage of the two additional attributes <em>HierarchyLevel</em> and <em>HierarchyIds </em>in the database. With their help, we no longer have to perform a recursive database query for validation, but can directly select and check the depth of the future parent element, and thus also our own depth. We can also use <em>HierarchyIds</em> to check whether our own id occurs in the id path of the parent element, which means it is a direct or indirect child and would create a circular reference in the tree.</p><h4>Exposing a service interface</h4><p>So far, all implemented elements of the core service except for the <em>OrgUnit_Save </em>structure were non-public, i.e. usable within the <em>OrgUnit_CS </em>module only. It is now time to provide an interface for the outside world. Of course we want to allow consumers of the service to perform the default CRUD (create, read, update and delete) actions on organizational units. We do so by exposing some public server actions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*fiy9BjQMnNEpVJLeA7lcSg.png" /><figcaption>CRUD server actions OrgUnit</figcaption></figure><p><strong>OrgUnit_Create</strong></p><pre>/**<br> * @serveraction OrgUnit_Create<br> * Creates a new organizational unit<br> *<br> * @input {OrgUnit_Save} OrgUnitSave<br> * Details of the organizational unit to be saved<br> *<br> * @output {OrgUnit Identifier} OrgUnitId<br> * Id of the new organizational unit<br> */</pre><ul><li>In the introduction, the action makes use of the previously implemented non-public server action <em>OrgUnit_Validate</em> on the data to be saved. If this check fails, a <em>ValidationException </em>is thrown there, aborting processing.</li><li>The next two steps are the basic ones to create the new record in the database and return the new identifier in output parameter <em>OrgUnitId</em>. By the way, this is generated directly in the <em>CreateOrgUnit </em>call via the expression TextToIdentifier(GenerateGuid()). <em>GenerateGuid </em>is added to the dependencies from <em>System</em>.</li><li>Finally, the call of <em>OrgUnit_UpdateHierarchy </em>ensures the three hierarchy attributes for optimized queries on the tree are updated in the database.</li></ul><p><strong>OrgUnit_Update</strong></p><pre>/**<br> * @serveraction OrgUnit_Update<br> * Updates an organizational unit<br> *<br> * @input {OrgUnit Identifier} OrgUnitId<br> * Id of the organizational unit<br> *<br> * @input {OrgUnit_Save} OrgUnitSave<br> * Details of the organizational unit to be saved<br> */<br><br>// Update attributes<br>GetOrgUnitForUpdate.Record.OrgUnit.Name = Trim(OrgUnitSave.Name)<br>GetOrgUnitForUpdate.Record.OrgUnit.ParentOrgUnitId = OrgUnitSave.ParentOrgUnitId<br>GetOrgUnitForUpdate.Record.OrgUnit.UpdatedOn = CurrDateTime()<br>GetOrgUnitForUpdate.Record.OrgUnit.UpdatedBy = GetUserId()</pre><p>This is implemented the same way as <em>OrgUnit_CreateOrg </em>is except the middle part which of course is not inserting a new record to the database but selecting the record specified by <em>OrgUnitId</em> and updating the relevant attributes.</p><p><strong>OrgUnit_Delete</strong></p><pre>/**<br> * @serveraction OrgUnit_Delete<br> * Updates an organizational unit<br> *<br> * @input {OrgUnit Identifier} OrgUnitId<br> * Id of the organizational unit<br> *<br> * @input {Boolean} [IsRecursive]<br> * True to recursively delete all children<br> * Default: False<br> */</pre><p>This action has two different operation modes:</p><ul><li>If <em>IsRecursive </em>is not set, aggregate <em>GetOrgUnitByHierarchyIds </em>selects if there is at least one (<em>Max Records</em> set to one again) direct or indirect child of the organizational unit to be deleted by filtering OrgUnit.HierarchyIds like &quot;%{&quot; + OrgUnitId + &quot;}%&quot;. If so, a <em>ValidationException </em>is thrown otherwise the record is deleted in the entity.</li><li>The second operation mode allows to delete an organizational unit and all its direct and indirect children. This is performed with the following advanced SQL statement which again as result structure simply uses the <em>OrgUnit </em>entity: DELETE FROM {OrgUnit} WHERE {OrgUnit}.[HierarchyIds] LIKE &#39;%[&#39; + @OrgUnitId + &#39;}%&#39;</li></ul><p><strong>OrgUnit_Search</strong></p><pre>/**<br> * @serveraction OrgUnit_Search<br> * Search for organizational units<br> *<br> * @input {OrgUnit_SearchCriteria} [SearchCriteria]<br> * Criteria to search for organizational units<br> *<br> * @output {OrgUnit_Result List} Results<br> * List of matching organizational units<br> */</pre><p>The last of the four CRUD actions is to read data and uses the aggregate <em>GetOrgUnitsBySearchCriteria </em>to select from <em>OrgUnit</em>, joined two times with the <em>System </em>entity <em>User </em>(alias CreatedByUserand LastUpdatedByUser) to also get details about the users who created (OrgUnit.CreatedBy = CreatedByUser.Id) and last updated (OrgUnit.LastUpdatedBy = LastUpdatedByUser.Id) the record. The search is performed by the filtering in that aggregate:</p><ul><li>To search for SearchTerm in hierarchy names path: OrgUnit.HierarchyNames like &quot;%&quot; + SearchCriteria.SearchTerm + &quot;%&quot;</li><li>To restrict the results to only direct children (ParentOrgUnitIdIsRecursive = False) or otherwise also indirect children of a single element in the tree: SearchCriteria.ParentOrgUnitId = NullTextIdentifier() or OrgUnit.ParentOrgUnitId = SearchCriteria.ParentOrgUnitId or (SearchCriteria.ParentOrgUnitIdIsRekursive and OrgUnit.HierarchyIds like &quot;%{&quot; + SearchCriteria.ParentOrgUnitId + &quot;}%&quot;)</li><li>To exclude a single element and all its direct and indirect children: SearchCriteria.ExcludeOrgUnitIdRecursive = NullTextIdentifier() or (OrgUnit.OrgUnitId &lt;&gt; SearchCriteria.ExcludeOrgUnitIdRecursive and not (OrgUnit.HierarchyIds like &quot;%{&quot; + SearchCriteria.ExcludeOrgUnitIdRecursive+ &quot;}%&quot;))</li><li>To limit the result to a certain maximal depth level: SearchCriteria.MaxHierarchyLevel = -1 or OrgUnit.HierarchyLevel &lt;= SearchCriteria.MaxHierarchyLevel</li></ul><p>Instead of a tree structure, the result obviously is a flat list of organizational units. As described above, OutSystems does not support self-referencing structures and therefore does not allow returning a recursive tree structure. In order to nonetheless provide the tree in a form that is easy to consume, the result list in the aggregate is sorted by <em>HierarchyNames</em>. In this way, child elements always immediately follow their individual parent element in alphabetical order.</p><p>I’m sure you’ve noticed that <em>SearchCriteria </em>and <em>Results </em>each use their own structure. Of course, I don’t want to withhold their configuration either:</p><pre>/**<br> * @structure OrgUnit_SearchCriteria<br> * Criteria to search for organizational units<br> * Public: Yes<br> *<br> * @attribute {Text} [SearchTerm]<br> * Search in HierarchyNames<br> *<br> * @attribute {OrgUnit Identifier} [ParentOrgUnitId]<br> * Filter by parent unit (parent unit is only included if ParentOrgUnitIdIsRecursive = True)<br> *<br> * @attribute {Boolean} [ParentOrgUnitIdIsRecursive]<br> * True to also return the specified parent unit (ParentOrgUnitId) and all indirect children<br> *<br> * @attribute {OrgUnit Identifier} [ExcludeOrgUnitIdRecursive]<br> * Exclude a specific unit and it&#39;s direct and indirect children<br> *<br> * @attribute {Integer} [MaxHierarchyLevel]<br> * Maximum returned hierarchy level (-1 for no filtering)<br> * Default: -1<br> */<br><br>/**<br> * @structure OrgUnit_Result<br> * Result of an organizational unit search<br> * Public: Yes<br> *<br> * @attribute {OrgUnit Identifier} OrgUnitId<br> * Id of the organizational unit<br> *<br> * @attribute {Text} Name<br> * Name of the organizational unit<br> * Length: 100<br> *<br> * @attribute {OrgUnit Identifier} [ParentOrgUnitId]<br> * Parent of the organizational unit (Null = root level)<br> *<br> * @attribute {Integer} [HierarchyLevel]<br> * Zero-based level of the organizational unit in hierarchy tree<br> *<br> * @attribute {Text} [HierarchyIds]<br> * Concatenated OrgUnitId path of the organizational unit in hierarchy tree<br> *<br> * @attribute {Text} [HierarchyNames]<br> * Concatenated name path of the organizational unit in hierarchy tree<br> *<br> * @attribute {Date Time} CreatedOn<br> * Timestamp of creation<br> *<br> * @attribute {User Identifier} CreatedBy<br> * User who created the record<br> *<br> * @attribute {Text} [CreatedByName]<br> * Name of the user who created the record<br> *<br> * @attribute {Date Time} UpdatedOn<br> * Timestamp of last update<br> *<br> * @attribute {User Identifier} UpdatedBy<br> * User who last updated the record<br> *<br> * @attribute {Text} [UpdatedByName]<br> * Name of the user who last updated the record<br> */</pre><h3>UI: How to display hierarchical data</h3><p>One of the first options that comes to mind for displaying hierarchical data in a GUI is certainly the well-known tree view. However, if we look through the default controls of the OutSystems UI, we won’t find such a component there. But don’t worry, we don’t have to code our own screen widget and struggle with the depths of React and JavaScript. Instead, I would like to present a simple solution based on the list control:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6_w3oL6rI_A9uLoQtnHNCQ.png" /><figcaption>Hierarchy list view &amp; added dependencies</figcaption></figure><p>Obviously, we need the service actions of the core service, so we add them as a dependency to the UI module.</p><h4>Loading the tree</h4><p>For the simplicity of this demo, I decided to implement everything on one screen. This loads the list of organizational units via the fetch action <em>GetOrgUnits</em>. This calls the <em>OrgUnit_Search </em>in the core service and assigns the result to the output parameter <em>List</em>. As can be seen in the screenshot above, in addition to the organizational unit data, we need further information to display the tree view, e.g. whether an element is collapsed. To do this, we create a new structure in the UI module:</p><pre>/**<br> * @structure OrgUnit_TreeItem<br> * Tree item data to display an organizational unit<br> * Public: No<br> *<br> * @attribute {OrgUnit_Result} OrgUnit<br> * Organizational unit data<br> *<br> * @attribute {Boolean} HasChildren<br> * True to indicate the element has children<br> *<br> * @attribute {Boolean} IsCollapsed<br> * True if the element is currently collapsed in the tree view<br> *<br> * @attribute {Boolean} IsVisible<br> * True if the element is currently visible in the tree view<br> */</pre><p>To hold this extended data for the tree view on the screen, we create a new local variable <em>TreeItems</em> of type <em>OrgUnit_TreeItem List</em>. After the organizational unit data has been loaded, this variable must of course also be filled with data. To do so, we handle the <em>On After Fetch</em> event of <em>GetOrgUnits</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*yIiPWSmZsZDYfteDe6lxlg.png" /><figcaption>Fetching and building up the tree</figcaption></figure><ul><li>As <em>GetOrgUnitsOnAfterFetch </em>is not only called once but after each data fetch and we do not want to loose the collapse state of the tree, in the first loop we append the ids of all expanded elements to the variable <em>ExpandedOrgUnitIds </em>of type <em>OrgUnit Identifier List</em>.</li><li>Afterwards the local screen variable <em>TreeItems </em>is cleared so it can easily be repopulated within the next loop.</li><li>This next loop iterates all freshly fetched organizational units in <em>GetOrgUnits.List</em> and assigns its values to the temporary variable <em>CurrentOrgUnitTreeItem</em>, which has our target type <em>OrgUnit_TreeItem</em>. Also the attribute <em>HasChildren </em>is calculated based on the subsequent element. By default <em>IsCollapsed </em>is initialized with <em>True </em>for all elements that have children.</li></ul><pre>// CurrentOrgUnitTreeItem<br>CurrentOrgUnitTreeItem.OrgUnit = GetOrgUnits.List.Current<br>CurrentOrgUnitTreeItem.HasChildren = (<br>  GetOrgUnits.List.CurrentRowNumber &lt; GetOrgUnits.List.Length - 1 and<br>  GetOrgUnits.List.Current.OrgUnitId = GetOrgUnits.List[GetOrgUnits.List.CurrentRowNumber + 1].ParentOrgUnitId<br>)<br>CurrentOrgUnitTreeItem.IsCollapsed = CurrentOrgUnitTreeItem.HasChildren</pre><ul><li>Elements without children (not CurrentOrgUnitTreeItem.HasChildren) cannot be collapsed, so they can directly be appended to the <em>TreeItems</em>.</li><li>For collapsible elements we check by their id if they were previously expanded (existent in <em>ExpandedOrgUnitIds</em>) and overwrite their <em>IsCollapsed </em>attribute with not AnyExpandedOrgUnitIds.Result before appending them to <em>TreeItems</em>.</li><li>Finally <em>Tree_RefreshItems </em>is called to iterate all elements in the updated <em>TreeItems </em>list to also set their <em>IsVisible </em>attribute. This is located in a separate client action because it is reused when switching the collapsed state of an element later.</li></ul><pre>// IsVisible<br>TreeItems.Current.IsVisible = (<br>  LastCollapsedIdPath = &quot;&quot; or<br>  Substr(TreeItems.Current.OrgUnit.HierarchyIds,0,Length(LastCollapsedIdPath)) &lt;&gt; LastCollapsedIdPath<br>)</pre><ul><li>The temporary variable <em>LastCollapsedIdPath </em>is set to the <em>HierarchyIds </em>value of the current element if it is visible and collapsed. In combination with the previous assignment, this ensures that all children of the last collapsed element (<em>HierarchyIds </em>starts with <em>LastCollapsedIdPath</em>) are invisible, while the next element, which is not a child, is visible.</li></ul><h4>Designing the screen</h4><p>Now that the data is prepared for display, we can implement the UI:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o8E6u8xtvzDd2EoG2xA9Uw.png" /><figcaption>Demo app screen and tree view list</figcaption></figure><ul><li>We place a <em>Container_TreeCollapseAll </em>in the <em>MainContent</em> to hold two links for collapsing and expanding all elements in the tree.</li><li><em>List_Tree </em>is a normal list control to display the tree items.</li><li>Each item will be represented by an instance of <em>Container_TreeItem</em> which is styled with the CSS classes list-item vertical-align gap-s padding-s. This aligns <em>Container_TreeItem_HierarchyLevel </em>and <em>Container_TreeItem_OrgUnitName </em>to be in line.</li><li>The magic is happening on <em>Container_TreeItem_HierarchyLevel</em>, styled by CSS class text-align-right in combination with its attribute style being &quot;width:&quot; + (TreeItems.Current.OrgUnit.HierarchyLevel * 2 + 2) + &quot;em;&quot;. This generates the indentation by 2 em per level. The +2 at the end adds space for the icon to expand or collapse (<em>Size</em> = 2x font size).</li><li>At a time, only one of both icons <em>Icon_Plus </em>and <em>Icon_Minus</em> is visible (<em>Visible </em>= TreeItems.Current.IsCollapsed eg. not TreeItems.Current.IsCollapsed).</li><li><em>Container_TreeItem_OrgUnitName</em> is just showing the organizational units name and linking it to a client action we will implement later.</li></ul><p>Pretty cool, isn’t it? The only little bit missing is some display logic for expanding and collapsing — and needless to say, neither the name link will remain unexplained.</p><h4>Collapsing tree items</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*DN9sB7-S5uE9Caesn-tTmQ.png" /><figcaption>Collapse tree item logic</figcaption></figure><p>With all the preparation we did so far, expanding and collapsing tree items is very easy. The <em>Link_OrgUnitCollapse </em>is only displayed for elements having children (<em>Visible </em>= TreeItems.Current.HasChildren). Switching the collapse state of a tree item is simply invert its IsCollapsed attribute:</p><pre>TreeItems.Current.IsCollapsed =<br>  not TreeItems.Current.IsCollapsed and<br>  TreeItems.Current.HasChildren</pre><p>The additional check for HasChildren is to ensure only collapsible tree items are modified, just in case the action should be called for a childless element. Again, finally we call <em>Tree_RefreshItems</em> so the <em>IsVisible </em>attribute of all <em>TreeItems </em>is updated accordingly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*qiudYrytO2S4Dy-PziW3fw.png" /><figcaption>Collapse all logic</figcaption></figure><p>This next client action allows to expand or collapse all elements at once (two links above the list). Therefore, <em>Tree_OnCollapseAll </em>receives <em>IsCollapse </em>as Boolean input parameter and assigns its value to all <em>TreeItems </em>by iterating them. Of course, the action is concluded by calling <em>Tree_RefreshItems</em>.</p><h4>Editing tree items</h4><p>As promised, I won’t withhold what happens in the small sample application when you click on an organizational unit. In this case, a pop-up dialog opens containing a text field for the name and a dropdown for selecting the parent unit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xJ-SAeME77ba1fwiK4fjAQ.png" /><figcaption>UI: Popup and custom dropdown</figcaption></figure><ul><li>To display the parent elements indented by level in the dropdown as well, we can set <em>Options Content</em> to <em>Custom</em>. This allows us to place a <em>Container</em> in the dropdown control that now represents the individual option entries.</li><li>Setting <em>Style Classes</em> to &quot;full-width&quot; ensures that the entry extends across the entire width. The style attribute uses &quot;padding-left: &quot; + GetParentOrgUnits.List.Current.HierarchyLevel + &quot;em:&quot; to indent again.</li></ul><p>For sure, this selection list must also be loaded. The interesting part is to prevent circular references. Wouldn’t it be smart to offer organizational units that are eligible as parents only. Fortunately, with the attribute <em>ExcludeOrgUnitIdRecursive</em> in <em>OrgUnit_SearchCriteria </em>we have created a suitable filter to achieve this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*Yekix0LpKdbUJazz3lDsWw.png" /><figcaption>Fetch selection list and show popup logic</figcaption></figure><ul><li><em>GetParentOrgUnits </em>can be fetched <em>Only on demand</em> because it is exclusivly used by the popup dialog and refreshed in <em>OrgUnit_ShowPopup </em>when needed. To determine this, we need to know which <em>OrgUnitId </em>has been excluded from the loaded selection list. This is what the second output parameter <em>ExcludedOrgUnitId </em>is for.</li><li><em>OrgUnit_ShowPopup </em>opens or closes the popup depending on the input parameter <em>Show</em>, whereby the optional parameter <em>OrgUnitId </em>specifies which organizational unit is to be opened.</li><li>First we check if the popup is to be hidden or shown to create a new entry (not Show or OrgUnitId = NullTextIdentifier()). If so, the local variable <em>OrgUnit_Data </em>is cleared:</li></ul><pre>/**<br> * @record OrgUnit_Data<br> * Organizational unit data for the popup dialog<br> * <br> * @attribute {Boolean} [HasChildren]<br> * @attribute {OrgUnit Identifier} [OrgUnitId]<br> * @attribute {OrgUnit_Save} [OrgUnitSave]<br> */<br><br>// Clear OrgUnitData<br>OrgUnit_Data.OrgUnitId = NullTextIdentifier()<br>OrgUnit_Data.OrgUnitSave.Name = &quot;&quot;<br>OrgUnit_Data.OrgUnitSave.ParentOrgUnitId = NullTextIdentifier()<br>OrgUnit_Data.HasChildren = False</pre><ul><li>Otherwise the index of OrgUnitId in TreeItems is searched and the respective data is assigned to OrgUnit_Data: OrgUnit_Data = TreeItems[IndexOfOrgUnitId.Position]. If not found an error message is displayed.</li><li>Finally, we check whether the selection list needs to be fetched (Show and (not GetParentOrgUnits.IsDataFetched or GetParentOrgUnits.ExcludedOrgUnitId &lt;&gt; OrgUnitId)), trigger <em>RefreshGetParentOrgUnits </em>accordingly and show or hide the popup (OrgUnit_ShowPopup = Show).</li></ul><p>Not to make the article any longer, I will abbreviate the implementation of the buttons on the popup dialog. The <em>X</em> to close and the <em>Cancel </em>button call <em>OrgUnit_ShowPopup </em>with the parameter <em>Show</em> set to <em>False</em>. <em>Save </em>and <em>Delete</em> buttons each have their individual client action, which should be straightforward:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*lA3ir4_IDP8lHKHqgoR0Lg.png" /><figcaption>Save and delete logic</figcaption></figure><p>You can download the complete application from the OutSystems Forge:</p><p><a href="https://www.outsystems.com/forge/component-overview/17744/hierarchical-data-in-outsystems-demo">Hierarchical data in OutSystems (Demo)</a></p><p>I hope this article was inspiring and gave you some ideas on how you can implement hierarchical data in your OutSystems projects easily and without much effort. If you liked it, feel free to follow me on medium and leave a few claps and/or a coffee 😉. In case you have any questions left open or have tips for me to improve, please contact me via medium or my <a href="https://www.outsystems.com/profile/enrntqhemy/">OutSystems profile</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ee689e09cbf" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/hierarchical-data-in-outsystems-8ee689e09cbf">Hierarchical data in OutSystems</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Make data searchable in OutSystems]]></title>
            <link>https://itnext.io/make-data-searchable-in-outsystems-87d5273325b3?source=rss-15f59cd3d285------2</link>
            <guid isPermaLink="false">https://medium.com/p/87d5273325b3</guid>
            <category><![CDATA[advanced-sql]]></category>
            <category><![CDATA[pagination]]></category>
            <category><![CDATA[dynamic-sorting]]></category>
            <category><![CDATA[outsystems]]></category>
            <dc:creator><![CDATA[Sebastian Krempel]]></dc:creator>
            <pubDate>Wed, 15 Nov 2023 16:23:21 GMT</pubDate>
            <atom:updated>2023-11-15T16:49:25.021Z</atom:updated>
            <content:encoded><![CDATA[<h4>Extending the Master-Detail sample with a flexible search functionality</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0D-FLsZqL_G3LjgNlhuUZQ.png" /></figure><p>In my last two-part article, I described how to handle master-detail data in OutSystems. As an example, we implemented a small application that allows you to create and edit purchase orders and their order items. However, the example lacks a list of purchase orders and a way to navigate to the respective detail screens. In this article, I would therefore like to add this missing function to the example and show a sample for implementing a flexible search functionality that can be used throughout the application.</p><h3>What you need</h3><p>If you want to follow up the implementation on your own, you need:</p><ul><li>An OutSystems account (a <a href="https://www.outsystems.com/free-edition/">free personal environment</a> is sufficient)</li><li>OutSystems Service Studio</li><li>The sample application implemented in part one and two of my last article:</li></ul><ul><li><a href="https://itnext.io/master-detail-data-in-outsystems-1-cs-869b0777f8ee">Master-Detail data in OutSystems (1) CS</a></li><li><a href="https://itnext.io/master-detail-data-in-outsystems-2-ui-a8331a585f4d">Master-Detail data in OutSystems (2) UI</a></li></ul><p>This tutorial is also suitable for OutSystems newcomers. However, a little prior experience in using the Service Studio is useful.</p><h3>Getting a list of purchase orders</h3><h4>Architectural and performance considerations</h4><p>The function of getting a list of orders is so fundamental that it should be part of the core functionality, right? So let’s start with the core service again. 😀<br>But to be serious: According to our software architecture, it is the core service’s job to store data and allow other modules to access it. So we should start the implementation here.</p><p>So far, <em>Order_CS </em>only provides the server action <em>Orders_GetOrder </em>for receiving orders. This receives the <em>OrderId </em>as input and returns the order with all its order items in the <em>Order_Detail </em>structure. The simplest solution to obtain a list of all orders would be to simply create a copy of this server action and remove the <em>OrderId </em>parameter and the filtering. However, this has some disadvantages:</p><ul><li>Instead of selecting all orders at once, you usually only need a subset that matches certain search criteria.</li><li>To meet the requirements of end users, the result lists need to be sorted by one or more attributes.</li><li>Often only a paginated list is displayed, as transferring large quantities of results to consumers at once costs a lot of data traffic.</li><li>As can be seen in the following illustration, <em>Orders_GetOrder </em>has been optimized to select a single order with all its order items, which would be very performance-intensive and irrelevant for overview lists.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*GnKwmrd7721QWqPiiOYDAw.png" /><figcaption>Implementation of <em>Orders_GetOrder</em></figcaption></figure><p>So from a performance perspective we want to have a server action that is optimized to</p><ul><li>retrieve a selection of purchase orders that match given search criteria,</li><li>already sort the results by given sort attributes,</li><li>paginate the returned data rows,</li><li>and return only a projection of the attributes needed for overview lists.</li></ul><h4>Additional data structures</h4><p>Let’s first create the additional data structures that are required in <em>Order_CS </em>for the new search function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*iOVA_7iZNEvvTLYwuDVkQw.png" /><figcaption>New structures for the search feature</figcaption></figure><p>As you can see, I organized the structures in folders: <em>Order</em> holds all structures used for purchase orders, <em>Data </em>is for general helper structures.</p><ul><li><em>PaginationInfo</em><br>This public structure is used to control pagination. It defines the zero-based index of the first result and the maximum number of records to be returned. Both attributes are optional, so by default the pagination will start at index 0 and contain the max. possible Integer count of records (2147483647).</li><li><em>TotalRows</em><br>This private structure is only used as output structure for advanced SQL queries to receive the total number of rows that match the given search criteria.</li><li><em>Order_Result</em><br>Similar to the public structure <em>Order_Detail</em>, which was implemented in my last articles, this one is to represent a single result of a purchase order search. It contains nearly the same attributes, but stripped down to the really relevant ones for result lists.</li><li>Order_SearchCriteria<br>This public structure contains all attributes, the purchase order search is allowing to filter for.</li></ul><pre>/**<br> * @structure PaginationInfo<br> * Pagination control<br> * Public: Yes<br> *<br> * @attribute {Integer} [StartIndex]<br> * Index of first returned result<br> * Default: 0<br> *<br> * @attribute {Integer} [MaxResults]<br> * Max. number of results returned<br> * Default: 2147483647<br> */<br><br>/**<br> * @structure TotalRows<br> * Total number of rows<br> * Public: No<br> *<br> * @attribute {Integer} Count<br> * Total number of matching rows<br> */<br><br>/**<br> * @structure Order_Result<br> * Result of a purchase order<br> * Public: Yes<br> *<br> * @attribute {Order Identifier} OrderId<br> * Id of the purchase order<br> *<br> * @attribute {Date} OrderDate<br> * Date of the purchase order<br> *<br> * @attribute {Integer} ItemsCount<br> * Number of order items<br> *<br> * @attribute {Currency} TotalAmount<br> * Total amount of all order items<br> *<br> * @attribute {Date Time} CreatedOn<br> * Timestamp of creation<br> *<br> * @attribute {User Identifier} CreatedBy<br> * User who created the record<br> *<br> * @attribute {Text} [CreatedByName]<br> * Name of user who created the record<br> *<br> * @attribute {Date Time} UpdatedOn<br> * Timestamp of last update<br> *<br> * @attribute {User Identifier} UpdatedBy<br> * User who last updated the record<br> *<br> * @attribute {Text} [UpdatedByName]<br> * Name of user who last updated the record<br> */<br><br>/**<br> * @structure Order_SearchCriteria<br> * Criteria to search for orders<br> * Public: Yes<br> *<br> * @attribute {Date} [OrderDate_Start]<br> * Earliest order date to match<br> *<br> * @attribute {Date} [OrderDate_End]<br> * Latest order date to match<br> */</pre><h4>One server action to search them all</h4><p>For the search feature we will use an advanced SQL query with a dynamic ORDER BY clause. To prevent a SQL injection we need to preprocess the dynamic part. One possible way is described in this <a href="https://success.outsystems.com/documentation/how_to_guides/development/how_to_enable_dynamic_sorting_in_a_table_fed_by_a_sql_query/">OutSystems documentation article</a>. For a project I was working on earlier, I reworked this method to be suitable for multiple fields and include a default sort order as a fallback option. In the meantime, I improved it again and published the most recent version in the Forge:</p><p><a href="https://www.outsystems.com/forge/component-overview/8548/encodingsortforsql">EncodingSortForSQL</a></p><p>After installing the component into our environment, we can add a dependency to its helper function <em>EncodingSortForSQL</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*xZNEv3BiwcutZ1SDBdZOzw.png" /><figcaption>Required dependencies</figcaption></figure><p>Now everything is prepared to start with low-coding the public server action <em>Order_Search</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*AQETYg-EdSO8ymCZSt24vg.png" /><figcaption>Server action Order_Search (part 1)</figcaption></figure><p>As you can see, the new server action <em>Order_Search </em>has many parameters, but the flow is quite simple. Of course, we start by creating all the input and output parameters:</p><pre>/**<br> * @serveraction Order_Search<br> * Returns a list of matching orders<br> * Public: Yes<br> *<br> * @input {Order_SearchCriteria} [OrderSearchCriteria]<br> * Criteria to search for orders<br> *<br> * @input {PaginationInfo} [PaginationInfo]<br> * Pagination control<br> *<br> * @input {Text} [SortField]<br> * String with comma separated SQL sort attributes (e.g. &quot;CreatedOn DESC&quot;, &quot;OrderDate,TotalAmount DESC&quot;)<br> * Default: &quot;OrderDate,TotalAmount DESC&quot;<br> *<br> * @output {Order_Result List} OrderResults<br> * List of orders<br> *<br> * @output {Integer} TotalCount<br> * Total number of matching orders<br> */</pre><p>Next we implement the advanced SQL query. The parameters can simply be copied from <em>Order_SearchCriteria</em> and <em>PaginationInfo</em>. <em>SortField</em> is a bit special as we need to set <em>Expand Inline</em> to <em>Yes</em>. By doing so, OutSystems will no longer encode this parameters value and allows us to directly pass SQL code into the query statement. This is why we will encode it later with the helper function added as a dependency before. The last parameter <em>NullDate </em>is used to pass OutSystems NullDate() value, so the database can compare stored values against it.</p><p>In an advanced SQL query, you always have to define the expected output structure so the results can be assigned correctly. This can be one or more entities or structures whose attributes match the result columns of the SQL query in sequence and data types. So in our app we can use <em>Order_Result</em> for the purchase order data followed by <em>TotalRows</em> to receive the total number of matching records.</p><pre>WITH BASE_CTE AS<br>(<br>  SELECT<br>      {Order}.[OrderId]                AS OrderId,<br>      {Order}.[OrderDate]              AS OrderDate,<br>      COUNT({OrderItem}.[OrderItemId]) AS ItemsCount,<br>      SUM({OrderItem}.[Quantity] *<br>          {OrderItem}.[Amount])        AS TotalAmount,<br>      {Order}.[CreatedOn]              AS CreatedOn,<br>      {Order}.[CreatedBy]              AS CreatedBy,<br>      CreatedByUser.[Name]             AS CreatedByName,<br>      {Order}.[UpdatedOn]              AS UpdatedOn,<br>      {Order}.[UpdatedBy]              AS UpdatedBy,<br>      UpdatedByUser.[Name]             AS UpdatedByName<br>  FROM {Order}<br>  LEFT JOIN {OrderItem} ON {OrderItem}.[OrderId] = {Order}.[OrderId]<br>  LEFT JOIN {User} CreatedByUser ON CreatedByUser.[Id] = {Order}.[CreatedBy]<br>  LEFT JOIN {User} UpdatedByUser ON UpdatedByUser.[Id] = {Order}.[UpdatedBy]<br>  WHERE<br>      (@OrderDate_Start = @NullDate OR {Order}.[OrderDate] &gt;= @OrderDate_Start) AND<br>      (@OrderDate_End = @NullDate OR {Order}.[OrderDate] &lt;= @OrderDate_End)<br>  GROUP BY<br>      {Order}.[OrderId], {Order}.[OrderDate],<br>      {Order}.[CreatedOn], {Order}.[CreatedBy], CreatedByUser.[Name],<br>      {Order}.[UpdatedOn], {Order}.[UpdatedBy], UpdatedByUser.[Name]<br>),<br>COUNT_CTE AS<br>(<br>  SELECT COUNT(*) AS Count FROM BASE_CTE<br>)<br><br>SELECT * FROM BASE_CTE, COUNT_CTE<br>ORDER BY @SortField<br>OFFSET @StartIndex ROWS FETCH NEXT @MaxResults ROWS ONLY;</pre><p>As you can see, we are using common table expressions here. This way we can preselect all matching purchase orders with BASE_CTE on the database server so we can count the total number of matching records with COUNT_CTE.<br>I recommend using column aliases that match the attribute names in our return structure <em>Order_Result</em>. By doing so, a consumer of the service knows what column names to use for sorting in parameter <em>SortField</em>.<br>The joins should be self-explanatory. When joining with the same entity multiple times, like {User} in this example, I also use speaking aliases for better readability.<br>In the where clause we now need to filter for all of <em>SearchCriteria</em>. For this we use the so called conditional where clause pattern: Every search criterion is separated in parentheses, starting with the selective condition @OrderDate_Start = @NullDate, followed by an OR and the filter condition itself {Order}.[OrderDate] &gt;= @OrderDate_Start. So the selective condition controls if the filter condition is to be applied. The individual search criteria are linked with an AND, so they are subtractive.<br>The grouping includes all selected purchase order attributes and is necessary for the aggregation functions used to get the order items count and total amount.<br>The last three lines contain the final select statement that fetches the data to be filled into the output structures <em>Order_Result </em>and <em>TotalRows</em>. Where the first one is identical to the selected columns of BASE_CTE and the second one only contains one attribute for the total rows count selected in COUNT_CTE. The order by statement is where the dynamic sort comes into place and you can see, why it’s so important to sanitize the value of <em>SortField</em> to prevent SQL injections. The last line is handling the pagination of the result set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B9PICFCxmOZ09UiTGF2OPQ.png" /><figcaption>Server action Order_Search (part 2)</figcaption></figure><p>Of course, we need to pass in all the defined SQL parameters in the flow. In <em>SortField</em> we can directly use the sanitization of the forge component <em>EncodingSortForSQL</em> hence both parts are provided as functions: BuildSafe_SortClause(TextToSortAttributes(SortField, &quot;OrderDate,TotalAmount DESC&quot;)). The two parts are separated in the component to allow for manipulation of the sort attributes between <em>SortField </em>parsing and sanitization.</p><p>Finally we assign the fetched rows and the total count to the output parameters of the server action <em>Order_Search</em>.</p><h3>Presenting the results to the user</h3><p>In the last articles we already created a UI to view and edit a single purchase order. What was missing is the list of purchase orders to navigate to the detail screen <em>Order</em> implemented so far.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*79l9QYnDjR5FoLxJHwN_aw.png" /><figcaption>Required dependencies</figcaption></figure><p>So let’s begin by adding a dependency to the new <em>Order_Search</em> server action in <em>Order_CS</em>. The used structures will be selected automatically.</p><h4>A screen to show them all</h4><p>Next we create a new screen named <em>Orders</em> with the following local variables to control which purchase orders to display:</p><pre>/**<br> * @screen Orders<br> *<br> * @variable {Order_SearchCriteria} OrderSearchCriteria<br> * Criteria to search for orders<br> *<br> * @variable {Text} TableSort<br> * String with comma separated SQL sort attributes (e.g. &quot;CreatedOn DESC&quot;, &quot;OrderDate,TotalAmount DESC&quot;)<br> *<br> * @variable {Integer} StartIndex<br> * Index of the first result on the page<br> */</pre><p>If you have already implemented a paginated list view as shown in the If you have already implemented a paginated list view as shown in the OutSystems online courses, you may be missing a fourth variable that contains the number of records per page. Here I would like to demonstrate a different approach that allows the end user to select this value from a dropdown menu. To maintain the setting between screens, we store it in a client variable instead:</p><pre>/**<br> * @clientVariable {Integer} ResultsPerPage<br> * Max. number of results per page<br> * Default: 20<br> */</pre><p>To fetch the list of purchase orders on the screen we also need to add a data action with two output parameters:</p><pre>/**<br> * @dataAction GetOrders<br> * Fetches the list of purchase orders of the current page<br> * Fetch: At start<br> *<br> * @output {Order_Result List} OrderResults<br> * List of purchase orders<br> *<br> * @output {Integer} TotalCount<br> * Total number of results<br> */</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*xFN0LbSb-wlsBqRp9zlT3Q.png" /><figcaption>Data action GetOrders</figcaption></figure><p>The action flow is pretty simple: First <em>Order_Search</em> from the core service is called with the corresponding input parameters and then the results are assigned to the output parameters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*al0UQBQdpSM1Seb-Ht29HA.png" /><figcaption>Screen Orders</figcaption></figure><p>The screen contains all necessary controls:</p><ul><li>the title,</li><li>a button to create a new order (by navigating to the existing <em>Order</em> screen with an empty <em>OrderId </em>parameter),</li><li>input fields for the search criteria (OrderSearchCriteria.OrderDate_Start and OrderSearchCriteria.OrderDate_End),</li><li>the table for the results (<em>GetOrders.OrderResults</em>) with a edit icon linked to the existing <em>Order </em>screen with the parameter <em>OrderId </em>set to GetOrders.OrderResults.Current.OrderId,</li><li>and a pagination widget called <em>PageNavigation</em>.</li></ul><h4>Navigate page by page</h4><p>As you can see, the pagination widget is a custom web block. Of course, we could simply use the <em>OutSystems UI</em> control <em>Navigation\Pagination</em>, but this is lacking of the option to choose the number of results per page. So I created a wrapper here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*Axoi35PuW_g_Jq-g4VPNqw.png" /><figcaption>Custom pagination widget UI</figcaption></figure><pre>/**<br> * @webblock PageNavigation<br> * Wrapper of Navigation\Pagination extended by a dropdown to select the<br> * number of results per page<br> *<br> * @input {Integer} StartIndex<br> * Set the initial index to start pagination.<br> *<br> * @input {Integer} TotalCount<br> * Total records of list.<br> *<br> * @variable {Integer List} ResultsPerPageOptions<br> * Options in the dropdown list<br> */</pre><p>Everything is wrapped in an outer container with <em>Style Class</em> display-flex containing a container with <em>Style Class</em> flex1 for the <em>Navigation\Pagination</em> control of the <em>OutSystems UI</em> and a <em>Popover Menu</em> to mimic the dropdown. To align this one with the standard pagination control we add the <em>Style Class</em>es popover margin-top-m margin-right-s. The popover control has two placeholders: <em>Top Content</em> is always visible and can be clicked to open the menu, and <em>Bottom Content</em> holds the menu items. As top content we add a container with <em>Style Class</em> pagination-button padding-x-s full-width containing an expression with Value set to Client.ResultsPerPage and a caret-down icon. The options in bottom content are dynamically generated with a <em>List </em>bound to ResultsPerPageOptions containing a <em>Link</em> with <em>Style Class</em> display-block text-neutral-9, the <em>On Click</em> event handler ResultsPerPageOnClick and an expression bound to ResultsPerPageOptions.Current.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*EBBZCfVMr7g-XXSaa_YWOA.png" /><figcaption>Custom pagination widget logic</figcaption></figure><p>The logic of <em>ResultsPerPageOnClick</em> updates the client variable with the clicked option: Client.ResultsPerPage = ResultrsPerPageOptions.Current. After this the <em>OnNavigate</em> event ist raised with <em>NewStartIndex</em> set to <em>0</em>. To close the popout menu finally a short javascript is called, that simply triggers a click on the body:</p><pre>document.body.click();</pre><p>So where are the options in the local variable <em>ResultsPerPageOptions </em>coming from? Those need to be initialized in the <em>OnInitialize </em>handler of the block. Here the OutSystems built-in action <em>ListAppendAll </em>is very handy to append several options at once.</p><h4>Wire everything up</h4><p>Back to our new screen <em>Orders</em>, we need to wire everything up with some client actions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*dyENE-4pHSnf5mA3nfnMfg.png" /><figcaption>Client actions of the Orders screen</figcaption></figure><ul><li><em>OnInitialize</em><br>handles the screens initialization event and sets the default filter configuration: OrderSearchCriteria.OrderDate_Start = AddMonths(CurrDate(),-1) and OrderSearchCriteria.OrderDate_End = NullDate().</li><li><em>Refresh</em><br>updates the list of fetched orders. I normally implement this wrapper as sometimes more than one data action need to be refreshed.</li><li><em>OnFilter</em><br>is a handler to react to changed filter criteria and in our sample handles the <em>OnChange </em>events of the two filter inputs. It sets <em>StartIndex </em>to <em>0</em> before calling <em>Refresh</em> so the pagination is reset to the first new results.</li><li><em>PaginationOnNavigate</em><br>works the same as the standard handler built by OutSystems scaffolding. It sets StartIndex = NewStartIndex and refreshes the data.</li><li><em>OnSort</em><br>also follows the standard scaffolded implementation to set or invert the sort order in <em>TableSort</em>, reset the pagination and refresh the data.</li></ul><p>That’s it! We can now publish the application.</p><p>You can download the complete application from the OutSystems Forge:</p><p><a href="https://www.outsystems.com/forge/component-overview/17064/master-detail-data-in-outsystems-demo">Master-Detail data in OutSystems (Demo)</a></p><p>I would be pleased if you follow me on medium and leave some claps and/or a coffee 😉. In case you have any questions left open or have tips for me to improve, please contact me via medium or my <a href="https://www.outsystems.com/profile/enrntqhemy/">OutSystems profile</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87d5273325b3" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/make-data-searchable-in-outsystems-87d5273325b3">Make data searchable in OutSystems</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Master-Detail data in OutSystems (2) UI]]></title>
            <link>https://itnext.io/master-detail-data-in-outsystems-2-ui-a8331a585f4d?source=rss-15f59cd3d285------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8331a585f4d</guid>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[master-detail]]></category>
            <category><![CDATA[outsystems]]></category>
            <category><![CDATA[low-code]]></category>
            <category><![CDATA[popups]]></category>
            <dc:creator><![CDATA[Sebastian Krempel]]></dc:creator>
            <pubDate>Fri, 08 Sep 2023 08:25:21 GMT</pubDate>
            <atom:updated>2023-09-08T08:38:50.654Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 2 of 2: Sample implementation of the UI with popup pattern</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TiMJi4jF8eTkjXc8PeC6IA.png" /></figure><p>In lots of my OutSystems projects I came across master-detail data structures. In this two-parted article, we’ll explore an efficient approach to manage master-detail data structures in OutSystems projects.<br>In part one we already created the core service to handle purchase orders and their related order items. In this second part, we’ll delve into designing the user interface and introducing a pattern for editing sub items (here: order items) via a popup dialog.</p><h3>What you need</h3><p>If you want to follow up the implementation on your own, you need:</p><ul><li>An OutSystems account (a <a href="https://www.outsystems.com/free-edition/">free personal environment</a> is sufficient)</li><li>OutSystems Service Studio</li><li>The sample core service implemented in part one:</li></ul><p><a href="https://medium.com/@sebastian-krempel/master-detail-data-in-outsystems-1-cs-869b0777f8ee">Master-Detail data in OutSystems (1) CS</a></p><p>This tutorial is also suitable for OutSystems newcomers. However, a little prior experience in using the Service Studio is useful.</p><h3>Introduction</h3><h4>Understanding the challenge</h4><p>In part one of this article, we dug into the intricacies of master-detail structures and how they often come with unique consistency requirements. These requirements can present challenges when dealing with detail records (child elements) that are intricately linked to their master records (parent elements). In the realm of user interface (UI) design, an essential question arises: how can we create child elements if the parent element doesn’t exist within the core service, yet? This issue becomes particularly pertinent when dealing with compositions, where the core service must ensure the absence of “empty” parent elements, such as purchase orders without associated order items. To address this challenge, in part one, we have already implemented a core service that exclusively provides access to purchase orders along with their associated order items as a cohesive composition.</p><h4>Designing the user interface</h4><p>Our primary objective is to craft a user-friendly screen that seamlessly presents a single purchase order, complete with its header information and a tabular representation of all associated order items. This interface should empower users to perform a range of actions with ease, including:</p><ul><li>Modifying the order date.</li><li>Adding new order items via a dedicated “Add” button.</li><li>Editing existing order items through an intuitive pencil icon.</li><li>Removing order items via a distinct icon.</li></ul><p>Importantly, all these changes should remain pending until the user explicitly clicks a “Save order” button. Additionally, we aim to streamline the process of creating new orders directly through the same screen.</p><p>To realize this vision, I have conceptualized the following layout, complemented by a popup dialog for entering or editing order items:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OIn-QdaQAkuc6oEJnqRoug.png" /><figcaption>Final screen layout of the demo app</figcaption></figure><h3>Implementation</h3><h4>Creating the basic detail screen</h4><p>Our journey begins with the foundation of a Reactive Web App template, to which we add a dependency on the core service <em>Order_CS</em> introduced in the preceding part of this article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oejYsswmjKf0uSq1FdfB-g.png" /><figcaption>Adding dependency and the order detail screen</figcaption></figure><p>To construct the detail screen, let’s follow these steps:</p><ul><li>Generate a new blank screen, naming it <em>Order</em>. This screen will serve as the canvas for displaying and manipulating purchase order details.</li><li>Add an optional input parameter called <em>OrderId</em> of type <em>Order Identifier</em>. This parameter will facilitate passing the order’s ID to the screen for displaying existing orders or leaving it blank to create new ones.</li><li>Add a boolean local variable named <em>IsSaving</em>. This variable will be used to animate the save button during the saving process, providing a visual cue to the user.</li><li>Create a data fetch action named <em>GetOrder</em> responsible for loading the specific purchase order. Change its output parameter <em>Out1</em> to <em>OrderDetails</em> and set the data type to <em>Order_Detail</em>.</li><li>Last add a client action named <em>SaveOnClick</em> to handle user interactions with the “Save” button. This action will trigger the saving process for the entire purchase order by invoking the relevant server actions. To facilitate this, we’ll need a local variable named <em>OrderSaveItems</em>, structured as a list of type <em>Order_Save_Item</em>.</li></ul><p>Certainly, let’s proceed with adding the essential UI components to our detail screen while ensuring proper integration with OutSystems integrated validation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0dZf4l70wCBcItA0JwwBJw.png" /><figcaption>Adding UI components for basic functionality</figcaption></figure><ul><li>Begin by adding a form element called <em>Form_Order</em>. This form must encompass all the relevant input controls and the “Save” button for the built-in validation to work properly.</li><li>Adding the text input for the order date and the table of order items is straight forward. Just bind the parameter <em>Variable </em>of the text input to GetOrder.OrderDetails.OrderDate and the <em>Source </em>of the table to GetOrder.OrderDetails.OrderItems.</li><li>The expressions in the table cells can be bound to the respective attributes of GetOrder.OrderDetails.OrderItems.Current.</li><li>Following the table, insert a container with the <em>Style Class</em> set to &quot;margin-top-base display-flex align-items-flex-end&quot;. This container will serve as a visually appealing section for the “Save” button and display of relevant information such as when the purchase order was created and last updated.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/909/1*vzvvLFNRYbACgKH0tDq5bg.png" /><figcaption>Save button configuration and client action to format created and updated info</figcaption></figure><ul><li>For the “Save” button, we’ll enhance its functionality by adding the <em>ButtonLoading</em> control instead of a normal <em>Button</em>. The property <em>IsLoading</em> is to be bound to the local variable <em>IsSaving</em>.</li><li>To prevent users from clicking the button multiple times, we want to disable the button within the <em>ButtonLoading </em>control while saving is in progress by binding its <em>Enabled </em>property to not IsSaving.</li><li>Assign the <em>SaveOnClick</em> action, which we previously created, as the <em>On Click</em> event handler for the “Save” button.</li><li>Regarding the display of created and last updated information, we implement a client action on the <em>Logic</em> tab with <em>Function</em> set to <em>Yes</em> and assigning the following expression to the output parameter <em>Result</em>:</li></ul><pre>If(CreatedOn &lt;&gt; NullDate(),<br>  &quot;Created &quot; + FormatDateTime(CreatedOn,&quot;dd.MM.yyyy HH:mm&quot;) + &quot; by &quot; +<br>  If(CreatedByName = &quot;&quot;, &quot;[Deleted user &quot; + CreatedBy + &quot;]&quot;, CreatedByName) + NewLine() +<br>  &quot;Last updated &quot; + FormatDateTime(UpdatedOn,&quot;dd.MM.yyyy HH:mm&quot;) + &quot; by &quot; +<br>  If(UpdatedByName = &quot;&quot;, &quot;[Deleted user &quot; + UpdatedBy + &quot;]&quot;, UpdatedByName)<br>, &quot;&quot;)</pre><ul><li>This new client-side function can then be used in the expression component on the screen.</li></ul><h4>Adding a popup dialog to manipulate order items</h4><p>As outlined in the introduction, we want to enable the user to add and change order items through a popup dialog. For controlling this popup we need various local variables and client actions. Here I want to share a slim tried-and-tested solution pattern, refined through my prior project experiences:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*tM3R-W_DnqPpGSd7Jphyig.png" /><figcaption>Local variables and actions for order items</figcaption></figure><ul><li><em>OrderItemPopup_Data<br></em>This variable stores the data of the currently opened order item in the popup dialog, utilizing the structure <em>Order_Save_Item</em>.</li></ul><blockquote><em>💡 TIP<br></em>In cases where you need to display item data that cannot be manipulated and, therefore, is not part of the _Save structure, consider reusing the _Detail structure instead. However, keep in mind that you’ll need to assign all relevant data to the respective attributes when opening the popup and update dependent data if changes occur in the popup inputs.</blockquote><ul><li><em>OrderItemPopup_Index<br></em>Holds the index of the currently opened order item (-1 for new items to be created).</li><li><em>OrderItemPopup_Show<br></em>Is a boolean variable that controls the visibility of the popup dialog.</li></ul><p>While we will implement the following actions in detail later, it’s beneficial to create them in advance for a clear code structure and allows us to directly assign them on creation of the related UI components:</p><ul><li><em>OrderItem_DeleteOnClick<br></em>Is responsible for removing order items on the client side.</li><li><em>OrderItemPopup_SaveOnClick<br></em>This action handles the click event of the &quot;Save&quot; button within the popup dialog and manages the writing back of entered data.</li><li><em>OrderItemPopup_Show<br></em>Acts as a helper method to initialize and control the popup dialog. It accepts two input parameters: <em>Show </em>to determine whether to display or hide the popup and an optional parameter <em>Index</em> for specifying which order item to open.</li></ul><p>By structuring and naming your solution in this manner, you’ll establish a clear and organized framework for handling order items and the related popup dialog.</p><p>Next, we have to add the UI components for the popup dialog as well. For the sake of efficient validation, the popup contains a separate own form. In OutSystems, forms cannot be nested, so it’s crucial to place the <em>Popup Dialog </em>component in <em>MainContent </em>after and not into <em>Form_Order</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*ESE5UrsEOn5RIQYKH7z1Jg.png" /><figcaption>Adding UI components for order item popup dialog</figcaption></figure><p>The popup UI consists of two essential components:</p><ul><li><em>OrderItemPopup_Title<br></em>This dynamic element features an expression If(OrderItemPopup_Index = -1, &quot;New order item&quot;, &quot;Edit order item&quot;) to display a title text and a link element to close the popup by calling <em>OrderItemPopup_Show </em>with the parameter <em>Show </em>being set to <em>False</em>.</li><li><em>Form_OrderItem<br></em>allows users to manipulate the currently open order item.</li></ul><p>To ensure an organized layout, the various input fields of the form are placed within containers. Their size and floating are simply controlled by adjusting the <em>Width</em> property on the <em>Styles</em> tab, aligning with a suitable number of columns.</p><ul><li>For the data connection, the input fields are directly bound to the corresponding attributes of <em>OrderItemPopup_Data</em>.</li><li>To allow the user to commit changes made, there is a “Save” button placed in the last container. By setting <em>Is Form Default </em>to <em>Yes</em>, this button serves as the form’s default action. As you guess, the <em>On Click</em> event is send to <em>OrderItemPopup_SaveOnClick</em>. To ensure the <em>Built-in Validation</em> is utilized set it to <em>Yes</em>.</li><li>Additionally, a “Cancel” button is placed adjacent to the “Save” button, providing users with the option to discard changes. Similar to the close link in the popup title, clicking this button invokes <em>OrderItemPopup_Show</em> with the parameter <em>Show</em> being set to <em>False</em>. In this case, <em>Built-in Validation</em> is set to <em>No</em> allowing for a straightforward cancellation of actions without validation checks.</li></ul><p>To complete the UI, we need to add an additional column to the order items table. This new column houses a button and the icons for adding, editing, and removing order items.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mdQlEOaJWcrsFnOE1GWTMw.png" /><figcaption>Extend the UI table of order items</figcaption></figure><ul><li>In the new header cell, we place the button <em>Button_OrderItem_Add</em>. On click we simply call <em>OrderItemPopup_Show</em> with <em>Show </em>is <em>True </em>to display the popup dialog, <em>Index </em>is left blank so the default value -1 is used to indicate a new order item is to be created.</li><li>In the new row cell, we add the two icons, one for editing and one for removing the individual order item.</li><li>By right clicking the edit icon, we can link it to <em>OrderItemPopup_Show</em>. Obviously <em>Show</em> has to be <em>True </em>but this time also <em>Index </em>is filled with GetOrder.OrderDetails.OrderItems.CurrentRowNumber to open the popup dialog and load the current order item.</li><li>Finally, the delete icon is linked to <em>OrderItem_DeleteOnClick</em>.</li></ul><h4>Implementing the logic</h4><p>With all UI components in place, it’s now time to implement the corresponding logic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*x99hS2FciA2wxaYrgbkZTA.png" /><figcaption>Logic to load the purchase order, remove order items and show/hide the popup dialog</figcaption></figure><ul><li><em>GetOrder<br></em>The logic begins with this fetch action, responsible for loading the purchase order by calling <em>Order_GetOrder</em> of the core service. The fetched result is then assigned to the output parameter <em>OrderDetails</em>. However, to avoid unnecessary calls to the core service, the action is directly aborted if the screen input parameter <em>OrderId</em> is null.</li><li><em>OrderItem_DeleteOnClick<br></em>removes the current order item from the formerly fetched list GetOrder.OrderDetails.OrderItems by calling <em>ListRemove</em> for <em>Position </em>GetOrder.OrderDetails.OrderItems.CurrentRowNumber.</li></ul><p>The third action, <em>OrderItemPopup_Show</em> holds the magic for controlling the popup dialog and operates as follows:</p><ul><li>In the first switch branch, it checks whether the popup should be hidden or shown add a new order item. Specifically, it verifies not Show or Index = -1 and if the condition is met, all attributes of <em>OrderItemPopup_Data</em> are reset to their initial values.</li><li>In the second switch branch, the condition not GetOrder.OrderDetails.OrderItems.Empty and Index ≥ 0 and Index &lt; GetOrder.OrderDetails.OrderItems.Length is checked to verify, Index is in the list range of existing order items. If met, the popup data is initialized by assigning GetOrder.OrderDetails.OrderItems[Index] to <em>OrderItemPopup_Data</em>.</li><li>Finally, the action shows or hides the popup dialog by assigning the input parameters <em>Index</em> and <em>Show</em> to <em>OrderItemPopup_Index</em> and <em>OrderItemPopup_Show</em>.</li><li>In case none of the conditions are met, it means <em>Index </em>is out of bounds, and an error message is displayed.</li></ul><p>What’s now missing is handling clicks on the “Save”-buttons:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*92BTF7g9wuFXqe1q1fpTtQ.png" /><figcaption>Logic to handle the “Save”-buttons</figcaption></figure><p>Let’s beginn with the popup dialogs “Save”-button by implementing <em>OrderItemPopup_SaveOnClick</em>. To leverage OutSystems’ built-in validation, we follow best practices outlined in the <a href="https://success.outsystems.com/documentation/11/developing_an_application/design_ui/forms/validate_the_fields_of_a_form/#validate-the-data-in-a-client-action">documentation</a>. If the form is valid, we proceed as described in the following breakdown.</p><ul><li>By checking OrderItemPopup_Index &lt;&gt; -1 we determine whether we’re updating an existing order item or creating a new one.</li><li>To update an existing item, we first must recalculate the <em>TotalAmount </em>with the formular GetOrder.OrderDetails.TotalAmount - GetOrder.OrderDetails.OrderItems[OrderItemPopup_Index].Total + (OrderItemPopup_Data.Quantity * OrderItemPopup_Data.Amount) before we can assign the updated values in <em>OrderItemPopup_Data </em>to GetOrder.OrderDetails.OrderItems[OrderItemPopup_Index] .</li><li>On the other hand, for creating an order item we can simply append a new entry with the entered values in <em>OrderItemPopup_Data </em>to the list <em>GetOrder.OrderDetails.OrderItems</em> and afterwards recalculate the <em>TotalAmount </em>with the formular GetOrder.OrderDetails.TotalAmount + (OrderItemPopup_Data.Quantity * OrderItemPopup_Data.Amount) .</li><li>Following the update or addition of the item, we use <em>ListSort</em> to reorder the order item list accordingly.</li><li>The action concludes by hiding the popup with <em>OrderItemPopup_Show</em> passing in <em>False </em>for the <em>Show </em>parameter.</li></ul><p>The action <em>SaveOnClick</em> is the final piece of functionality to be implemented. The beauty of this pattern lies in its client-side nature, which ensures that no data changes are made on the server until the user actively saves their changes. Consequently, there’s no need for temporary data storage on the server, and no dependency issues arise.<br>This client-centric approach empowers users to freely manipulate the master and detail data without affecting the core service at all.</p><ul><li>It’s important to ensure entered data is valid before proceeding. Thus, the action begins with the validation of the <em>Form_Order</em>.</li><li>To disable the “Save” button and show its loading animation, we set the local screen variable <em>IsSaving</em> to <em>True </em>before the processing begins.</li><li>On the client side, all data is held in the <em>Order_Detail</em> structure and its sub-structure <em>Order_Detail_Item</em>. However, to persist changes using the core service, the data must be converted to <em>Order_Save</em> and <em>Order_Save_Item</em> structures. OutSystems handles automatic conversion between structures where possible, but manual mapping may be necessary. This is especially true for substructures of a list type.<br>This is the reason for assigning the list of order items to a temporary variable OrderSaveItems = GetOrder.OrderDetails.OrderItems in the flow element <em>Convert Detail~ to OrderSaveItems</em>.</li><li>Persisting the changes on the server side is invoked for an existing purchase order by calling <em>Order_UpdateOrder</em>, and for a new one by calling <em>Order_CreateOrder</em>. For new purchase orders, also the screen input parameter <em>OrderId</em> is updated with the newly created ID.</li><li>After saving is complete, <em>IsSaving</em> is reset to be <em>False</em>.</li><li>Finally, refreshing the fetch action <em>GetOrder</em> ensures the most recent data version is loaded again.</li></ul><p>With these steps, your demo application is ready to be published and tested. It follows a client-centric approach, ensuring that server data remains consistent and unchanged until the user explicitly saves their modifications, providing a seamless and efficient user experience.</p><p>Hopefully, I succeeded in presenting my pattern for loading and saving nested data structures along with the use of popup dialogs for those structures. I am delighted if you liked the article and if you can adapt the pattern to your own applications. Happy coding with OutSystems!</p><p>I would be pleased if you follow me on medium and leave some claps and/or a coffee 😉. In case you have any questions left open or have tips for me to improve, please contact me via medium or my <a href="https://www.outsystems.com/profile/enrntqhemy/">OutSystems profile</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8331a585f4d" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/master-detail-data-in-outsystems-2-ui-a8331a585f4d">Master-Detail data in OutSystems (2) UI</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Master-Detail data in OutSystems (1) CS]]></title>
            <link>https://itnext.io/master-detail-data-in-outsystems-1-cs-869b0777f8ee?source=rss-15f59cd3d285------2</link>
            <guid isPermaLink="false">https://medium.com/p/869b0777f8ee</guid>
            <category><![CDATA[low-code]]></category>
            <category><![CDATA[master-detail]]></category>
            <category><![CDATA[outsystems]]></category>
            <category><![CDATA[core-service]]></category>
            <dc:creator><![CDATA[Sebastian Krempel]]></dc:creator>
            <pubDate>Mon, 04 Sep 2023 18:16:08 GMT</pubDate>
            <atom:updated>2023-10-17T16:01:48.030Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 1 of 2: Sample implementation of the core service</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bGbEegX35-Rw9trBoYeuIw.png" /></figure><p>In lots of my OutSystems projects I came across master-detail data structures. In this two-parted article, we’ll explore an efficient approach to manage master-detail data structures in OutSystems projects.<br>As a sample app, we’ll create a core service to handle purchase orders and their related order items. Part one of this article will focus on setting up the core service, while part two will delve into designing the user interface and introducing a pattern for editing sub items (here: order items) via a popup dialog.</p><h3>What you need</h3><p>To follow along with this implementation, you’ll need:</p><ul><li>An OutSystems account (a <a href="https://www.outsystems.com/free-edition/">free personal environment</a> is sufficient).</li><li>OutSystems Service Studio.</li></ul><p>This tutorial is also suitable for OutSystems newcomers. However, a little prior experience in using the Service Studio is useful.</p><h3>Introduction</h3><h4>Understanding the challenge</h4><p>In OutSystems projects, dealing with relational data models is a common task. A quite frequent structure is aggregations or compositions in particular. These lead to master-detail structures like for example purchase orders with associated order items. Here often consistency requirements come into place. E.g. when creating new data records in the database, detail records (child elements) can only be created after the identifier of the master record (parent element) is known.</p><h4>Designing the core service</h4><p>The primary objective of a core service is to store data related to a specific core concept. Depending on the project’s complexity, it may be advisable to create a business logic module atop the core service to implement more intricate business rules or orchestrate data access that spans multiple core services. For the purpose of this article, we’ll use a simple order core service, named <em>Order_CS</em>, to demonstrate the pattern. This core service can later be directly accessed by consumers, such as the user interface we’ll construct in part two of this article.</p><h3>Database</h3><p>In OutSystems, the most straightforward method to store data is by utilizing the platform’s built-in relational database. When dealing with master-detail structures, such as a purchase order and its associated order items, you can model this relationship with a simple one-to-many relationship in the database. For our purposes, we need two entities:</p><ul><li><em>Order</em><br>This entity represents the purchase order itself and contains essential header information like the order date.</li><li><em>OrderItem</em><br>Use this entity to store the corresponding order items, linked to the <em>OrderId</em>.</li></ul><p>In a real-world application, you would likely include additional attributes and establish relationships with other entities, such as products. However, for this sample app, the simplified model described above should suffice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*jKiluvG6-kl0UT_EYCGZ_w.png" /><figcaption>Entity relationship model of the demo app</figcaption></figure><pre>/**<br> * @entity Order<br> * Purchase order<br> * Public: No<br> *<br> * @attribute {Text} OrderId<br> * Id of the purchase order<br> * Length: 36<br> *<br> * @attribute {Date} OrderDate<br> * Date of the purchase order<br> *<br> * @attribute {Date Time} CreatedOn<br> * Timestamp of creation<br> *<br> * @attribute {User Identifier} CreatedBy<br> * User who created the record<br> * Delete Rule: Ignore<br> *<br> * @attribute {Date Time} UpdatedOn<br> * Timestamp of last update<br> *<br> * @attribute {User Identifier} UpdatedBy<br> * User who last updated the record<br> * Delete Rule: Ignore<br> */<br><br>/**<br> * @entity OrderItem<br> * Item of a purchase order<br> * Public: No<br> *<br> * @attribute {Text} OrderItemId<br> * Id of the order item<br> * Length: 36<br> *<br> * @attribute {Order Identifier} OrderId<br> * Order the item belongs to<br> * Delete Rule: Delete<br> *<br> * @attribute {Integer} Number<br> * Order item number<br> *<br> * @attribute {Text} Description<br> * Description of the order item<br> * Length: 50<br> *<br> * @attribute {Integer} Quantity<br> * Ordered quantity of order item<br> *<br> * @attribute {Currency} Amount<br> * Amount of order item per unit<br> *<br> * @index UX_OrderId_Number<br> * Number must be unique per purchase order<br> * Unique: Yes<br> * Attributes: OrderId, Number<br> */</pre><p>In the code block below, you’ll find specific database configurations:</p><ul><li>Data type for identifiers:<br>Both <em>OrderId </em>and <em>OrderItemId </em>use a <em>Text </em>data type with a length of 36. This choice aligns with the use of GUIDs as identifiers.</li><li>Delete rule for external relations:<br>The delete rule for attributes <em>CreatedBy </em>and <em>UpdatedBy </em>is set to <em>Ignore</em>. This decision is made because the data type <em>User Identifier</em> generates a foreign key constraint to the system entity <em>User</em>. Other options like <em>Delete</em> or <em>Protect</em> would pose problems when attempting to delete frontend accounts in the user provider. Broken references possibly caused through <em>Ignore</em>, on the other hand, can be handled within the own application.</li><li>Delete rule for fully dependent, internal relations:<br>For the attribute <em>OrderId </em>in the <em>OrderItem </em>entity, the delete rule is intentionally set to <em>Delete</em>. This setting ensures that all order items associated with a purchase order are automatically deleted when the purchase order is deleted, as they cannot exist independently.</li><li>Additional unique index:<br>The index <em>UX_OrderId_Number</em>, visibly denoted as unique with the prefix <em>UX</em>, enforces that each order item number can only appear once within the same purchase order. It ensures uniqueness and data integrity.</li></ul><h3>Public interface of the core service</h3><p>You may have noticed that the entities in our configuration are not set as public. It’s a common practice to expose entities publicly, often in a read-only mode. This approach offers the advantage of controlled data writing through actions within the core service, while still permitting free usage in other modules for selection purposes, such as in joins.</p><p>However, for our demo application, we’re taking a different approach. We aim to provide read access to the data only in a controlled manner. This means that external modules will have limited access to the data, ensuring that it’s handled and manipulated as intended.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eOJIfLEpl5k-tvHFWQueDw.png" /><figcaption>Public server actions and structures of the core service</figcaption></figure><h4>Server actions (CRUD operations)</h4><p>In our implementation, you’ll find public server actions that cover all fundamental CRUD (Create, Read, Update, Delete) operations for purchase orders. These actions, tailored to their respective functions, expect or provide input/output parameters structured as <em>OrderId</em>, <em>Order_Detail</em>, and <em>Order_Save</em>.</p><p>Typically, public exposed actions would include an authorization check as the first step. For the sake of simplicity, this article omits that step.</p><blockquote><em>💡 TIP</em><br>To enhance clarity and workflow within your application, consider using custom icons for public actions. This makes it easier to distinguish them from private actions and locate them within the flow of other modules.</blockquote><h4>Detail structure (Order_Detail)</h4><p>The <em>Order_Detail</em> structure defines the detailed information of a single purchase order. It is designed to be retrieved by other modules using the core service. This structure allows for a clear representation of the purchase order’s details, facilitating its utilization within your application.</p><pre>/**<br> * @structure Order_Detail<br> * Details of a purchase order<br> * Public: Yes<br> *<br> * @attribute {Order Identifier} OrderId<br> * Id of the purchase order<br> *<br> * @attribute {Date} OrderDate<br> * Date of the purchase order<br> *<br> * @attribute {Currency} TotalAmount<br> * Total amount of all order items<br> *<br> * @attribute {Order_Detail_Item List} [OrderItems]<br> * Items of the purchase order<br> *<br> * @attribute {Date Time} CreatedOn<br> * Timestamp of creation<br> *<br> * @attribute {User Identifier} CreatedBy<br> * User who created the record<br> *<br> * @attribute {Text} [CreatedByName]<br> * Name of user who created the record<br> *<br> * @attribute {Date Time} UpdatedOn<br> * Timestamp of last update<br> *<br> * @attribute {User Identifier} UpdatedBy<br> * User who last updated the record<br> *<br> * @attribute {Text} [UpdatedByName]<br> * Name of user who last updated the record<br> */<br><br>/**<br> * @structure Order_Detail_Item<br> * Order item details of a purchase order<br> * Public: Yes<br> *<br> * @attribute {OrderItem Identifier} OrderItemId<br> * Id of the order item<br> *<br> * @attribute {Integer} Number<br> * Order item number<br> *<br> * @attribute {Text} Description<br> * Description of the order item<br> *<br> * @attribute {Integer} Quantity<br> * Ordered quantity of order item<br> *<br> * @attribute {Currency} Amount<br> * Amount of order item per unit<br> *<br> * @attribute {Currency} Total<br> * Total amount of the order item<br> */<br></pre><p>The <em>_Detail</em> structure, as a general pattern, offers some advantages for managing data objects and their associated sub items:</p><ul><li>Nested structure:<br>One standout feature is the inclusion of order items as a nested structure within the <em>Order_Detail</em>. This design allows you to request the entire purchase order, including its items, in a single query to the core service. Consequently, there’s no need for additional requests, enhancing efficiency.</li><li>Elimination of redundant foreign keys:<br>Due to the nesting of <em>Order_Detail_Item</em>, the foreign key <em>OrderId </em>is not required at the sub item level. This reduces redundancy and simplifies the structure.</li><li>Structured naming convention:<br>To maintain clarity in the Service Studio, I recommend prefixing nested structures with the parent structure’s name. This naming convention aids in quickly identifying and organizing structures, especially as they are listed alphabetically. It also helps prevent confusion with other structures that might represent the same child object independently of the particular parent structure.</li><li>Enhanced convenience:<br>To improve the user experience and assist consumers of the core service, we’ve incorporated calculated attributes (e.g. totals) and lookup information (e.g. names of users who created and last updated the record) within the structure. These additions enhance the usability and usefulness of the <em>Order_Detail </em>structure.</li></ul><h4>Save structure (Order_Save)</h4><p>In a manner similar to the detail structure used for data retrieval, the <em>Order_Save</em> structure encompasses all attributes of a single purchase order that can be modified from outside of the core service. This structure is designed to ensure a comprehensive representation of writable attributes for efficient data management while facilitating the same advantages as the previously described <em>_Detail</em> structure.</p><pre>/**<br> * @structure Order_Save<br> * Details of a purchase order to be saved<br> * Public: Yes<br> *<br> * @attribute {Date} OrderDate<br> * Date of the purchase order<br> *<br> * @attribute {Order_Save_Item List} [OrderItems]<br> * Items of the purchase order<br> */<br><br>/**<br> * @structure Order_Save_Item<br> * Order item details of a purchase order to be saved<br> * Public: Yes<br> *<br> * @attribute {OrderItem Identifier} OrderItemId<br> * Id of the order item (Null for new items)<br> *<br> * @attribute {Integer} Number<br> * Order item number<br> *<br> * @attribute {Text} Description<br> * Description of the order item<br> *<br> * @attribute {Integer} Quantity<br> * Ordered quantity of order item<br> *<br> * @attribute {Currency} Amount<br> * Amount of order item per unit<br> */</pre><h3>Private server actions</h3><p>As depicted in the figure above, the flows of the public server actions are relatively straightforward. The actual heavy lifting occurs through the invocation of two non-public server actions: <em>Order_Load</em> and <em>Order_Save</em>. In this section, we will delve into these essential components.</p><blockquote><em>💡 TIP</em><br>Employing dedicated server actions for loading and saving orders not only streamlines the code but also enhances maintainability. This separation minimizes redundancy and ensures consistent functionality.</blockquote><h4>Load data (Order_Load)</h4><p>The <em>Order_Load </em>server action serves the purpose of retrieving a specific purchase order from the database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*bxqTWZGbAHUIGpsv0IVEFw.png" /><figcaption>Server action Order_Load</figcaption></figure><ul><li>The action begins by checking if OrderId &lt;&gt; NullTextIdentifier(). This ensures that in absence of the <em>OrderId</em> required to proceed with the data retrieval, an empty (initial) <em>Order_Detail </em>structure is returned. If desired, default values for the attributes of new orders could also be set here.</li><li>The Data is selected using an aggregate that filters records by the given <em>OrderId </em>and joins with the order items from the <em>OrderItem </em>entity. Although we enforce not allowing purchase orders without order items, the join type <em>With or Without</em> is selected to ensure that orders can still be loaded if this rule is neglected.</li><li>Two joins are made with the <em>User </em>entity, once for <em>CreatedBy </em>and once for <em>UpdatedBy</em>. This enables the retrieval of users’ names associated. The <em>Ignore</em> delete rule is set for these two foreign keys to avoid issues with deletion attempts in the user provider. Consequently, the join type <em>With or Without</em> must be selected to avoid excluding purchase orders created or last modified by users who may have been deleted in the meantime. It’s worth noting the assignment of speaking aliases for the user entity, which simplifies later assignments of values.</li><li>If the purchase order is found, the flow continues. Otherwise, a <em>NotFoundException </em>is thrown to handle situations where the requested purchase order does not exist.</li><li>Regarding the attribute <em>OrderItems </em>in <em>Order_Detail</em>, it is intentionally not set to be mandatory. This design choice allows the flexibility to leave the value empty initially in the assign <em>OrderDetail</em> and then easily append items in a subsequent loop.</li><li>The final assignment in the loop calculates the <em>TotalAmount </em>for the purchase order using an expression:</li></ul><pre>OrderDetail.TotalAmount = OrderDetail.TotalAmount + (<br>  GetOrderWithItemsByOrderId.List.Current.OrderItem.Quantity *<br>  GetOrderWithItemsByOrderId.List.Current.OrderItem.Amount<br>)</pre><h4>Save data (Order_Save)</h4><p>The primary objective of the <em>Order_Save </em>server action is to persist the changes specified within the <em>OrderSave </em>input parameter. This process entails validation, comparison with the current state (optional parameter <em>OrderDetail</em>), and ultimately, updating the database. The entire flow is segmented into three distinct processing blocks for clarity and comprehensibility.</p><p><strong>Processing block 1: Data validation<br></strong>The initial block focuses on the validation of the data contained in the <em>OrderSave </em>parameter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*5dONu_I48N_SE6vUyjcPrQ.png" /><figcaption>Server action Order_Save (part 1/3: Validation)</figcaption></figure><p>In OutSystems, data validation can efficiently be achieved using the <em>Switch </em>element to evaluate all possible invalid values and throw a <em>ValidationException</em>. When none of these checks match, the flow proceeds through the <em>Otherwise </em>branch.</p><ul><li><em>no order date</em><br>The system checks if OrderSave.OrderDate = NullDate() to determine if there’s no order date specified.</li><li><em>no order items<br></em>Validation checks whether OrderSave.OrderItems.Empty is true, indicating that there are no order items provided.</li></ul><p>Within the loop, each order item intended for saving undergoes thorough validation:</p><ul><li><em>number duplicate</em><br>Validation is carried out by examining if ListAnySameNumber.Result is true, which utilizes the expression Value = OrderSave.OrderItems.Current.Number to identify a match in the local variable <em>OrderItemNumbers </em>of type <em>Integer List</em>. This variable is employed to keep track of numbers already in use. Successful validation appends all numbers from validated order items to this list using <em>ListAppendOrderItemNumber</em>.</li><li><em>no description</em><br>The system checks if Trim(OrderSave.OrderItems.Current.Description) = &quot;&quot;, verifying the presence of a description for each order item.</li></ul><p><strong>Processing block 2: Creating or Updating purchase order<br></strong>Within the second block of the <em>Order_Save</em> server action, the system determines whether to create a new purchase order or update an existing one, based on the condition OrderDetail.OrderId = NullTextIdentifier().</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*jCfyySvSVnuo-6QAUdTk7w.png" /><figcaption>Server action Order_Save (part 2/3: Create or update order)</figcaption></figure><ul><li>In the case of an update operation, the server action calls <em>GetOrderForUpdate</em>. This function serves to set a database lock specifically for the affected <em>Order </em>record. The lock’s purpose is to prevent concurrent writes to the same purchase order, ensuring data consistency.</li><li>The assign step <em>Update Attributes </em>is responsible for only overwriting values that require modification and leaves all other attributes of the entity unchanged. This selective approach avoids data loss when the <em>UpdateOrder </em>action writes the changes back to the database.</li><li>Before both branches of the operation converge in the next processing block, the system performs the essential task of assigning the newly created or recently updated order identifier to the <em>OrderId</em> output parameter. This step ensures that following steps reference the correct purchase order and the caller receives the identifier as part of the server action’s output.</li></ul><p><strong>Processing block 3: Synchronization of order items<br></strong>Within the final block of the <em>Order_Save </em>server action, a series of steps are executed to handle order items. These steps involve iterating through the current order items in <em>OrderDetail </em>(representing the loaded database state, which may be empty for new purchase orders) and searching for corresponding items in <em>OrderSave </em>(representing the state to be saved). The related database actions taken to synchronize are contingent on the comparison results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*clqtKe2pMf5somdfdWiaLQ.png" /><figcaption>Server action Order_Save (part 3/3: Sync order items)</figcaption></figure><p>The process initiates by iterating through all current order items in <em>OrderDetail</em>. This step is essential to examine the existing state of order items:</p><ul><li><em>not found</em><br>The system checks if the same <em>OrderItemId </em>is not present in <em>OrderSave</em> anymore (determined by ListIndexOfOrderSaveItem.Position = -1). If no match is found, this implies that the item should be deleted from the database, leading to the invocation of <em>DeleteOrderItem</em>.</li><li><em>not modified<br></em>If the state of the order item in <em>OrderSave </em>is identical to its counterpart in <em>OrderDetail</em> (according to the following expression), it signifies that no modifications have been made. In this case, the order item is removed from <em>OrderSave</em> to suppress further actions for this item.</li></ul><pre>OrderDetail.OrderItems.Current.Number =<br>  OrderSave.OrderItems[ListIndexOfOrderSaveItem.Position].Number and<br>OrderDetail.OrderItems.Current.Description =<br>  OrderSave.OrderItems[ListIndexOfOrderSaveItem.Position].Description and<br>OrderDetail.OrderItems.Current.Quantity =<br>  OrderSave.OrderItems[ListIndexOfOrderSaveItem.Position].Quantity and<br>OrderDetail.OrderItems.Current.Amount =<br>  OrderSave.OrderItems[ListIndexOfOrderSaveItem.Position].Amount</pre><ul><li><em>Otherwise<br></em>If this branch is reached, <em>UpdateOrderItem</em> is invoked to ensure that the modifications detected are accurately reflected in the database. The order item is also removed from <em>OrderSave </em>here as no further save action is required for this item.</li></ul><p>Subsequently, the server action proceeds to loop through the remaining order items in <em>OrderSave</em>. These are items that were not present in the loaded database state but need to be created. For each of these items, the action <em>CreateOrderItem </em>is invoked to facilitate their creation in the database.</p><p>The next part of this article concentrates on the UI implementation and how to efficiently realize a popup dialog to edit order items:</p><p><a href="https://itnext.io/master-detail-data-in-outsystems-2-ui-a8331a585f4d">Master-Detail data in OutSystems (2) UI</a></p><p>I hope the article was to your liking and would be pleased if you follow me on medium and leave some claps and/or a coffee 😉. In case you have any questions left open or have tips for me to improve, please contact me via medium or my <a href="https://www.outsystems.com/profile/enrntqhemy/">OutSystems profile</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=869b0777f8ee" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/master-detail-data-in-outsystems-1-cs-869b0777f8ee">Master-Detail data in OutSystems (1) CS</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Best practice: Integration Services in OutSystems]]></title>
            <link>https://itnext.io/best-practice-integration-services-in-outsystems-6469d1b85ffb?source=rss-15f59cd3d285------2</link>
            <guid isPermaLink="false">https://medium.com/p/6469d1b85ffb</guid>
            <category><![CDATA[integration-services]]></category>
            <category><![CDATA[geojson]]></category>
            <category><![CDATA[what3words]]></category>
            <category><![CDATA[outsystems]]></category>
            <category><![CDATA[low-code]]></category>
            <dc:creator><![CDATA[Sebastian Krempel]]></dc:creator>
            <pubDate>Wed, 05 Apr 2023 09:17:11 GMT</pubDate>
            <atom:updated>2023-04-05T10:13:51.418Z</atom:updated>
            <content:encoded><![CDATA[<h4>Sample based on what3words API</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*py39D20bzqcTrI5J2sRlXQ.png" /></figure><p>I recently published the first <a href="https://www.outsystems.com/forge/component-overview/14823/aleph-alpha-connector">OutSystems forge component to integrate with the Aleph Alpha Public API</a> and considered writing a guide on how to implement integration services for REST APIs. However, due to the API’s size and complexity, I opted to showcase another public API instead. Have you heard of what3words? It’s a solution for communicating precise locations worldwide using human-friendly three-word addresses, rather than GPS coordinates. what3words has divided the earth’s surface into three-by-three-meter squares, each with a unique three-word address. Using their app or API, you can easily convert coordinates to these three words and vice versa.</p><p><a href="https://what3words.com/">The simplest way to talk about location</a></p><h3>Summary</h3><p>This tutorial will guide you through the best practices for integrating a REST API in OutSystems, including</p><ul><li>consuming the API through a driver module and</li><li>implementing a reusable integration service.</li></ul><p>If you’re only interested in obtaining the component, you can scroll to the end of the article for a shortcut.</p><h3>What you need</h3><p>If you want to follow up the implementation on your own, you need:</p><ul><li>An OutSystems account (a <a href="https://www.outsystems.com/free-edition/">free personal environment</a> is sufficient)</li><li>OutSystems Service Studio</li><li>what3words account and API key (will be created in this tutorial)</li></ul><p>For this tutorial you should already have some experience in building applications with OutSystems.</p><h3>Register for your what3words API key</h3><p>Before utilizing what3words’ API, you will need to register for an account and generate an API key:</p><ul><li>Go to <a href="https://developer.what3words.com/">https://developer.what3words.com/</a> and click the button <em>Get an API Key.</em></li><li>Choose the plan of your liking (free plan is sufficient for this tutorial).</li><li>Sign up or log in via your preferred method.</li><li>Accept the terms and conditions.</li><li>Optionally type in your company and industry information.</li><li>In step <em>Create an API Key</em> fill in a name (e.g. <em>OutSystems Connector</em>) and a brief description of your project and click <em>Generate API Key</em>.</li></ul><p>It’s also possible to limit the usage of your API key, but for the purposes of this tutorial, you can leave the checkbox <em>Add API Key restriction</em> unchecked.</p><h3>Architecture</h3><p>OutSystems simplifies the process of consuming REST APIs, even directly in your UI module. However, this can result in multiple integrations of the same API, which can make code maintenance difficult. To address this, it’s recommended to encapsulate the API integration in a dedicated integration service, which can be utilized by various OutSystems applications in your environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*h9UGwL23GqGO-qKDsO81ZQ.png" /></figure><p>The integration architecture consists of two module types:</p><ul><li>Integration Service<br>provides the integrated functionality to your environment and can be seen as the facade towards applications.</li><li>Driver<br>is the interface to the consumed external service and connects to its provided API endpoints.</li></ul><p>The purpose of this division into two parts is to decouple between both sides. So only minimal adjustments are required when changes occur. You do not want to change all applications in your environment when the external service changes an API endpoint or releases a new version.</p><h3>Create the service application</h3><p>To begin, create a new application called <em>what3words Connector</em>. Since this will only include our new integration service and doesn’t have its own UI, we select <em>Service</em> as the application type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x9KhSpt-zJWqf7f1WDzgEA.png" /></figure><p>After clicking on <em>Create App</em>, OutSystems opens the new application and asks for the first module to be created.</p><h3>Implementing the driver module</h3><p>Let’s begin with creating the driver module. Following OutSystems’ naming convention, we name the module <em>what3words_DRV</em>. The suffix <em>_DRV</em> is denoting its functional role as a driver. We keep the preselected <em>Service</em> option in the module type dropdown and click <em>Create Module</em>.</p><p>Of course, the main functionality of the API is the two conversion endpoints. As you will see later in this tutorial, they are a little bit special. Thats why I decided to start with the easiest endpoint:</p><h4>First simple endpoint: Available languages</h4><p>This endpoint returns a list of all available languages used for valid three-word addresses.</p><ul><li>On the <em>Logic</em> tab in Service Studio open the <em>Integrations</em> folder.</li><li>Right click on <em>REST</em> and click on <em>Consume REST API…</em></li></ul><p>In the opening dialog, you have the option to add a single method or multiple methods. The second option is only applicable if you have a Swagger definition of the endpoint(s) you wish to consume. For this tutorial, we choose the first option to demonstrate all steps in detail.</p><ul><li>Select <em>Add single method</em> and click on <em>Continue.</em></li></ul><p>In the next dialog we need to configure the REST call to be made. It is always a clever idea to inspect the API documentation first. For what3words you can find the documentation here:</p><p><a href="https://developer.what3words.com/public-api/docs#overview">API Reference Docs | what3words</a></p><p>The most important setting are the HTTP verb and the URL of the endpoint to be consumed.</p><pre>HTTP Method: GET<br>URL: https://api.what3words.com/v3/available-languages</pre><ul><li>Leave the HTTP method unchanged and copy and paste the endpoint&#39;s URL to the dialog.</li></ul><p>As you can see from the API docs sample, we must pass the API key to authenticate. The sample shows passing it as a parameter <em>key</em> in the URL but what3words also offers to pass it in a custom header. To demonstrate how data can be sent in header variables, we will use this option here.</p><ul><li>Switch to the <em>Headers and Authentication</em> tab and enter the request header <em>X-Api-Key</em>.</li></ul><p>To get the response structure for the REST method, we can copy and paste the result JSON from the API documentation. Alternatively, we can switch to the <em>Test </em>tab of the dialog, fill in the API key in the X-<em>Api-Key </em>parameter, and click the <em>Test </em>button. This will invoke the request and show the result. If successful, we can apply the result by clicking <em>Copy to response body</em>.</p><p>Regardless of the method we choose, it’s important that the response body field contains the JSON structure with sample data. Here I omitted most of the languages to save you from scrolling. If all returned fields and values of the respective data types are present, OutSystems can determine the required structures.</p><pre>{<br>  &quot;languages&quot;: [<br>    {<br>      &quot;nativeName&quot;: &quot;Deutsch&quot;,<br>      &quot;code&quot;: &quot;de&quot;,<br>      &quot;name&quot;: &quot;German&quot;<br>    },<br>    {<br>      &quot;nativeName&quot;: &quot;हिन्दी&quot;,<br>      &quot;code&quot;: &quot;hi&quot;,<br>      &quot;name&quot;: &quot;Hindi&quot;<br>    }<br>  ]<br>}</pre><p>To generate the REST consumer action, click <em>Finish</em> and let’s see what has been generated so far:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*tsEbqOmz3LyB8TOdx_6-Nw.png" /></figure><p>As you can see, there now is a new REST integration called <em>What3words </em>with one action <em>GetAvailablelanguages </em>to invoke the GET request. On <em>Data</em> tab you find a <em>What3words</em> item with structures generated for the response.</p><p>The API key is used for authentication and thus should be treated like a password. As the request is made over HTTPS the key is encrypted in transport, but we should change a setting in the <em>Logic</em> tab:</p><ul><li>Go to the input parameter <em>XApiKey</em> and change <em>Log Reduction</em> to <em>Yes</em>. This will hide the key from the log.</li></ul><p>I personally recommend filling in descriptions for the REST action and its parameters as well as for the generated structures and their attributes. Normally I just copy the respective texts from the official API docs.</p><p>I also rename the REST action in Pascal case for better readability and move the HTTP verb to the end. In our case <em>GetAvailablelanguages</em> becomes <em>AvailableLanguages_Get</em>. This will group all actions invoking the same endpoint with different HTTP verbs (GET, POST, PUT, etc.). The structures I rename the following way, which I will explain later in this article.</p><pre>/**<br> * @structure What3words_AvailableLanguages_GetResponse<br> * Response of available languages endpoints<br> *<br> * @attribute {What3words_Language List} [Languages]<br> * List of available languages<br> */<br><br>/**<br> * @structure What3words_Language<br> * Available language<br> *<br> * @attribute {Text} [NativeName]<br> * Native name<br> *<br> * @attribute {Text} [Code]<br> * ISO 3166-1 alpha-2 2 letter code<br> *<br> * @attribute {Text} [Name]<br> * Name<br> */</pre><h4>Using URL parameters: Conversion endpoints</h4><p>Everything was simple so far, wasn’t it? Next, we will implement the two conversion endpoints for converting three-word addresses to coordinates and vice versa.</p><ul><li>As the <em>What3words </em>integration is already present in our module, we can now add additional methods by simply right clicking it on the <em>Logic </em>tab and select <em>Add REST API Method…</em> from the context menu.</li><li>For the dialog just follow the same steps we did for the first endpoint.</li></ul><p>As you can see in the API documentation, both conversion endpoints await some URL parameters. We can use placeholders for this in OutSystems by simply replacing the value parts in the URL by the name of the parameter we later want to use in OutSystems, enclosed in curly brackets:</p><pre># Convert to three-word address<br>HTTP Method: GET<br>URL: https://api.what3words.com/v3/convert-to-3wa?coordinates={Coordinates}&amp;language={Language}&amp;format={Format}<br><br># Convert to coordinates<br>HTTP Method: GET<br>URL: https://api.what3words.com/v3/convert-to-coordinates?words={Words}&amp;format={Format}</pre><p>As we saw while adding the first endpoint, OutSystems helps us with the automatic creation of the respective response structures if we provide sample response data. So, let’s make use of this assistance and copy the response of the <em>json</em> format:</p><pre>{<br>  &quot;country&quot;: &quot;GB&quot;,<br>  &quot;square&quot;: {<br>    &quot;southwest&quot;: {<br>      &quot;lng&quot;: -0.195543,<br>      &quot;lat&quot;: 51.520833<br>    },<br>    &quot;northeast&quot;: {<br>      &quot;lng&quot;: -0.195499,<br>      &quot;lat&quot;: 51.52086<br>    }<br>  },<br>  &quot;nearestPlace&quot;: &quot;Bayswater, London&quot;,<br>  &quot;coordinates&quot;: {<br>    &quot;lng&quot;: -0.195521,<br>    &quot;lat&quot;: 51.520847<br>  },<br>  &quot;words&quot;: &quot;filled.count.soap&quot;,<br>  &quot;language&quot;: &quot;en&quot;,<br>  &quot;map&quot;: &quot;https://w3w.co/filled.count.soap&quot;<br>}</pre><p>Once you have completed the dialog for both methods, also rename the REST methods accordingly:</p><ul><li>Rename <em>GetConverttocoordinates</em> to <em>ConvertToCoordinates_Get</em> and</li><li><em>GetConvertto3wa</em> to <em>ConvertToThreeWordAddress_Get</em>.</li></ul><p>For the generated structures, you will notice that the ones already present are reused. This is because OutSystems attempts to reuse structures if they match, and sometimes even extends them. If you do not want to reuse them, you can manually copy structures and modify the data types of the REST action parameters as needed.</p><h4>Structures of the REST integration</h4><p>In our case, we know that the API returns the same response structure for both conversion endpoints. Therefore, it is reasonable to rename the structures and provide descriptions as well. In addition, meaningful names help with later assignment and prevent naming conflicts with other structures that we still need to implement further below.</p><p>While implementing the first endpoint <em>/available-languages</em> I renamed the structures in a special manner, and promised to explain my personal naming preferences:</p><ul><li>All structures of the integration are prefixed with the integration’s name and an underscore to generate a unique namespace for them.</li><li>Structures for the request or response body (root level only) are named analog to the REST methods using them followed by <em>Response</em> or <em>Request</em>.</li><li>Structures for nested data objects are named by the name of the object. If a nested data object has differing endpoint or request/response specific representations, the specific method’s name or <em>Response</em>/<em>Request</em> is also part of the prefix.</li><li>When names would otherwise become too long, middle parts can be omitted or abbreviated, while trying to remain a most senseful sorting order.</li></ul><p>For our example this results in the following <em>What3words</em> structures:</p><pre>/**<br> * @structure What3words_Convert_GetResponse<br> * Response of conversion endpoints<br> *<br> * @attribute {Text} [Country]<br> * Uppercase ISO 3166-1 alpha-2 country code<br> *<br> * @attribute {What3words_Square} [Square]<br> * Square coordinates<br> *<br> * @attribute {Text} [NearestPlace]<br> * Nearest place (e.g. city)<br> *<br> * @attribute {What3words_Coordinates} [Coordinates]<br> * Coordinates<br> *<br> * @attribute {Text} [Words]<br> * Three-word-address<br> *<br> * @attribute {Text} [Language] = &quot;hidden&quot;<br> * ISO 639-1 2 letter code of the 3 word address language<br> *<br> * @attribute {Text} [Map]<br> * Link to the address on the what3words website<br> */<br><br>/**<br> * @structure What3words_Coordinates<br> * Coordinates<br> *<br> * @attribute {Decimal} [Lng]<br> * Longitude<br> *<br> * @attribute {Decimal} [Lat]<br> * Latitude<br> */<br><br>/**<br> * @structure What3words_Square<br> * Square coordinates<br> *<br> * @attribute {What3words_Coordinates} [Southwest]<br> * Southwest coordinates of the square<br> *<br> * @attribute {What3words_Coordinates} [Northeast]<br> * Northeast coordinates of the square<br> */</pre><h4>Dynamic response structures: Conversion endpoints</h4><p>So far so good, were it not for the viable alternative response format <em>geojson</em>, which does not fit into the now generated structure. So how can we handle this?</p><p>For our integration we want to have the default format <em>json</em> parsed into the already generated structure for easy consumption. But the second format might also become handy to receive for applicable use cases that expect the <em>geojson</em> as text. To allow for both use cases, we need to make some adjustments:</p><ul><li>Go to the <em>Logic </em>tab and select both conversion REST actions.</li><li>In the properties area change the <em>Response Format</em> from <em>JSON </em>to <em>Plain Text</em>.</li><li>Change the <em>Data Type</em> of the Response parameters from <em>What3words_Convert_GetResponse</em> to <em>Text</em>.</li></ul><p>This will make the former assigned response structures obsolete but please just keep them for now, as we will need them later.</p><p>The what3words API provides some more endpoints, but for this tutorial we concentrate on the three already added methods only.</p><h4>Public objects for the integration service</h4><p>All objects implemented so far are private, so they are only available within the driver module. Since they are fully dependent on the API and we do not want to pass this dependency on to the integration service, we now need to write corresponding public wrappers that can be used by the <em>what3words_IS</em> module. In addition, errors can occur when calling the API, which we must handle accordingly.</p><h4>Structures of the driver module</h4><p>Of course, this also requires structures for transferring the data. The driver is only an abstraction between the integration service and the API endpoints. So, the public structure should not differ from the private ones already existent. Thus, for now, we can simply copy them and make them public. Here we benefit from already having named and filled in descriptions, since these are now kept when copying.</p><p>You will see, that OutSystems is appending a number 2 at the end of all structure names. This is why I rename the public structures by removing the integration’s name prefix and the number at the end:</p><pre>/**<br> * @structure AvailableLanguages_GetResponse<br> * Response of available languages endpoints<br> *<br> * @attribute {Language List} [Languages]<br> * List of available languages<br> */<br><br>/**<br> * @structure Language<br> * Available language<br> *<br> * @attribute {Text} [NativeName]<br> * Native name<br> *<br> * @attribute {Text} [Code]<br> * ISO 3166-1 alpha-2 2 letter code<br> *<br> * @attribute {Text} [Name]<br> * Name<br> */<br><br>/**<br> * @structure Convert_GetResponse<br> * Response of conversion endpoints<br> *<br> * @attribute {Text} [Country]<br> * Uppercase ISO 3166-1 alpha-2 country code<br> *<br> * @attribute {Square} [Square]<br> * Square coordinates<br> *<br> * @attribute {Text} [NearestPlace]<br> * Nearest place (e.g. city)<br> *<br> * @attribute {Coordinates} [Coordinates]<br> * Coordinates<br> *<br> * @attribute {Text} [Words]<br> * Three-word-address<br> *<br> * @attribute {Text} [Language] = &quot;hidden&quot;<br> * ISO 639-1 2 letter code of the 3 word address language<br> *<br> * @attribute {Text} [Map]<br> * Link to the address on the what3words website<br> */<br><br>/**<br> * @structure Coordinates<br> * Coordinates<br> *<br> * @attribute {Decimal} [Lng]<br> * Longitude<br> *<br> * @attribute {Decimal} [Lat]<br> * Latitude<br> */<br><br>/**<br> * @structure Square<br> * Square coordinates<br> *<br> * @attribute {Coordinates} [Southwest]<br> * Southwest coordinates of the square<br> *<br> * @attribute {Coordinates} [Northeast]<br> * Northeast coordinates of the square<br> */</pre><p>For each REST method we now implement a public server action that wraps the call to the API.</p><ul><li>The name is equal to the called REST method, but prefixed with the integration’s name and API version, separated by an underscore.</li></ul><p>The simplest way to support both response formats of the conversion methods is to expose separate server actions for <em>json </em>(output as structure) and <em>geojson</em> (output as text). For the <em>geojson</em> variant just append <em>GeoJson</em> to the action’s name.</p><p>Afterwards, we need to add all input and output parameters. While you can simply copy and paste them from the REST method, it is important to ensure:</p><ul><li>The <em>Mandatory</em> property of all required input parameters is set to <em>Yes.</em></li><li>The <em>Data Type</em> of all parameters is changed to the according public structures.</li></ul><p>You should end up with the following five server actions:</p><pre>/**<br> * @action What3words_v3_AvailableLanguages_Get<br> * Retrieves a list of all available 3 word address languages, including<br> * the ISO 3166-1 alpha-2 2 letter code, english name and native name.<br> *<br> * @input {Text} XApiKey<br> * A valid API key<br> *<br> * @output {AvailableLanguages_GetResponse} Response<br> * Response of available languages endpoints<br> */<br><br>/**<br> * @action What3words_v3_ConvertToCoordinates_Get<br> * This function converts a 3 word address to a latitude and longitude.<br> * It also returns country, the bounds of the grid square, a nearest place<br> * (such as a local town) and a link to our map site.<br> *<br> * @input {Text} XApiKey<br> * A valid API key<br> *<br> * @input {Text} Words<br> * A 3 word address as a string. It must be three words separated with dots<br> * or a japanese middle dot character (・). Words separated by spaces will<br> * be rejected. Optionally, the 3 word address can be prefixed with ///<br> * (which would be encoded as %2F%2F%2F)<br> *<br> * @output {Convert_GetResponse} Response<br> * Result of conversion endpoints<br> */<br><br>/**<br> * @action What3words_v3_ConvertToCoordinates_GetGeoJson<br> * This function converts a 3 word address to a latitude and longitude.<br> * It also returns country, the bounds of the grid square, a nearest place<br> * (such as a local town) and a link to our map site.<br> *<br> * @input {Text} XApiKey<br> * A valid API key<br> *<br> * @input {Text} Words<br> * A 3 word address as a string. It must be three words separated with dots<br> * or a japanese middle dot character (・). Words separated by spaces will<br> * be rejected. Optionally, the 3 word address can be prefixed with ///<br> * (which would be encoded as %2F%2F%2F)<br> *<br> * @output {Text} Response<br> * GeoJSON<br> */<br><br>/**<br> * @action What3words_v3_ConvertToThreeWordAddress_Get<br> * This function will convert a latitude and longitude to a 3 word address,<br> * in the language of your choice. It also returns country, the bounds of<br> * the grid square, a nearby place (such as a local town) and a link to our<br> * map site.<br> *<br> * @input {Text} XApiKey<br> * A valid API key<br> *<br> * @input {Text} Coordinates<br> * Coordinates as a comma separated string of latitude and longitude<br> *<br> * @input {Text} [Language]<br> * A supported 3 word address language as an ISO 639-1 2 letter code.<br> * Defaults to en (english). For a full list of 3 word address languages,<br> * see available-languages.<br> *<br> * @output {Convert_GetResponse} Response<br> * Result of conversion endpoints<br> */<br><br>/**<br> * @action What3words_v3_ConvertToThreeWordAddress_GetGeoJson<br> * This function will convert a latitude and longitude to a 3 word address,<br> * in the language of your choice. It also returns country, the bounds of<br> * the grid square, a nearby place (such as a local town) and a link to our<br> * map site.<br> *<br> * @input {Text} XApiKey<br> * A valid API key<br> *<br> * @input {Text} Coordinates<br> * Coordinates as a comma separated string of latitude and longitude<br> *<br> * @input {Text} [Language]<br> * A supported 3 word address language as an ISO 639-1 2 letter code.<br> * Defaults to en (english). For a full list of 3 word address languages,<br> * see available-languages.<br> *<br> * @output {Text} Response<br> * GeoJSON<br> */</pre><p>Now it is time to implement the logic flow. For all actions:</p><ul><li>Simply drag the respective REST method from the <em>Logic </em>tab to your flow.</li><li>Fill in all its parameters by mapping them to the corresponding input parameters.</li></ul><p>For <em>What3words_v3_AvailableLanguages_Get</em> and both <em>_GetGeoJson</em> actions:</p><ul><li>Add an assign element beneath and assign the REST action’s <em>Response</em> to the output parameter <em>Response</em>.</li></ul><p>For both other conversion actions we need to parse the response ourselves:</p><ul><li>To do this, add a <em>JSON Deserialize</em> node and pass in the REST action’s <em>Response</em> as <em>JSON String</em> and select <em>Convert_GetResponse</em> as <em>Data Type</em>.</li><li>Add an assign element beneath and assign <em>JSONDeserializeConvert_GetResponse.Data</em> to the output parameter <em>Response</em>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*gLBxVR5-4h7HTDsbwYOI4Q.png" /></figure><h4>Error handling</h4><p>The last missing feature of our driver module is error handling. There are a lot of things that can go wrong when calling the API, for example the API will return:</p><ul><li>HTTP 401 when the API key is missing or invalid</li><li>HTTP 400 when the request was bad (e.g. missing a required parameter)</li><li>HTTP 50x when an internal server error occurs</li></ul><p>So, let’s begin with implementing an exception that can be thrown when an error occurs. On <em>Logic </em>tab scroll to the end, unfold <em>Exceptions </em>and <em>All Exceptions</em> and right click <em>User Exception</em> to <em>Add User Exception</em>. Name the new exception <em>ApiException</em>.</p><p>According to the API documentation, it provides some JSON-formatted details on the error in the response body as well:</p><pre>{<br>  &quot;error&quot;: {<br>      &quot;code&quot;: &quot;BadWords&quot;,<br>      &quot;message&quot;: &quot;Invalid or non-existent 3 word address&quot;<br>  }<br>}</pre><p>To parse this, we create two new structures called <em>ErrorResponse </em>and <em>Error </em>with the following attributes. You can quickly create new structures in OutSystems from a sample JSON and afterwards adjust them:</p><ul><li>Right click on the <em>Structures</em> folder on <em>Data</em> tab and select <em>Add Structure from JSON…</em></li><li>Copy and paste the sample error response JSON.</li><li>Adjust naming and add descriptions:</li></ul><pre>/**<br> * @structure ErrorResponse<br> * API response in case of an error<br> *<br> * @attribute {Error} [Error]<br> * Error details<br> */<br><br>/**<br> * @structure Error<br> * Error details<br> *<br> * @attribute {Integer} [StatusCode]<br> * The HTTP status code received from the API.<br> *<br> * @attribute {Text} [StatusLine]<br> * The name of the HTTP status code received from the API.<br> *<br> * @attribute {Text} [Code]<br> * Parsed error code received from the API.<br> *<br> * @attribute {Text} [Message]<br> * Parsed error message received from the API.<br> */</pre><p><em>ErrorResponse</em> will only be used inside the driver and can stay non-public. <em>Error</em> is also used to pass error details to the integration service, so we need to make it public.</p><p>To parse the error response body, we implement the additional server action named <em>TryAndParseApiError</em>.</p><ul><li>Add an input parameter <em>TextToParse </em>of type <em>Text</em>.</li><li>Add an output parameter <em>Error </em>of type <em>Error</em>.</li><li>Add a <em>JSON Deseralize</em> item to the flow and name it <em>DeserializeError</em>.</li><li>Pass the input parameter <em>TextToParse </em>to the <em>JSON String</em> property and select <em>ErrorResponse </em>as <em>Data Type</em>.</li><li>Add an <em>Assign </em>item beneath and assign <em>DeserializeError.Data.Error</em> to the output parameter <em>Error</em>.</li></ul><p>If an error occurs during parsing, we simply return the <em>TextToParse </em>as <em>Error.Message</em>. Don’t forget to change the <em>Abort Transaction</em> property of the <em>AllExceptions </em>handler to <em>No</em>. Otherwise, we would abort transactions of a consumer app which might not be intended.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Ly9BdID3NrACnJARJ1Zqw.png" /></figure><p>To catch the error when needed, we have to react to the <em>OnAfterResponse </em>event of the REST integration. To add this event handler</p><ul><li>navigate to the <em>What3words</em> integration,</li><li>open the dropdown <em>On After Response</em>,</li><li>and select <em>New OnAfterResponse</em>.</li></ul><p>This will create a new action where we can check for the HTTP response status code and try to parse the error details in the response body:</p><ul><li>Add an <em>If</em> item with condition <em>CustomizedResponse.StatusCode &gt;= 400</em>.</li><li>Move the <em>False </em>branch with the <em>End</em> item to the right, as the event handler can return when no error occurred.</li><li>Drag the action <em>TryAndParseApiError </em>to the <em>True </em>branch and pass <em>Response.ResponseText</em> to the <em>TextToParse </em>parameter.</li><li>Assign <em>Response.StatusCode</em> and <em>Response.StatusLine</em> to the corresponding attributes of <em>TryAndParseApiError.Error</em>.</li><li>Finally, JSON-serialize the error and throw a new <em>ApiException </em>with the serialized error as <em>Exception Message</em>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D4u0JTrcDKDsp9wYzcjr_Q.png" /></figure><p>Now that we will get an <em>ApiException </em>whenever a REST endpoint of <em>What3words </em>returns with a HTTP error, we must also catch this exception in our wrapping server actions. For this we need another helper action to parse the error details in the <em>ApiException</em>:</p><ul><li>Add an input parameter <em>TextToParse </em>of type <em>Text</em>.</li><li>Add an output parameter <em>Error </em>of type <em>Error</em>.</li><li>Add a <em>JSON Deseralize</em> item to the flow and name it <em>DeserializeError</em>.</li><li>Pass the input parameter <em>TextToParse </em>to the <em>JSON String</em> property and select <em>Error </em>as the <em>Data Type</em>.</li><li>Add an <em>Assign </em>item beneath and assign <em>DeserializeError.Data</em> to the output parameter <em>Error</em>.</li></ul><p>As in <em>TryParseApiError</em> catch all exceptions (without aborting the transaction) and return the <em>TextToParse </em>as <em>Error.Message</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6svLj9nsRgre1Cv8MacdSA.png" /></figure><p>Now we can extend all public server actions with the following exception handler flow:</p><ul><li>Add two output parameters: <em>IsSuccess </em>of type <em>Boolean, </em>and <em>Error </em>of type <em>Error </em>to the action.</li><li>Add an <em>ApiException </em>handler to the flow and don’t forget to change the <em>Abort Transaction</em> property to <em>No</em>.</li><li>Drag the <em>TryParseError </em>server action to the flow and pass <em>ApiException.ExceptionMessage</em> as <em>TextToParse</em>.</li><li>Assign <em>IsSuccess</em> = <em>False </em>and <em>Error </em>= <em>TryAndParseError.Error</em> and end the event handler flow.</li><li>Don’t forget to add <em>IsSuccess</em> = <em>True </em>as an assignment in item <em>Response </em>of the main flow.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YAhVOoSb4uchh6_LqKAdTg.png" /></figure><p>Everything is implemented for the driver now. Before we publish the module, we should remove all unused dependencies by clicking <em>Remove Unused Dependencies</em> in the <em>Module </em>menu.</p><h3>Implementing the integration service</h3><p>Now that the driver module is complete, we can implement the integration service. So, go to the application overview in Service Studio and add a new module named <em>what3words_IS</em> of type <em>Service</em>. The integration service uses the driver to call the what3words API, so we need to add dependencies to the public actions of our driver. The structures are selected automatically:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*FATEfYanRVXS4ut9MLdFoQ.png" /></figure><h4>Structures of the integration service</h4><p>Do you remember the architectural idea behind the separation between driver and integration service? We want to achieve decoupling of the external service and other applications in our environment. Therefore, it makes sense to create all data structures that should be used by consumers of the integration service again in the <em>what3words_IS</em> module. This will prevent later dependencies of consuming apps on the driver module.</p><p>To ease our work, we can copy and paste the structures again and then adjust them:</p><ul><li>I prefer to prefix the structures’ names with the integration’s name. This will become handy in consuming apps as it creates a namespace for the integration and reduces naming conflicts.</li><li>To abstract the external functionality, I modify names to be more general, without representing every technical detail only relevant to the driver. Additionally, the integration service may convert data and structures to be consumed by other developers more easily. However, I take care not to completely detach from the external service’s API, so the interface remains comprehensible.</li><li>OutSystems automatically exchanges data types of nested structures if you copy and paste them all at once. Nevertheless, you should double check none of the driver’s structures are referenced in the new structures.</li></ul><pre>/**<br> * @structure What3words_Conversion<br> * Result of a conversion from coordinates to 3-word-address and vice versa<br> *<br> * @attribute {Text} [Country]<br> * Uppercase ISO 3166-1 alpha-2 country code<br> *<br> * @attribute {What3words_Square} [Square]<br> * Square coordinates<br> *<br> * @attribute {Text} [NearestPlace]<br> * Nearest place (e.g. city)<br> *<br> * @attribute {What3words_Coordinates} [Coordinates]<br> * Coordinates<br> *<br> * @attribute {Text} [Words]<br> * Three-word-address<br> *<br> * @attribute {Text} [Language]<br> * ISO 639-1 2 letter code of the 3-word-address language<br> *<br> * @attribute {Text} [Map]<br> * Link to the address on the what3words website<br> */<br><br>/**<br> * @structure What3words_Coordinates<br> * Coordinates<br> *<br> * @attribute {Decimal} [Lng]<br> * Longitude<br> *<br> * @attribute {Decimal} [Lat]<br> * Latitude<br> */<br><br>/**<br> * @structure What3words_Error<br> * Error details<br> *<br> * @attribute {Integer} [StatusCode]<br> * The HTTP status code received from the API.<br> *<br> * @attribute {Text} [StatusLine]<br> * The name of the HTTP status code received from the API.<br> *<br> * @attribute {Text} [Code]<br> * Parsed error code received from the API.<br> *<br> * @attribute {Text} [Message]<br> * Parsed error message received from the API.<br> */<br><br>/**<br> * @structure What3words_Language<br> * Available language<br> *<br> * @attribute {Text} [NativeName]<br> * Native name<br> *<br> * @attribute {Text} [Code]<br> * ISO 3166-1 alpha-2 2 letter code<br> *<br> * @attribute {Text} [Name]<br> * Name<br> */<br><br>/**<br> * @structure What3words_Square<br> * Square coordinates<br> *<br> * @attribute {What3words_Coordinates} [Southwest]<br> * Southwest coordinates of the square<br> *<br> * @attribute {What3words_Coordinates} [Northeast]<br> * Northeast coordinates of the square<br> */</pre><h3>Service actions of the integration service</h3><p>As for structures, the same applies to server actions. To achieve the targeted decoupling, the integration service provides its own public actions for consuming apps.</p><ul><li>Same as with structures, I create a namespace for the integration by prefixing the actions’ names with the integration’s name.</li><li>For all input and output parameters we use the <em>What3words_*</em> structures we recently created, of course.</li></ul><p>As part of the abstraction process, I also implement some conversions in the IS module to make the integration consumable more easily. The function for converting coordinates to a three-word address, for example, expects a comma-separated string on the API side, although coordinates are returned in a structure with attributes for latitude and longitude. So, we can reuse this for input parameters as well. To demonstrate this, let’s</p><ul><li>implement the input parameter <em>Coordinates </em>with type <em>What3words_Coordinates </em>and convert the value accordingly before passing it to the driver.</li><li>Of course, we change the <em>Mandatory </em>property of <em>Lat </em>and <em>Lng </em>to <em>Yes</em>.</li></ul><p>When assigning the output structures, OutSystems automatically tries to map all attributes based on their names and datatypes. For nested structures this does not always work:</p><ul><li>In simple cases, you can select the proper attribute (e.g. <em>Coordinates.Lng</em> = <em>Coordinates.Lng</em>) from the dropdown.</li><li>If the nested attribute is a structure itself, you must assign it in a separate assignment (e.g. <em>Response.Square.Southwest</em> = <em>What3words_v3_ConvertToCoordinates_Get.Response.Square.Southwest</em>).</li><li>Nested lists sometimes require you to loop through and append items separately to a local variable that can afterwards be assigned to the output structure.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1x2eH5wuRCL1Zb6CYxEBww.png" /></figure><p>Congrats, you have made it through! Don’t forget to clean up the dependencies and publish.</p><h3>Get the ready-to-use component from the forge</h3><p>I published the <a href="https://www.outsystems.com/forge/component-overview/14957/what3words-connector">what3words Connector</a> including all API methods (except speech recognition) in the OutSystems Forge. This also comes with a small demo app so you can try out things and directly use it in your own apps. I would be happy if you leave a like in the forge.</p><p>I hope the article was interesting for you and would be pleased if you follow me on medium and leave some claps and/or a coffee 😉. In case you have any questions left open or have tips for me to improve, please contact me via medium or my <a href="https://www.outsystems.com/profile/enrntqhemy/">OutSystems profile</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6469d1b85ffb" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/best-practice-integration-services-in-outsystems-6469d1b85ffb">Best practice: Integration Services in OutSystems</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Panning and zooming images in OutSystems]]></title>
            <link>https://itnext.io/panning-and-zooming-images-in-outsystems-29fefed6a4fb?source=rss-15f59cd3d285------2</link>
            <guid isPermaLink="false">https://medium.com/p/29fefed6a4fb</guid>
            <category><![CDATA[low-code]]></category>
            <category><![CDATA[ui-component]]></category>
            <category><![CDATA[panzoom]]></category>
            <category><![CDATA[outsystems]]></category>
            <dc:creator><![CDATA[Sebastian Krempel]]></dc:creator>
            <pubDate>Tue, 13 Dec 2022 11:28:09 GMT</pubDate>
            <atom:updated>2023-10-16T16:52:42.109Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to integrate a JavaScript component as reusable widget</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hDW4j-uH8pg0kAQHpht-NQ.png" /></figure><p>For one of my projects, I needed a widget that allows panning and zooming around in a large image. In this short tutorial, I want to share with you how I implemented it based on the wonderful panzoom component by Timmy Willison.</p><h3>Summary</h3><p>What you will learn in this tutorial:</p><ul><li>How to integrate an external JavaScript component</li><li>How to implement a reusable widget</li><li>How to use it in a simple demo app</li></ul><p>If you just need the component, you can take the shortcut and scroll to the end of this article.</p><h3>What you need</h3><p>If you want to follow up the implementation on your own, you need:</p><ul><li>An OutSystems account (a <a href="https://www.outsystems.com/free-edition/">free personal environment</a> is sufficient)</li><li>OutSystems Service Studio</li><li><a href="https://timmywil.com/panzoom/">JavaScript panzoom library</a> by Timmy Willison (licensed under MIT)</li></ul><p>For this tutorial you should already have some experience in building reactive web applications with OutSystems.</p><p>Because we aim for a reusable component, I decided to split the project into two separate OutSystems modules: the widget itself and a demo app to test it.</p><h3>Build a reusable widget</h3><h4>Get the panzoom JavaScript library</h4><p>Timmy Willison has built a nice JavaScript component, which utilizes CSS transforms to allow a performant way of panning and zooming things around a webpage. You can play around with his demos and learn more about it on his <a href="https://timmywil.com/panzoom/">homepage</a>. All sources are available unter MIT license on GitHub:</p><p><a href="https://github.com/timmywil/panzoom">GitHub - timmywil/panzoom: A library for panning and zooming elements using CSS transforms</a></p><p>You can find several options to build the sources there. For our OutSystems component we only need the compiled JavaScript which can be loaded from a cdn:</p><p><a href="https://unpkg.com/@panzoom/panzoom@4.5.1/dist/panzoom.min.js">https://unpkg.com/@panzoom/panzoom@4.5.1/dist/panzoom.min.js</a></p><p>As I want to have the component independent from cdns for varied reasons, I grab the minified version from the cdn link and import it into the OutSystems module.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vUy1xOArxviblvsA0HoPMQ.png" /><figcaption>Adding the panzoom JavaScript</figcaption></figure><h4>Create the reusable web block</h4><p>Next, we must integrate the JavaScript as a reusable ui component. In OutSystems this is done with (web) blocks that, like screens, live in a ui flow. By default, your module contains a flow named <em>MainFlow</em>. I recommend renaming it to the same name as your widget module, so later you can easily find all blocks of your module in projects that use it.</p><p>Let’s rename the ui flow and add a new block <em>Panzoom</em> to it. As we want to use this web block from other modules, we need to set its attribute <em>Public</em> to <em>Yes</em>. Because it depends on the panzoom JavaScript we also need to append <em>Scripts.Panzoom</em> to the required scripts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*Y9mU20tWfq_HTSXOTWrzzg.png" /><figcaption>Adding the panzoom web block</figcaption></figure><p>You can also add a custom icon if you want to.</p><p>Screens using our panzoom widget will communicate with the widget via input parameters. The component itself provides a variety of options and I chose to use a structure <em>PanzoomOptions</em> in OutSystems to hold them.</p><pre>/**<br> * PanzoomOptions<br> *<br> * @property {bool} [Animate] = False<br> * Whether to animate transitions<br> *<br> * @property {bool} [Canvas] = False<br> * This option treats the Panzoom element&#39;s parent as a canvas. Effectively,<br> * Panzoom binds the down handler to the parent instead of the Panzoom<br> * element, so that pointer events anywhere on the &quot;canvas&quot; moves its<br> * children. See issue #472.<br> * Note: setting this option to true also changes where the cursor style is<br> * applied (i.e. the parent).<br> *<br> * @property {int} [Duration] = 200<br> * Duration of the transition (ms)<br> *<br> * @property {string} [Easing] = &quot;ease-in-out&quot;<br> * CSS Easing used for transitions<br> *<br> * @property {string} [ExcludeClass] = &quot;panzoom-exclude&quot;<br> * Add this class to any element within the Panzoom element that you want to<br> * exclude from Panzoom handling. That element&#39;s children will also be<br> * excluded. e.g. links and buttons that should not propagate the click event.<br> *<br> * @property {string} [Overflow] = &quot;hidden&quot;<br> * The overflow CSS value for the parent. Defaults to &#39;hidden&#39;<br> *<br> * @property {decimal} [StartScale] = 1<br> * Scale used to set the beginning transform<br> *<br> * @property {decimal} [StartX] = 0<br> * X value used to set the beginning transform<br> *<br> * @property {decimal} [StartY] = 0<br> * Y value used to set the beginning transform<br> *<br> * @property {string} [TouchAction] = &quot;none&quot;<br> * This value is used to set touch-action on both the Panzoom element and its<br> * parent. It is needed because that the native scroll on mobile interferes<br> * with panning and pinch zooming. Set this to empty string to re-enable<br> * scrolling on mobile, but note that both scrolling and panning cannot work<br> * at the same time.<br> *<br> * @property {string} [Contain] = &quot;&quot;<br> * &quot;inside&quot; | &quot;outside&quot;<br> *<br> * @property {string} [Cursor] = &quot;move&quot;<br> * The cursor style to set on the panzoom element<br> *<br> * @property {bool} [DisablePan] = False<br> * Disable panning functionality. Note: disablePan does not affect focal point<br> * zooming or the contain option. The element will still pan accordingly.<br> *<br> * @property {bool} [DisableXAxis] = False<br> * Pan only on the Y axis<br> *<br> * @property {bool} [DisableYAxis] = False<br> * Pan only on the X axis<br> *<br> * @property {bool} [PanOnlyWhenZoomed] = False<br> * Disable panning while the scale is equal to the starting value<br> *<br> * @property {bool} [RoundPixels] = False<br> * Round x and y values to whole numbers. This can help prevent images and<br> * text from looking blurry, but the higher the scale, the more it becomes<br> * necessary to use fractional pixels. Use your own judgment on how much to<br> * limit zooming in when using this option.<br> *<br> * @property {bool} [DisableZoom] = False<br> * Disable zooming functionality<br> *<br> * @property {decimal} [MaxScale] = 4<br> * The maximum scale when zooming<br> *<br> * @property {decimal} [MinScale] = 0.125<br> * The minimum scale when zooming<br> *<br> * @property {decimal} [Step] = 0.3<br> * The step affects zoom calculation when zooming with a mouse wheel, when<br> * pinch zooming, or when using zoomIn/zoomOut<br> */</pre><p>Now that we have created the structure, we can add the input parameter <em>Options</em> of type <em>PanzoomOptions</em> and the input parameter <em>ExtendedClass</em> to our web block. This will later allow the configuration of the panzoom component and setting additional CSS classes. We also need a local variable <em>PanzoomObject</em> to hold reference of our panzoom object, so we can access it via JavaScript.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*u2JjfYRdajk4605feWlz5Q.png" /><figcaption>Input parameters and local variable of web block Panzoom</figcaption></figure><p>For later apps to place pan and zoomable content into the widget, we also need to add a container and a placeholder to the widget tree. The container is a wrapper that gets the ExtendedClass als Style Classes. The placeholder&#39;s name is visible for developers using our component, so “Content” would be a descriptive option. It is also later referred in our JavaScript to identify the HTML element to render the panzoom component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*Q09r6ReMNM1dFeEQ9khSbA.png" /><figcaption>Widget tree of web block Panzoom</figcaption></figure><p>To bring panzoom to life, it’s time for a little bit of scripting. When the DOM of our web block is rendered, we need to initialize the panzoom component to have it render its HTML elements into the DOM as well. For this we have the <em>OnRender</em> event in OutSystems, which is fired when the block is ready after its first render.</p><p>You can add custom JavaScripts to your OutSystems client flows and to transfer data between it and the OutSystems flow you can define input and output parameters. Unfortunately, structures cannot be select as data type here, so we must serialize our options to JSON first. As mentioned above, we need a reference to the HTML element the panzoom should render into. This is done via the parameter <em>ElementId</em>, also of type <em>Text</em>. The JavaScript will output an object representing the panzoom component which we want to store in our local variable <em>PanzoomObject</em>. Last, we fire the own event <em>OnReady</em> to allow consumers of our widget to perform custom actions after we initialized the panzoom. We also pass the reference to the panzoom object to the consumer for reasons described later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mMy1XUgUI4aLiK3S3sFrwQ.png" /><figcaption>OnRender event handler of web block Panzoom</figcaption></figure><p>You can copy and paste the following listing into the JavaScript added above:</p><pre>/**<br> * Panzoom_Init<br> *<br> * @param {string} ElementId<br> * @param {string} Options<br> * @return {object} PanzoomObject<br> */<br>var e = document.getElementById($parameters.ElementId);<br>if(!e) throw &#39;Could not find element &quot;&#39; + $parameters.ElementId + &#39;&quot; for panzoom component.&#39;;<br>var o = JSON.parse($parameters.Options);<br>var p = Panzoom(e, o);<br>e.parentElement.addEventListener(&#39;wheel&#39;, p.zoomWithWheel);<br>e.addEventListener(&#39;panzoomchange&#39;, (event) =&gt; {<br>  $actions.PanzoomChange(event.Detail);<br>})<br>$parameters.PanzoomObject = p;</pre><p>As you can see, we add an event listener to the panzoom’s JavaScript event <em>panzoomchanged</em> which calls a client action called <em>PanzoomChange</em>. The panzoom component passes an object with information about the change to the event handler. To make its values available in OutSystems, we need to parse the event object with an additional JavaScript. Afterwards we pass the details <em>X</em>, <em>Y</em> and <em>Scale</em> (all of type <em>Decimal</em>) to our own <em>OnPanzoomChange</em> event to inform the consumer of our widget.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*QEGd-w2Ed8lCjrnmP6NKBQ.png" /><figcaption>Handler for the panzoom’s panzoomchanged event</figcaption></figure><pre>/**<br> * Panzoom_GetEventDetail<br> *<br> * @param {object} event<br> * @param {decimal} x<br> * @param {decimal} y<br> * @return {decimal} scale<br> */<br>var e = $parameters.event;<br>if(e) {<br>  $parameters.X = e.x;<br>  $parameters.Y = e.y;<br>  $parameters. Scale = e.scale;<br>}</pre><p>To properly tidy up everything when then web block is unloaded from a screen in OutSystems, there is another event <em>OnDestroy</em>. This is the correct place to also destroy the panzoom component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*AiDzioitmWpIaB6XRB-dqA.png" /><figcaption>OnDestroy event handler of web block Panzoom</figcaption></figure><p>The JavaScript removes the event listener we added for the mouse wheel while initialization and calls the corresponding method of the panzoom object passed as input parameter <em>PanzoomObject</em> which we stored to the local variable <em>PanzoomObject</em> after initialization.</p><pre>/**<br> * Panzoom_Destroy<br> *<br> * @param {string} ElementId<br> * @param {object} PanzoomObject<br> */<br>var p = $parameters.PanzoomObject<br>if(p) {<br>    var e = document.getElementById($parameters.ElementId);<br>    if(e) e.parentElement.removeEventListener(&#39;wheel&#39;, p.zoomWithWheel);<br>    p.destroy();<br>}</pre><p>Now there is one important block event left: <em>OnParametersChanged</em>, which is fired every time one input parameter of the web block is changed. In our case for example this will happen when the <em>Options</em> get changed by the screen the panzoom widget is placed on. To handle this event correctly we need to update the panzoom component’s options.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*QMozmvShVIzmqlfOyumYTQ.png" /><figcaption>OnParametersChanged event handler of web block Panzoom</figcaption></figure><p>Where did this strange looking client action <em>Panzoom_SetOptions</em> come from? We now will implement it together with some other client actions we will publish to the consumer of our widget.</p><h4>Implement some public client actions to interact with the panzoom</h4><p>You already learned the official way to communicate with blocks via input parameters and events. The panzoom component we are integrating here additionally provides some JavaScript methods to be called directly. Those are exposed by the panzoom object we hold in the local variable <em>PanzoomObject</em> during the initialization.</p><p>In OutSystems blocks can only expose input parameters and events but no client actions. So, the only way to make the component’s methods available for consumer apps, is to implement public client actions and pass an input parameter with the panzoom object we want the methods to be performed on. This is the reason we passed it to the consumer in our <em>OnReady</em> event.</p><p>Below you will find the client action flows and the respective JavaScripts. The input parameter <em>PanzoomObject</em> is passed to all JavaScripts as input parameter as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*e6rLUJStxOZl7JOZpe_Wlg.png" /><figcaption>Client Actions to interact with the panzoom component (part 1/2)</figcaption></figure><p><strong><em>Panzoom_GetOptions</em></strong> returns a copy of the current options object in our OutSystems structure <em>PanzoomOptions</em>. As we cannot pass structures to or from JavaScripts in OutSystems, we must serialize and deserialize it as JSON.</p><pre>/**<br> * Panzoom_GetOptions<br> *<br> * @param {object} PanzoomObject<br> * @return {string} Options<br> */<br>if ($parameters.PanzoomObject) {<br>  var o = $parameters.PanzoomObject.getOptions();<br>  $parameters.Options = JSON.stringify(o);<br>}</pre><p><strong><em>Panzoom_GetPan</em></strong> returns the current pan position (x/y translation).</p><pre>/**<br> * Panzoom_GetPan<br> *<br> * @param {object} PanzoomObject<br> * @return {decimal} x<br> * @return {decimal} y<br> */<br>if($parameters.PanzoomObject) {<br>    var p = $parameters.PanzoomObject.getPan();<br>    $parameters.X = p.x;<br>    $parameters.Y = p.y;<br>}</pre><p><strong><em>Panzoom_GetScale</em></strong> returns the current zoom scale.</p><pre>/**<br> * Panzoom_GetScale<br> *<br> * @param {object} PanzoomObject<br> * @return {decimal} Scale<br> */<br>if($parameters.PanzoomObject) $parameters.Scale = $parameters.PanzoomObject.getScale();</pre><p><strong><em>Panzoom_Pan</em></strong> pans to the given x and y coordinates.</p><pre>/**<br> * Panzoom_Pan<br> *<br> * @param {object} PanzoomObject<br> * @param {decimal} x<br> * @param {decimal} y<br> * @param {bool} Relative<br> * @param {bool} Force<br> */<br>if($parameters.PanzoomObject) {<br>    $parameters.PanzoomObject.pan(<br>        $parameters.X,<br>        $parameters.Y,<br>        {<br>            relative: $parameters.Relative,<br>            force: $parameters.Force<br>        }<br>    );<br>}</pre><p><strong><em>Panzoom_Reset</em></strong> resets the pan and zoom to <em>startX</em>, <em>startY</em>, and <em>startScale</em>. By default, it animates ignoring the global option (set <em>Animate</em> to <em>False</em> to override). The method also ignores the <em>disablePan</em>, <em>disableZoom</em>, and <em>panOnlyWhenZoomed </em>options (to override set <em>Force</em> to <em>False</em>).</p><pre>/**<br> * Panzoom_Reset<br> *<br> * @param {object} PanzoomObject<br> * @param {bool} Animate<br> * @param {bool} Force<br> */<br>if($parameters.PanzoomObject) $parameters.PanzoomObject.reset(<br>    {<br>        animate: $parameters.Animate,<br>        force: $parameters.Force<br>    }<br>);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*9wxD0bIoERgXwcE6dzUYag.png" /><figcaption>Client Actions to interact with the panzoom component (part 2/2)</figcaption></figure><p><strong><em>Panzoom_SetOptions</em></strong> updates the options of the panzoom instance with the given <em>PanzoomOptions</em> structure, which of course must be serialized as JSON to be passed to the JavaScript.</p><pre>/**<br> * Panzoom_SetOptions<br> *<br> * @param {object} PanzoomObject<br> * @param {string} Options<br> */<br>if ($parameters.PanzoomObject) {<br>    var o = JSON.parse($parameters.Options);<br>    $parameters.PanzoomObject.setOptions(o);<br>}</pre><p><strong><em>Panzoom_Zoom</em></strong> zooms the panzoom element to the given scale.</p><pre>/**<br> * Panzoom_Zoom<br> *<br> * @param {object} PanzoomObject<br> * @param {decimal} Scale<br> */<br>if($parameters.PanzoomObject) $parameters.PanzoomObject.zoom($parameters.Scale);</pre><p><strong><em>Panzoom_ZoomIn</em></strong> zooms in using the predetermined increment set in options. Animates by default, ignoring the global option (set <em>Animate</em> to <em>False</em> to override).</p><pre>/**<br> * Panzoom_ZoomIn<br> *<br> * @param {object} PanzoomObject<br> * @param {bool} Animate<br> */<br>if($parameters.PanzoomObject) $parameters.PanzoomObject.zoomIn({ animate: $parameters.Animate, });</pre><p><strong><em>Panzoom_ZoomOut</em></strong> zooms out using the predetermined increment set in options. Animates by default, ignoring the global option (set <em>Animate</em> to <em>False</em> to override).</p><pre>/**<br> * Panzoom_ZoomOut<br> *<br> * @param {object} PanzoomObject<br> * @param {bool} Animate<br> */<br>if($parameters.PanzoomObject) $parameters.PanzoomObject.zoomOut({ animate: $parameters.Animate, });</pre><p><strong><em>Panzoom_ZoomToPoint</em></strong> zooms the panzoom element to a focal point using the given <em>Scale</em> and point (<em>ClientX</em>/<em>ClientY</em>).</p><pre>/**<br> * Panzoom_ZoomToPoint<br> *<br> * @param {object} PanzoomObject<br> * @param {decimal} Scale<br> * @param {decimal} ClientX<br> * @param {decimal} ClientY<br> */<br>if($parameters.PanzoomObject) $parameters.PanzoomObject.zoomToPoint(<br>    $parameters.Scale,<br>    {<br>        clientX: $parameters.ClientX,<br>        clientY: $parameters.ClientY<br>    }<br>);</pre><p>Congratulations, you have now integrated the panzoom JavaScript component as a reusable widget for OutSystems. Now it’s time to try it out in a demo app.</p><h3>Build a demo app</h3><p>The purpose of the little demo app we will implement now, is to display a SVG graphic and allowing to “panzoom” around and test the functionality implemented above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tIVDLlQf0gv0d-kaCAtlCA.png" /><figcaption>UI of the demo app</figcaption></figure><p>We start by adding a dependency to the module holding our panzoom widget and activate all checkboxes for the block, client actions and structure. Afterwards we must add the home screen, I simply named “Demo”, to the <em>MainFlow</em>. The layout is based on an <em>Adaptive\ColumnsMediumRight</em> block. The left column holds the panzoom component, the right one contains a control panel to play around with the demo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*jybq1GPLNlj_3_nhkkM-2Q.png" /><figcaption>Widget tree of left column of the demo ui</figcaption></figure><p>To configure the panzoom component, we expand the <em>Options</em> parameter of the added <em>Panzoom </em>block. By doing so, we can see all attributes of the underlaying structure <em>PanzoomOptions</em> and provide initial values for all the options. The values used in this example are suitable for the used tiger graphic but please feel free to play around with them or change them according to the content you want to use. The block also has the <em>ExtendedClass </em>parameter which is set to <em>“full-height”</em> here to make sure, the panzoom area takes the available space in its parent container.</p><p>The content we want to be pan- and zoomable is placed into the <em>Content</em> placeholder of the <em>Panzoom </em>block. In this example we simply use a SVG graphic. In this example we use an SVG graphic, which has the advantage that it can be losslessly scaled. To directly display SVG graphics in OutSystems there is the <em>Utilities\InlineSVG</em> block in <em>OutSystemsUI</em>, which embeds the given <em>SVGCode</em>. Because this input parameter is of type <em>Text</em>, we must enclose in the SVG in double quotes and encode all containing double quotes. For your comfort and better readability of this article, you can find the ready to copy sample graphic on <a href="https://gist.github.com/sebastian-krempel/5f7295e75b7fddb980f6c287d2c9fdcc">my gist</a>. Please don’t forget to give the InlineSVG widget a name (here simply “SVG”) as we need it later to reference the HTML element in JavaScript.</p><p>The parent container ist styled by using the following CSS classes:</p><pre>background-neutral-0 padding-m border-radius-soft</pre><p>Next, we want to implement some code to test the different functionalities the <em>Panzoom</em> widget offers. First, we need a local variable <em>Panzoom</em> of type <em>Object</em> to hold the panzoom object and implement handlers for the events of the <em>Panzoom</em> widget:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f7Y9CmZ-fR4JL7eZlNZKig.png" /><figcaption>Variables and event handlers for the panzoom widget</figcaption></figure><p><strong><em>PanzoomOnReady</em></strong> simply assigns the received <em>PanzoomObject </em>to the local variable <em>Panzoom</em>.</p><p><strong><em>PanzoomOnPanzoomChange</em></strong> is triggered every time the state of the panzoom component changes. To later monitor the state on the screen the event handler composes a <em>Text</em> and assigns it to the local variable <em>PanzoomState</em> by using the following expression:</p><pre>&quot;X: &quot; + X + NewLine() + &quot;Y: &quot; + Y + NewLine() + &quot;Scale: &quot; + Scale</pre><p>The control panel in the second screen column (right side) offers a button field for the different client actions and a control to display the current panzoom state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hl7yYvV6O_hffTxk3OF0NQ.png" /><figcaption>Widget tree of right column of the demo ui</figcaption></figure><p>The control panel consists of a parent container (A), in which three button containers (B) with three buttons each are arranged. The additional attribute <em>title</em> is used to get a simple tooltip for the buttons. For the sake of simplicity, you will find the style classes to copy out here:</p><pre>Container A: background-neutral-0 padding-m border-radius-soft<br>Container B: display-flex margin-bottom-m<br>Buttons:     btn btn-primary flex1</pre><p>The control zu display the current panzoom state is constructed with a container (C) faking to be a disabled input control by utilizing the two additional attributes <em>data-input</em> and <em>disabled</em>. The expression inside is bound to the local variable <em>PanzoomState</em>.</p><p>Each button has a corresponding <em>OnClick</em> event handler that calls the related client action of our Panzoom component:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*QP7rRLc-DPucoVJM1rhC8A.png" /><figcaption>Event handlers for the control panel buttons</figcaption></figure><p><strong><em>Pan[Direction]OnClick</em></strong> calls the <em>Panzoom_Pan </em>client action with the following parameters:</p><pre>Down:  X =   0, Y =  10, Relative = True<br>Left:  X = -10, Y =   0, Relative = True<br>Right: X =  10, Y =   0, Relative = True<br>Up:    X =   0, Y = -10, Relative = True</pre><p><strong><em>ZoomEyeOnClick</em></strong> zooms to the “eye of the tiger” using the following parameters:</p><pre>Panzoom_Pan:  X = -40, Y = 91, Relative = False<br>Panzoom_Zoom: Scale = 3.6</pre><p>The last button with the cog icon opens a popup dialog which allows the user to manipulate all options of the <em>PanzoomOptions</em> structure. For simplicity this is implemented as a rudimentary JSON editor. Therefore, we need the following local variables and client actions in the screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8bPCA4t17iRZJSNlf3jZMA.png" /><figcaption>Variables and event handlers for the options popup dialog</figcaption></figure><p><strong><em>OptionsOnClick </em></strong>handles when the cog button is clicked and requests the current options from the panzoom component via <em>Panzoom_GetOptions</em>, serializes the retuned <em>PanzoomOptions </em>structure, assigns the resulting JSON to the local variable <em>OptionsJSON</em> and shows the popup by setting <em>OptionsDialogVisible </em>to <em>True</em>.</p><p><strong><em>OptionsDialogOkOnClick</em></strong> handles when the OK button of the popup dialog is clicked, deserializes the JSON user input in <em>OptionsJSON </em>and updating the panzoom component via <em>Panzoom_SetOptions</em>. Afterwards the popup dialog is closed by setting <em>OptionsDialogVisible </em>to <em>False</em>.</p><p><strong><em>OptionsDialogCancelOnClick </em></strong>handles clicks on the Cancel button of the popup dialog.</p><p>The UI of the options popup dialog is built as shown in the next figure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RdIAI5yyLWtA4qg2Apr0Gg.png" /><figcaption>UI of the options popup dialog</figcaption></figure><p>The last feature we want to implement is ability to zoom in to a point of the graphic the user double clicks. Therefore, we must implement the client action <em>ImageOnDblClick</em> to handle when the user double clicks and register it as an event listener in the browser. This can be achieved with JavaScript we place into the <em>OnReady</em> event of our screen. This receives the <em>ElementId</em> of the InlineSVG widget via an input parameter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/1*s1SuFH_WpF64uRfDQELc-Q.png" /><figcaption>Event handler for double clicking the graphic</figcaption></figure><pre>/**<br> * ImageAddEventListener<br> *<br> * @param {string} ElementId<br> */<br>var e = document.getElementById($parameters.ElementId)<br>e.addEventListener(&#39;dblclick&#39;,(event) =&gt; {<br>    $actions.ImageOnDblClick(event.clientX, event.clientY);<br>});</pre><p>Well done! You have made it through and also created the demo app. You can now publish and test the application and the panzoom component integration.</p><h3>Get the ready-to-use component from the Forge</h3><p>I already published the component in the OutSystems Forge (<a href="https://www.outsystems.com/forge/component-overview/14319/panzoom-reactive">Panzoom Reactive</a>) so you can use it in your apps as well. I would be happy if you leave some claps and/or a coffee 😉</p><p>I hope you enjoyed reading this tutorial and recreating it in your environment. If the article was interesting for you, I would be pleased if you follow me on medium. In case you have any questions left open or have tips for me to improve, please contact me via medium or my <a href="https://www.outsystems.com/profile/enrntqhemy/">OutSystems profile</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29fefed6a4fb" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/panning-and-zooming-images-in-outsystems-29fefed6a4fb">Panning and zooming images in OutSystems</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Profile pictures in OutSystems the traffic saving way]]></title>
            <link>https://itnext.io/profile-pictures-in-outsystems-the-traffic-saving-way-5c5f727b1253?source=rss-15f59cd3d285------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c5f727b1253</guid>
            <category><![CDATA[outsystems]]></category>
            <category><![CDATA[low-code]]></category>
            <category><![CDATA[localstorage]]></category>
            <category><![CDATA[html5]]></category>
            <dc:creator><![CDATA[Sebastian Krempel]]></dc:creator>
            <pubDate>Mon, 24 Oct 2022 07:31:17 GMT</pubDate>
            <atom:updated>2023-01-11T20:37:51.270Z</atom:updated>
            <content:encoded><![CDATA[<h3>Profile pictures in OutSystems the traffic-saving way</h3><h4>How to implement them and avoid unnecessary data traffic</h4><figure><img alt="Article title and subtitle in front of lines of code that shrink down in size and represent a data stream" src="https://cdn-images-1.medium.com/max/1024/1*FiphTQb2COh2gUQUvcktLw.png" /></figure><p>OutSystems is very handy and offers a lot of ready-to-use UI patterns when it comes to quickly implementing reactive web applications. An example of this is the so-called <em>UserInfo</em> widget, which resides in the upper right corner of the page. Unfortunately, this widget does not implement the profile picture functionality although it displays a placeholder image.</p><h3>Summary</h3><p>In this article you will learn</p><ul><li>how to implement this missing feature in a simple way,</li><li>where there are drawbacks regarding data traffic,</li><li>and how to avoid them.</li></ul><p>Therefore, we will build a small example app together.</p><h3>What you need</h3><p>If you want to follow up the implementation on your own, you need:</p><ul><li>An OutSystems account (a <a href="https://www.outsystems.com/free-edition/">free personal environment</a> is sufficient)</li><li>OutSystems Service Studio</li><li>A web browser with dev tools to inspect sent requests (e.g. Edge, Chrome, Firefox)</li></ul><p>For this tutorial you should already have some experience in building reactive web applications with OutSystems.</p><h3>The simple solution</h3><h4>Adding a profile picture to our users</h4><p>In OutSystems, end users are managed in the <em>User</em> entity that can be found in the <em>System</em> module and is by default added as a dependency of new reactive web apps. Since this entity does not provide an attribute to store a profile picture, we need to store the picture elsewhere. In an application intended to run in a production environment, we would consider a separate domain-based service for this type of user profile data or obtaining the profile image from an identity provider such as for example Azure Active Directory.</p><p>To keep things simple in this article, we create a separate <em>UserPicture</em> entity in our example application. Since each user can only have exactly one profile picture, we use <em>User Identity</em> as the primary key for <em>UserPicture</em> so we get a one-to-one relationship.</p><figure><img alt="Entity relationship model showing the 1-to-1 relation between User and UserPicture with their attributes" src="https://cdn-images-1.medium.com/max/710/1*Nj_o8l8aYev4wYERvn6_xw.png" /><figcaption>Entities of the sample app</figcaption></figure><p>For the user to be able to change the profile picture, we need a form with a data action <em>GetProfilePicture</em> to load the current image data.</p><figure><img alt="Action flow of GetProfilePicture" src="https://cdn-images-1.medium.com/max/310/1*1cn8GaVocxDooAMNrWJ1Bw.png" /><figcaption>Data action: GetProfilePicture</figcaption></figure><p>Next, we place an upload widget on the form. By setting the widget’s parameters <em>File Content</em> to <em>GetProfilePicture.Picture</em> and <em>Accept</em> to <em>Image</em>, we get a neat editor which shows the current picture and provides an option to upload a new image file.</p><figure><img alt="Screenshot of the upload widget with its parameters’ configuration" src="https://cdn-images-1.medium.com/max/1008/1*YUOpMdboeAV0fqLrcyvnJg.png" /><figcaption>UI to change the profile picture</figcaption></figure><p>As you can see in the screenshot above, a handler for the <em>On Change</em> event is added to the widget as well. This is to directly save the image to the database when the user selects a new file. To realize this functionality on the server side, we implement a new server action <em>ProfilePicture_Save</em>.</p><figure><img alt="Action flows of UploadOnChange and ProfilePicture_Save" src="https://cdn-images-1.medium.com/max/725/1*8iKA4KzrEna10s_ZJu5L6A.png" /><figcaption>Client action UploadOnChange and server action ProfilePicture_Save</figcaption></figure><p>For better testing purposes, we will also add a server action to remove the profile picture if one exists. Therefore, we can reuse <em>ProfilePicture_Save</em> and set the parameter <em>Picture</em> to <em>NullBinary()</em>. To update the ui afterwards we could refresh the data action <em>GetProfilePicture</em>. But to save this server callback, we can simply be optimistic and overwrite the value as it is expected to be <em>NullBinary()</em>.</p><figure><img alt="Screenshot of the Remove button with action flow of its click event handler RemoveOnClick and the parameters’ configurations for the containing action calls" src="https://cdn-images-1.medium.com/max/864/1*dpCmoQD0-rcotVG1Pysvqw.png" /><figcaption>Extended ui and client action RemoveOnClick</figcaption></figure><p>After we have this all set up, we can publish and test our application.</p><h4>Displaying the profile picture in the UserInfo widget</h4><p>For the moment, the user can already change the profile picture, but of course it will not be displayed in the <em>UserInfo</em> widget in the upper right corner yet. To realize this, we need to extend the <em>UserInfo</em> widget accordingly. An uncomplicated way would be to add the already implemented data action to the widget and configure its output parameter to be the source of the image widget. The disadvantage of this method is that it would be reloaded on every page load and thus the profile picture would always be reloaded from the database and transferred from the server to the client. As the title of my article states, we want to avoid unnecessary traffic, so this is no solution.</p><p>If you look at how OutSystems loads the username from the server and displays it in the <em>UserInfo</em> widget, you will see that they store the username in a client variable and request it from the server only when necessary. So why shouldn’t we also store the profile picture in a client variable? This poses the problem that OutSystems does not support the binary data type for client variables. If you search for a solution to this issue in the OutSystems community, you will find a simple solution that encodes the image as base64 and stores the resulting string in a client variable. To display the image, the string is then decoded to binary data again.</p><p>So, let’s put it this way for now. To save another request to the server, we simply extend the existing server action <em>GetUserNameFromServer</em> by another output parameter for the profile picture. Of course, we need to extend the client action <em>GetUsername</em> as well and store the received profile picture locally into a new client variable <em>UserPicture</em>. For better reusability and maintainability, we implement this as a separate client action to store the profile picture on the client side.</p><figure><img alt="Action flows of GetUserNameFromServer, GetUsername and SetLocalUserPicture" src="https://cdn-images-1.medium.com/max/971/1*wIRwkn3fXW0q9_7eqQhdIA.png" /><figcaption>Extended actions GetUserNameFromServer and GetUsername of the standard widget and SetLocalUserPicture</figcaption></figure><p>Obviously, we also need to retrieve the locally stored profile picture and load it into the source parameter of the image widget of <em>UserInfo</em>. For this we use a second client action <em>GetLocalUserPicture</em> which is configured as a function. This allows us to modify the parameters of the image widget as shown in the figure below and directly receive the picture from the client action.</p><figure><img alt="Action flow of GetLocalUserPicture and changed parameters of the profile image widget in UserInfo" src="https://cdn-images-1.medium.com/max/706/1*82FLcHxQj5XvWjva_qKpqg.png" /><figcaption>GetLocalUserPicture and changed profile image in UserInfo widget</figcaption></figure><p>For encoding and decoding the binary data as base64 string we can simply write our own javascripts <em>Base64encode</em> and <em>Base64decode</em>. These contain one input and one output parameter to receive and return the binary data and the encoded string, respectively. The conversion is pretty easy to do with the built-in <em>btoa</em> and <em>atob</em> functions of the <em>window</em> object in javascript:</p><pre>// base64 encode:<br>$parameters.Base64 = window.btoa($parameters. Binary);</pre><pre>// base64 decode:<br>$parameters.Binary = window.atob($parameters.Base64);</pre><p>Congratulations, we have managed to let the user upload a profile picture and display it in the already existing <em>UserInfo</em> widget without having to request it repeatedly. But there is even more to the story…</p><h3>Is using client variables a clever idea?</h3><p>Client variables differ from normal screen variables by being kept in local storage even when the browser is closed, and by being shared between screens. This is especially useful if you want to preserve user preferences or an overall context.</p><p>This is great for our purpose, isn’t it? As long as client variables are only used on the client side, the solution described above works totally fine.</p><h4>Unnecessary data traffic in server callbacks</h4><p>However, as soon as a single client variable is accessed on the server side, all client variables are transferred to the server with each callback by default.</p><p>To illustrate the behavior in our sample application, let’s create a client variable called <em>ResultsPerPage</em> with a default value of 10 and add a small list view to our screen. For simplicity, the data action <em>GetListData</em> returns n randomly generated passwords, where n is the value of <em>ResultsPerPage</em>.</p><figure><img alt="Extended screen with list view and action flow of GetListData" src="https://cdn-images-1.medium.com/max/1024/1*0Rc0ZpKMtl7IFdRtdAD56Q.png" /><figcaption>Extended screen with list view and the new data action GetListData</figcaption></figure><p>If we now publish this new app version we can check, in the developer tools of our browser (to open press F12), which data is sent to the server when we click on the <em>Refresh list</em> button. As you can see in the network tab, all client variables, including the base64 encoded profile picture, are sent within the payload of each server callback.</p><figure><img alt="Screenshot of the network inspection result showing the requests payload containing the encoded UserPicture content" src="https://cdn-images-1.medium.com/max/961/1*HB-DAip2YbEQjsNzYNReGw.png" /><figcaption>Network inspection in the browser’s dev tools</figcaption></figure><p>Certainly, 102 kB as in this example is not a large amount of data but transferring it unnecessarily does not make sense. Depending on the complexity of the application and the number of client variables that are only required locally, this can quickly add up to quite a bit of data that should not be transferred.</p><h3>The better solution</h3><p>The goal is to prevent the profile picture from being sent to the server, as part of the client variables, with each request. To achieve this, we can modify our already implemented client actions to store the picture in a separate local storage item that is independent of the standard OutSystems mechanism, wich also utilizes the local storage for its client variables.</p><p>To do this, we first remove the <em>UserPicture</em> client variable, since we won’t need it anymore. Afterwards we need to adjust the logic of both client actions <em>SetPictureFromLocalStorage</em> and <em>GetPictureFromLocalStorage</em> as shown in the following figure:</p><figure><img alt="Action flow of SetPictureFromLocalStorage with the parameters’ configurations of the contained JavaScripts and actions flow of GetPictureFromLocalStorage" src="https://cdn-images-1.medium.com/max/1024/1*96nPv3P2ROvRYXZk8kO-0Q.png" /><figcaption>Modified client actions to store and load the profile picture from local storage</figcaption></figure><p>As you can see in the middle section of the screenshot, all three new JavaScripts have an input parameter called <em>AppName</em>. It is used to create an application specific prefix for the key of our separate local storage item. This ensures each app gets its own namespace if multiple apps are deployed on the same host. In addition, the prefix also contains the segment <em>$KeepLocalVars$</em> to identify our purely local variables and distinguish them from the namespace used by OutSystems.</p><p>To access to the local storage, you can find the component <a href="https://www.outsystems.com/forge/component-overview/6978/local-storage-reactive"><em>Local Storage Reactive</em></a><em> </em>by Paulo Cação in the OutSystems forge. I decided not to use it, since we only need three simple lines of code to achieve the result and can do the required encoding of the binary data at the same time.</p><p>Below you can find the listings of the three new JavaScripts:</p><pre>// SavePictureToLocalStorage<br>window.localStorage.setItem(<br>  &#39;$&#39; + $parameters.AppName + &#39;$KeepLocalVars$UserPicture&#39;,<br>  window.btoa($parameters.Binary)<br>);</pre><pre>// RemovePictureFromLocalStorage<br>window.localStorage.removeItem(<br>  &#39;$&#39; + $parameters.AppName + &#39;$KeepLocalVars$UserPicture&#39;<br>);</pre><pre>// GetPictureFromLocalStorage<br>var p = window.localStorage.getItem(<br>  &#39;$&#39; + $parameters.AppName + &#39;$KeepLocalVars$UserPicture&#39;<br>);<br>if (p!==null) $parameters.Binary = window.atob(p);</pre><p>Let us now republish our app and inspect the network tab. As you can see, now the client variable <em>UserPicture</em> does not get sent to the server anymore.</p><h4>One last question</h4><p>How does the local storage item get cleared when the user logs out?<br>The answer is simple: Never!</p><p>The reason you cannot encounter an issue with this behavior is, that OutSystems clears the client variables on logout, so <em>Client.Username</em> is empty the next time <em>GetUsername</em> runs, and the locally stored profile picture will be overwritten. Nevertheless, it is good practise to actively remove the profile picture from local storage on logout. To do this, we just need to call <em>SetLocalUserPicture</em> with the parameter <em>Picture</em> set to <em>NullBinary()</em> in the <em>Logout</em> client action of the <em>UserInfo</em> widget:</p><figure><img alt="Extended action flow of ClientLogout and paremeter configuration of SetLocalUserPicture" src="https://cdn-images-1.medium.com/max/629/1*8Q2o7Eke96eULFYpqg8c-w.png" /><figcaption>Remove local profile picture on logout</figcaption></figure><p>I hope the article was interesting for you to read and I have covered the topic. If you have any questions left open or have tips for me to improve, please contact me via medium or my <a href="https://www.outsystems.com/profile/enrntqhemy/">OutSystems profile</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c5f727b1253" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/profile-pictures-in-outsystems-the-traffic-saving-way-5c5f727b1253">Profile pictures in OutSystems the traffic saving way</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>