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

<channel>
	<title>AprendeXojo &#8211; Xojo Programming Blog</title>
	<atom:link href="https://blog.xojo.com/tag/aprendexojo/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.xojo.com</link>
	<description>Blog about the Xojo programming language and IDE</description>
	<lastBuildDate>Thu, 21 Apr 2022 15:19:11 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>
	<item>
		<title>Updated: Make Your Own Classes Iterables</title>
		<link>https://blog.xojo.com/2021/09/02/updated-make-your-own-classes-iterables/</link>
		
		<dc:creator><![CDATA[Javier Menendez]]></dc:creator>
		<pubDate>Thu, 02 Sep 2021 19:59:59 +0000</pubDate>
				<category><![CDATA[General]]></category>
		<category><![CDATA[Learning]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[AprendeXojo]]></category>
		<category><![CDATA[Iterable]]></category>
		<category><![CDATA[Iterator]]></category>
		<guid isPermaLink="false">https://blog.xojo.com/?p=9074</guid>

					<description><![CDATA[In programming, iterators are the mechanisms that allow us to run through all the items of a collection without needing to know in advance how many of them compose that collection. To do this, we can use the commands For Each… Next in Xojo. What are the main differences when comparing For Each… Next with the conventional For… Next? See how the For Each… Next loop iterates every item associated with the object. It's a more concise, stylish and Object-Oriented (OOP) way of doing things when compared with the classic For… Next loop.]]></description>
										<content:encoded><![CDATA[
<h5 class="wp-block-heading">This blog post was <a href="https://blog.xojo.com/2017/12/13/make-your-own-classes-iterables/">originally written</a> by Javier Menendez in 2017 and has been updated for Xojo API 2.0 by Wayne Golding.</h5>



<p>In programming,&nbsp;<a href="https://documentation.xojo.com/api/code_execution/iterator.html">iterators</a>&nbsp;are the mechanisms that run through all the items of a collection without needing to know in advance how many items compose that collection. To do this in Xojo, use the commands&nbsp;<code>For Each… Next</code>. What are the main differences when comparing <code>For Each… Next</code> with the conventional&nbsp;<code>For… Next</code>?</p>



<p>The first difference is that with&nbsp;<code>For Each… Next</code>&nbsp;we can’t assume that we are iterating the items in the collection in order, as is the case when using the variable of the conventional&nbsp;<code>For… Next</code>. The second difference is that the iterator will be invalid when the iterated elements are modified or when we modify the number of elements in the collection during the iteration process.</p>



<p>By default in Xojo, there are a couple of collections that are <a href="https://documentation.xojo.com/api/code_execution/iterable.html">iterable</a>: <a href="https://documentation.xojo.com/api/language/array.html">Arrays</a>, <a href="http://developer.xojo.com/xojo-core-dictionary">Dictionaries</a> and <a href="https://documentation.xojo.com/api/files/folderitem.html.Children">FolderItem.Children</a>. Wouldn’t it be great to extend this behaviour to other classes, making them more flexible? The key to doing just that is in two of Xojo&#8217;s Class Interfaces: Iterator and Iterable.</p>



<p><a href="https://www.dropbox.com/s/gcjvnmewyc3wyb4/Ejemplo_Iterador.zip?dl=1">Download the example project</a> used in this tutorial.</p>



<h3 class="wp-block-heading"><strong>Using Iterator</strong></h3>



<p>In order to implement this behaviour in our classes so they can use the&nbsp;<code>For Each… Next</code>&nbsp;schema, the real work is in the&nbsp;Iterator&nbsp;Class Interface. Under this interface, we can find the definition of the methods that are needed to implement the class and that are responsible for advancing every item of the collection, and for returning the current value of the collection:</p>



<ul class="wp-block-list"><li><strong>MoveNext</strong>. Moves to the next element of the Collection, returning <code>True</code> if it has not reached the end of the collection, <code>False</code>when reached past the last element in the Collection.</li><li><strong>Value</strong>&nbsp;This is the Class Interface method that returns the current element of the collection as an Variant data type.</li></ul>



<p>From this, it is easy to conclude that our iterable classes need to implement a counter (as a Property) that updates its value for every&nbsp;<code>MoveNext</code>&nbsp;invocation. We will also use this property to check if it has reached the maximum number of elements. Also, be aware that the property has to be initialized using the value -1 (that is, as an invalid value), as it is stated in the documentation that we have to invoke <code>MoveNext</code> before we can get the first iterable element from the collection.</p>



<p>On the other hand, we will handle all the error cases during the iteration process raising <code>IteratorException</code>.</p>



<p>In order to see all this in action, let’s run through an example using the <code>Person</code>class in charge to store in their instances all the possible postal addresses associated with a person.</p>



<p>Let’s start defining our<code>Person</code>class as a simple set of Properties:</p>



<ul class="wp-block-list"><li>firstName As String</li><li>middleName As String</li><li>secondName As String</li></ul>



<p>Also, add the Property in charge of referencing all the postal addresses assigned to the Person, using an Array:</p>



<ul class="wp-block-list"><li>postalAddresses() As PostalAdress</li></ul>



<p>With that, we have finished our Person class definition. It’s very simple but works for the purpose of this example.</p>



<p>We will also create a simple (and incomplete) definition for the PostalAddress class using a set of public properties so they serve the purpose of the main topic.</p>



<ul class="wp-block-list"><li>street As Text</li><li>streetNumber As Integer</li><li>streetFlat As Integer</li></ul>



<h3 class="wp-block-heading"><strong>Creating an Iterator</strong></h3>



<p>Once we have the two classes needed for our example (Person and PostalAddress), we can define the Class responsible for acting as the iterator; that is, returning every element from the collection for the associated class. In this example we will return every object of the PostalAddress that is associated with an instance of the Person class. In fact, the Iterator is responsible of doing all the hard work, moving forward the counter to the next item, and returning the object or value when requested.</p>



<p>Let’s create a new Class with the name<code>PersonIterator</code>. In this case, use the associated Inspector to select the<code>Choose</code>button next to the<code>Interfaces</code>label. This will display a window containing all the available Class Interfaces. Select the checkbox for<code>Iterator</code>and confirm the selection.</p>



<p>The IDE will now add the following defined methods for the selected class interface:</p>



<ul class="wp-block-list"><li><strong>MoveNext</strong>. The documentation states that this is the method invoked before calling the Value method in order to get a new value. In fact, in the method implementation we have to write the code that increases the counter value, and also checks if the counter value is over the available quantity of items. Meaning, we have to add a<code>counter</code>Property to our class, and initialize it with the value -1.</li><li><strong>Value</strong>. This is the method that will be called every time we need to get a new value. In our example, this will return a new PostalAddress object from the available items.</li></ul>



<p>Thus, the implementation for the<code>MoveNext</code>method could be the following:</p>



<pre class="wp-block-preformatted">counter = counter + 1</pre>



<p>But the method signature and the class interface documentation states that the method has to return a boolean value of<code>True</code>if there are remaining available items to iterate and<code>False</code>if the quantity of iterable items has been surpassed. In the case we should raise an exception in order to point this out.</p>



<p>For example, our class could check if the counter doesn’t exceed the quantity of items stored by the PostalAddresses Array, returning the corresponding boolean value.</p>



<p>But let’s fill in some holes before writing the final implementation for the<code>MoveNext</code>method. First, let’s add some more needed properties:</p>



<ul class="wp-block-list"><li><strong>maxPostalAddresses As Integer</strong>. This will be responsible for storing the number of elements available under the PostalAddress Array.</li><li><strong>source As Person</strong>. This will be in charge of saving the reference to the Person object it has to iterate.</li><li>The Calculated Property&nbsp;<strong>valid as Boolean</strong>. We will use the<code>Get</code>method from this calculated property to know if the PostalAddress Array has been modified during the iteration of the object, returning<code>False</code> when this is the case. In fact, this is the code for the<code>Get</code>method:</li></ul>



<pre class="wp-block-preformatted">Return if(source.postalAddresses.LastIndex = maxPostalAddresses, True, false)</pre>



<p>Next, we will add the<code>Constructor</code>method to the class using this signature:</p>



<pre class="wp-block-preformatted">Constructor( value As Person )</pre>



<p>and the following code for the method:</p>



<pre class="wp-block-preformatted">source = value
maxPostalAddresses = value.postalAddresses.LastIndex</pre>



<p>This initialized the previously declared property’s values with the reference to the Person object that we will use to iterate over, and the number of elements included in the Array when we initialize the class. Thus, the number of original items that we will use to check if it has been modified during the iteration process.</p>



<p>Now we can move back to the<code>MoveNext</code>method to write the final implementation:</p>



<pre class="wp-block-preformatted">If valid Then
  counter = counter + 1
  Return If(counter &lt;= source.postalAddresses.Ubound, True, False)
Else
&nbsp; Var e As New IteratorException
  e.Reason = "Invalid Data"
  Raise e
End If</pre>



<p>Inside the method implementation we will also check if the object has been modified during the iteration, returning the corresponding value:</p>



<pre class="wp-block-preformatted">If valid Then
  Return source.postalAddresses(counter)
Else
  Var e As New IteratorException
  e.Reason = "Invalid Data"
  Raise e
End If</pre>



<p>As you can see, the Value method will return the PostalAddress item from the Person array, using the value of the Counter property as Index.</p>



<p><strong>Creating the Iterable Class</strong></p>



<p>Now we have to create the iterable class itself. Add a new class to the project with the name <code>IterablePerson</code> and make it a subclass from the Person class. Write this data type in the<code>Super</code>field of the Inspector Panel. In addition, this class will be the one that implements the class interface&nbsp;Iterable, so you have to push on the<code>Choose</code>button associated with the<code>Interfaces</code>label in order to select and confirm the addition of the corresponding methods. In fact, is just one method:</p>



<pre class="wp-block-preformatted">Iterator() As Iterator</pre>



<p>And this is the code for that method:</p>



<pre class="wp-block-preformatted">Var it As New iterablePerson(Self)
Return it</pre>



<p>Now we have all the definitions we need for the subclass: we get a new <code>IterablePerson</code>instance passing as a parameter the iterable object (a Person subclass). Finally, we return the iterator we got and that will be used inside the<code>For Each… Next</code>loop.</p>



<h3 class="wp-block-heading"><strong>Putting It All Together</strong></h3>



<p>Armed with all the needed classes for our example, we can finally put it all into practice. For this, add a&nbsp;<a href="http://developer.xojo.com/listbox">ListBox</a>&nbsp;in the main project Window (<code>Window1</code>). This is the control where we will add as many rows as there are postal addresses associated with an instance of the Person class used for the example. For this, add a button to the window with the Action event and write the following code in the resulting Code Editor:</p>



<pre class="wp-block-preformatted">Var p As New IterablePerson
p.firstName = "Juan"
p.middleName = "Sin Miedo"
p.secondName = "De Nada"
Var d As New PostalAddress
d.street = "Juan de Urbieta"
d.streetNumber = 6
d.streetFlat = 1
p.postalAddresses.Add(d)
d = New PostalAddress
d.street = "Mi calle bonita"
d.streetNumber = 8
d.streetFlat = 3
p.postalAddresses.Add(d)
d = New PostalAddress
d.street = "Princesa"
d.streetNumber = 5
d.streetFlat = 5
p.postalAddresses.Add(d)
For Each s As PostalAddress In p
  Listbox1.AddRow(s.street + ", " + s.streetNumber.ToString + " Piso: " + s.streetFlat.ToString)
Next</pre>



<p>Run the project, push the button and you will see how the<code>For Each… Next</code>loop iterates every postal address associated with the Person object. This is a more concise, stylish and OOP way of doing things when compared with the classic<code>For… Next</code>loop, which requires getting the upper value (or limit) and use a variable as index to get every collection object we are interested in.</p>



<p>*This blog post was <a href="https://blog.xojo.com/2017/12/13/make-your-own-classes-iterables/">originally written</a> by Javier Menendez in 2017 and has been updated for Xojo API 2.0 by Wayne Golding.</p>



<p><em>Wayne Golding has been a Xojo developer since 2005 and is a Xojo MVP. He operates the IT Company <a href="http://www.axisdirect.nz">Axis Direct Ltd </a>which primarily develops applications using Xojo that integrate with Xero www.xero.com. Wayne’s hobby is robotics where he uses Xojo to build applications for his Raspberry Pi, often implementing IoT for remote control.</em></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Pump Up Your Xojo Development</title>
		<link>https://blog.xojo.com/2021/05/03/the-xojo-extras-store/</link>
		
		<dc:creator><![CDATA[Dana Brown]]></dc:creator>
		<pubDate>Mon, 03 May 2021 09:12:00 +0000</pubDate>
				<category><![CDATA[Community]]></category>
		<category><![CDATA[Database]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[Learning]]></category>
		<category><![CDATA[Networking]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[AprendeXojo]]></category>
		<category><![CDATA[Monkeybread Software]]></category>
		<category><![CDATA[Ohanaware]]></category>
		<category><![CDATA[Third Party]]></category>
		<category><![CDATA[xDev Magazine]]></category>
		<category><![CDATA[Xojo Programming Language]]></category>
		<guid isPermaLink="false">https://blog.xojo.com/?p=7746</guid>

					<description><![CDATA[During this week's May Sale all Xojo licenses and everything in the Xojo Extras Store are discounted 20%! What kind of deals and extras are out there? Let's check them out! There are 5 categories of Xojo Extras: Developer Tools, User Interface, Database, Distribution and Learning.]]></description>
										<content:encoded><![CDATA[
<p>During this week&#8217;s May Sale all Xojo licenses and everything in the Xojo Extras Store are discounted 20%! What kind of deals and extras are out there? Let&#8217;s check them out. There are 5 categories of Xojo Extras: Developer Tools, User Interface, Database, Distribution and Learning.</p>



<h2 class="wp-block-heading"><strong>Developer Tools</strong></h2>



<p><strong>piDog DataView</strong> is a fast and flexible list viewer and includes one year of updates.</p>



<p><strong>Markdown Parser</strong> for Xojo is a class that allows you to implement the ability to parse Markdown source text into HTML + the provided CSS styles, so it can be presented on the fly over an HTML control for its use &#8220;as-is&#8221;, as a starting point for invoices, reports, templates or document conversion. </p>



<p>If you don&#8217;t have anything from Monkeybread Software, then this is a great deal for you! Everything is 20% off from the <strong>Complete Plugin Set</strong>, which includes 54,000+ functions, to <strong>DynaPDF</strong> for creating and editing PDF documents and more.</p>



<p><strong>Mime Parser</strong> is a class for parsing emails.</p>



<p>The <strong>OMP Plugin</strong> allows you to easily parse Microsoft Outlook Structured Storage (.MSG) files cross-platform from Xojo.</p>



<p>Also offered is a <strong>Spell Checker Class</strong> to easily spell check text.</p>



<h2 class="wp-block-heading">User Interface</h2>



<p><strong>ARWaitingView</strong> is a class to prevent the user from navigating the interface while something is downloading or doing a long process. </p>



<p><strong>AXControlGrid</strong> is a complete and powerful Xojo desktop UI component for macOS and Windows that it makes possible to put Canvas-based controls in a Page or a series of Pages of a given size and, optionally, their associated captions.</p>



<p><strong>AXImageCanvas </strong>greatly simplifies the task of displaying a Picture with the ability to correctly display the image maintaining its original aspect ratio, and keeping the full resolution of the picture and reference to the original FolderItem.</p>



<p><strong>AXNumValidatedTF</strong> is a Xojo TextField subclass (32/64 bits) for Windows and macOS allowing the input validation of a defined numeric range, using the system Locale settings for decimal and grouping text formatting.</p>



<p>Antonio Rinaldi offers <strong>Doughnut</strong>, which is an extension for iOSGraphics to draw circular graphs. Additionally, <strong>iOSTableViewExtended</strong> is a subclass that adds useful features including: swipe to reload, table header and footer, customer section header and footer, contextual menus, side index, TextEdit fix and more.</p>



<p><strong>GraffitiSuite</strong> All Access, Desktop and Web are on sale! They are a collection of custom components for Xojo Desktop and Web. </p>



<p>MBS <strong>ChartDirector</strong> lets you create professional charts in Xojo, with 30 chart and gauge types.</p>



<p><strong>RubberViews</strong> from Match Software maintains the place and relative size of every control when a Window or Container Control is resized. They also offer Window Placement and Screen Extensions that are modules that let you manage windows with greater control.</p>



<h2 class="wp-block-heading">Database</h2>



<p><strong>DataViewer Component </strong>is a collection of objects for Xojo that can easily incorporate into your own projects to give SQL Query and DML functionality for SQLite and MySQL databases along with Data Export facilities. Full source code edition also available.</p>



<p>The<strong> MBS SQL Plugin</strong> is an alternative database interface to Xojo that gives access to SQL databases including Oracle, Microsoft SQL Server, DB2, Sybase, Informix, InterBase/Firebird, SQLBase, MySQL, PostgreSQL, ODBC and SQLite. Also available is the <strong>MBS SQLite Extension</strong> is a plug-in for cubeSQL Server, a plug-in for SQLite Manager (sqlabs) and an extension for SQLite that you can use in all SQLite-based database engines, including the SQLiteDatabase class in Xojo.</p>



<p><strong>SQLVue</strong> is the fast and easy way to manage your SQLite databases.</p>



<h2 class="wp-block-heading">Distribution</h2>



<p><strong>App Wrapper </strong>from Ohanaware simplified the process of preparing applications for submission to the Mac App Store and deploying on websites. Get a 30-day or a 1 year single user or team update plan during this limited time offer.</p>



<p><strong>BoxedApp Packer</strong> helps Xojo developers prepare a single executable file that contains all required files a Xojo application needs.</p>



<p>The <strong>GuancheMOS</strong> plug-in is a serial number creation and validation Engine. Also available is <strong>GuancheID</strong>, the easiest way to get a unique ID for macOS and Windows based computers, so you can use it in combination with GuancheMOS or your own software licensing scheme to make sure your software only runs on the computer the license has been generated for.</p>



<p><strong>Quick License Manager</strong> protects your Xojo Windows application with licensing for trials, perpetual or subscription-based licenses.</p>



<h2 class="wp-block-heading"><strong>Learning</strong></h2>



<p><strong>AprendeXojo</strong> has 2 Spanish-language ebooks in the store available for $20 each during the sale:&nbsp;<em>Programación Multiplataforma Xojo</em>&nbsp;and&nbsp;<em>SQLite</em>.</p>



<p><strong>xDev Magazine</strong> is an&nbsp;independent bimonthly publication focused on educating Xojo users through instruction, tutorials and programming. Score a 1 year subscription during the sale for just $40!</p>



<h2 class="wp-block-heading">Shop Now</h2>



<p>The <a href="https://www.xojo.com/store">Xojo Extras store</a> has something for every kind of Xojo developer, whether you are learning something new or looking to save some time implementing something tricky. Take a look now to see what can help make your development life easier! The Xojo May Sale runs until midnight (CT) Friday, May 7th.  </p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Drawing User Interface Controls with DrawInto</title>
		<link>https://blog.xojo.com/2019/10/21/drawing-user-interface-controls-with-drawinto/</link>
		
		<dc:creator><![CDATA[Javier Menendez]]></dc:creator>
		<pubDate>Mon, 21 Oct 2019 10:00:08 +0000</pubDate>
				<category><![CDATA[General]]></category>
		<category><![CDATA[Learning]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[AprendeXojo]]></category>
		<category><![CDATA[Object-Oriented]]></category>
		<category><![CDATA[OOP]]></category>
		<category><![CDATA[Xojo Programming Language]]></category>
		<guid isPermaLink="false">https://blog.xojo.com/?p=6090</guid>

					<description><![CDATA[As an Object Oriented Programming language (OOP), Xojo&#8217;s data types, especially the non-primitive ones, use or can use a Class hierarchy. This means that one&#8230;]]></description>
										<content:encoded><![CDATA[<p>As an Object Oriented Programming language (<b>OOP</b>), Xojo&#8217;s data types, especially the non-primitive ones, use or can use a <b>Class hierarchy</b>. This means that one class, either included by default in the Xojo Framework or created from scratch, can act as a base or root class for other classes based upon them.<span id="more-6090"></span></p>
<p>The main advantage of a class hierarchy is that all the derived classes share the same set of methods, properties and events declared in their upper classes (those not set with a Private scope) and, thus, we can make our code more flexible, easier to maintain and get more dynamism from our apps at run time thanks to the <b>Casting</b> of types.</p>
<p style="text-align: center;"><a href="https://drive.google.com/open?id=1FhKmAhYkJYvgagtGuQCK3-67zvdrY78E">Download the Demo Project</a></p>
<p>What is this all about? Very simple. For the subject at hand, every graphic control or User Interface (UI) control included in the Desktop Xojo Framework share the common base class <code>RectControl</code> (this one based, at the same time, on the base class <code>Control</code>); and among the methods available in that class we can find <code>DrawInto</code>.</p>
<p>This means that every UI control has the ability to <em>draw</em> itself in any given <b>Graphic</b> context. However, when drawn in the target graphic context they will lose their usual response to any user interaction. That is, they would be a mere graphic representation of themselves; something that is really useful in many cases. For example, this is the technique used for drawing all the contents of a given page or range of pages in <a href="https://www.aprendexojo.com/shop/axcontrolgrid-2/"><code>AXControlGrid</code></a>.</p>
<p>As you can see in the Xojo documentation, the <code>DrawInto</code> signature is as follows:</p>
<pre>RectControl.<b>DrawInto(g as Graphics,x as Integer, y as Integer)</b></pre>
<ul>
<li>The first thing you can see is that the method is called on the instance (UI control) we want to draw into a given graphic context.</li>
<li>Second, the first argument we provide in the <code>DrawInto</code> method is the <b>graphic context</b> we want to use to draw the control. As you probably know, we can get such graphic context from several kind of classes, for example <b>Picture</b>. In addition, the target graphic context can be of any size we need it to be!</li>
<li>Third, the <code>x</code> and <code>y</code> arguments are the top-left coordinates used to draw the control in the target graphic context and, of course, these coordinates should be in the range of the width and height of the target graphic context passed as the first argument.</li>
</ul>
<p>For most of the cases, you don&#8217;t need to do anything special to use this method in your own classes. That means that the object calling the <code>DrawInto</code> method will draw itself using the same code you put in its <b>Paint</b> event. The unique difference in this case is that the Paint event will use the <b>external</b> graphic context and receive <code>x</code> and <code>y</code> coordinates that may be (or may not be) outside its own width and height range.</p>
<p>But there might be other times you don&#8217;t want to draw the control using the same code as the one written in the Paint event. Maybe because you need a more refined representation of the control or you simply want to leave out some details that are useful when the control is drawn as part of the UI but not when it is printed or used in a PDF document. In addition, it can be the case that inside the Paint event you may need to do some calculations on the <code>x</code> and <code>y</code> coordinates that would not make sense (or would be out of range) when done on an external graphic context.</p>
<p>After all, the key about using&nbsp;<code>DrawInto</code> is this:</p>
<ul>
<li>When a instance calls this method, what really happens is the code in the <code>Paint</code> event will be executed on the new graphic context received as argument. Of course, if you have not implemented the Paint event yourself, then Xojo will execute the default implementation.</li>
</ul>
<h2>Customizing the DrawInto Behavior</h2>
<p>In other cases, especially on Windows, it is possible that we won&#8217;t get the right drawing when using the default implementation of the DrawInto method. If you find yourself in this situation, you can fix it by overwriting the <code>DrawInto</code> method for your own UI classes.</p>
<p>When you do that, evey time you call this method it will execute the code you included in it, and that means that you will be in control of the received graphic context as parameter, its size and origin coordinates, and especially the drawing operations available through the methods from the <code>Graphics</code> class.</p>
<p>The way to implement (overwrite) the <code>DrawInto</code> method in your own UI controls (derived from the <code>RectControl</code> class) is as simple as for any other overwritten method or Event in your own subclasses.</p>
<p>With your class selected in the Xojo IDE Navigator, access the contextual menu to select the <code>Add to "instanceName" &gt; Method</code> option, choosing the <code>DrawInto(graphics as Graphics, Left as Integer, Top as Integer)</code> item in the Name field popup from the Inspector Panel.</p>
<p>Once selected, you will see that the associated Code Editor will contain by default a call to the same method signature on the <b>Super</b> class. This gives the class the control is based on the oportunity to drawn itself.</p>
<p>From a practical point of view, you will probably want to delete that call when you don&#8217;t want to use the same kind of representation for the control on the external graphic context when that is drawn in the UI. In addition you will save some drawing time thus improving the overall speed.</p>
<p>Now you only need to include in the <code>DrawInto</code> method the code you want to use in order to paint your control on the received context and you&#8217;ll be set! From that point on, every time you call:</p>
<pre>aRectControlInstance.DrawInto( tContext, 100, 100 )</pre>
<p>Xojo will execute the code put in your own implementation of the <code>DrawInto</code> method, and that means more flexibility and control about what is drawn and how it is drawn; especially if your UI control is going to be used both in macOS and Windows.</p>
<p><img fetchpriority="high" decoding="async" class="size-medium wp-image-6092 aligncenter" src="https://blog.xojo.com/wp-content/uploads/2019/10/DrawIntoOverload-Run-300x266.png" alt="" width="300" height="266" srcset="https://blog.xojo.com/wp-content/uploads/2019/10/DrawIntoOverload-Run-300x266.png 300w, https://blog.xojo.com/wp-content/uploads/2019/10/DrawIntoOverload-Run-768x682.png 768w, https://blog.xojo.com/wp-content/uploads/2019/10/DrawIntoOverload-Run.png 964w" sizes="(max-width: 300px) 100vw, 300px" /></p>
<h2>DrawInto in Practice</h2>
<p>In order to see how everything works, let&#8217;s create a simple Xojo Desktop project where we will make use of our own <code>DrawInto</code> implementation on one Canvas based class.</p>
<p>Create a new Xojo Desktop project, drag the <code>Canvas</code> control from the Library panel into the Navigator.</p>
<p>Next, and with the new Canvas class selected, access the Inspector Panel to set the following values:</p>
<ul>
<li><b>Name</b>: MyOwnControl</li>
<li><b>Super</b>: Canvas</li>
</ul>
<p>With our new class still selected in the Navigator, add the <b>Paint</b> Event. For that, you may access the contextual menu and choose the <code>Add to "MyOwnControl" &gt; Event Handler…"</code> option, selecting the Paint entry afterwards in the resulting window.</p>
<p>Then, write the following code in the Code Editor associated with the Paint Event:</p>
<pre>g.DrawingColor = &amp;cff0000
g.FillRectangle(0,0,g.Width, g.Height)</pre>
<p>Nothing especially significant here. As you can see, it sets the foreground color to Red and then fills all the control area using the <code>FillRect</code> method on the control graphic context.</p>
<p>Now it is time to overwrite the <code>DrawInto</code> method. With our class still selected in the Navigator, add the <code>DrawInto</code> method and write the following code in the associated Code Editor:</p>
<pre>// Uncomment the following line of code to see what happens!
// In that Case, the control first executes the code from the Paint Event,
// executing the drawing code from the overriden DrawInto method afterwards.

//super.DrawInto(graphics, left, top)

Var s As String = "From DrawInto"

Var sLen As Double = graphics.TextWidth( s ) / 2

graphics.DrawingColor = &amp;c00FF00

// No matter what the "Left" and "Top" values are, we don't use them
// for our custom drawing.

graphics.DrawRectangle(0,0, graphics.Width, graphics.Height)

graphics.DrawingColor = &amp;c000000
graphics.PenSize = 1
graphics.AntiAlias = True

graphics.DrawText("From DrawInto", (graphics.Width/2) - sLen, (graphics.Height / 2) )</pre>
<p>Basically, what we are doing here is substantially changing the graphical representation of the control between what is seen when it is drawn in the user interface through the Paint Event and what we will get when calling the <code>DrawInto</code> method on the Control instance.</p>
<p>In the second case, it will draw a non-filled green rectangle using the same width and height that the control itself, writting the string &#8220;From DrawInto&#8221; centered in the control area.</p>
<p>You can see that the <code>Super.DrawInto(graphics, Left, Top)</code> code line is commented. After the initial running of the demo app, you can uncoment that line if you want in order to see how it changes the drawing when the <code>Super</code> class is called (remember, that means executing the code on the Paint event for the Class).</p>
<h2>Putting it all Together</h2>
<p>With our class already finished, it is time to start the layout of our minimal user interface. Something really simple. Choose the <code>Window1</code> window in order to access the Layout Editor. Then drag the <code>MyOwnControl</code> item from the Project Broswer into the the Window1 area in the Layout Editor. With that action we will have added a new instance from our class. The resulting name for the instance will be <code>MyOwnControl1</code>.</p>
<p><iframe title="DrawInto: Dibujado personalizado de controles en un Contexto Gráfico" width="500" height="375" src="https://www.youtube.com/embed/ehyTLCuMIsM?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe></p>
<p>Then, drag a standard Canvas control from the Library panel into the <code>Window1</code> area in the Layout Editor. This action will result in the creation of a new Canvas instance with the by-default name <code>Canvas1</code>.</p>
<p>Lastly, add a new button from the Library into the <code>Window1</code> area in the Layout Editor and use the Inspector Panel to set its name to <code>pbDrawInto</code> and its caption to &#8220;DrawInto&#8221;. This will be the button in charge to order our <code>MyOwnControl1</code> instance to draw itself in the graphic context provided by <code>Canvas1</code>.</p>
<p>For that, and with the <code>pbDrawInto</code> selected, add an <code>Action</code> Event Handler and write the following code in the associated Code Editor:</p>
<pre>// We create a Picture we can use to give a Graphics context to the
// Canvas1 backdrop (it would be "Nil" by default)

Var p As New Picture( canvas1.Width, Canvas1.Height, 32 )

canvas1.Backdrop = p

// And we instruct our "MyOwnControl" instance to draw itself on the
// "Canvas1" graphics context.

MyOwnControl1.DrawInto(Canvas1.Backdrop.Graphics,0,0)</pre>
<p>If you want, you can layout your user interface like the one displayed in the following screenshot:</p>
<p><img decoding="async" class="size-medium wp-image-6091 aligncenter" src="https://blog.xojo.com/wp-content/uploads/2019/10/DrawIntoOverload-IDE-300x267.png" alt="" width="300" height="267" srcset="https://blog.xojo.com/wp-content/uploads/2019/10/DrawIntoOverload-IDE-300x267.png 300w, https://blog.xojo.com/wp-content/uploads/2019/10/DrawIntoOverload-IDE-768x684.png 768w, https://blog.xojo.com/wp-content/uploads/2019/10/DrawIntoOverload-IDE.png 892w" sizes="(max-width: 300px) 100vw, 300px" /></p>
<p>Now we have our app ready to test. Press the <code>Run</code> button in the IDE and verify the results you get between what is drawn by the Paint Event and what you get when you click on the button labeled &#8220;DrawInto&#8221;.</p>
<p><em data-rich-text-format-boundary="true">Javier Rodri­guez has been&nbsp;the Xojo Spanish&nbsp;Evangelist since 2008, he’s also a Developer, Consultant and Trainer who&nbsp;has be using&nbsp;Xojo since 1998. He manages&nbsp;<a href="http://www.aprendexojo.com">AprendeXojo.com</a> and is the developer behind the GuancheMOS plug-in for Xojo Developers, GuancheID, AXControlGrid, AXImageCanvas, Markdown Parser for Xojo, and HTMLColorizer for Xojo among others.</em></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Dealing with Pictures and Databases: AXImageCanvas</title>
		<link>https://blog.xojo.com/2019/08/28/dealing-with-pictures-and-databases-aximagecanvas/</link>
		
		<dc:creator><![CDATA[Javier Menendez]]></dc:creator>
		<pubDate>Wed, 28 Aug 2019 15:14:31 +0000</pubDate>
				<category><![CDATA[Cross-Platform]]></category>
		<category><![CDATA[Database]]></category>
		<category><![CDATA[Desktop]]></category>
		<category><![CDATA[AprendeXojo]]></category>
		<category><![CDATA[DarkMode]]></category>
		<category><![CDATA[Third Party]]></category>
		<category><![CDATA[Xojo Programming Language]]></category>
		<guid isPermaLink="false">https://blog.xojo.com/?p=6004</guid>

					<description><![CDATA[How to save pictures in a database is without doubt one of the more frequent questions I&#8217;m asked about. I hear this from Xojo newcomers,&#8230;]]></description>
										<content:encoded><![CDATA[
<p><br>How to save pictures in a database is without doubt one of the more frequent questions I&#8217;m asked about. I hear this from Xojo newcomers, and not so newcomers, just as much as I do from people using other development environments. That&#8217;s why I decided to put all the frequent questions and operations related to the Canvas and Pictures on the drawing board …&nbsp;and AXImageCanvas is the result of that!</p>



<p>Things like drag and drop (from other sources and also to other sources), undoing the picture assigned, moving the control instances around the parent <strong>RectControl</strong> (or Window), reacting to <strong>DarkMode</strong> changes on macOS, and properly resizing the picture so it fits in the Canvas area while keeping its original aspect ratio are implemented in AXImageCanvas, among other features.</p>



<p>Of course, AXImageCanvas abstracts the user from everything related to the usual <strong>CRUD</strong> operations associated with a Database backend: Creating a new Record, Retrieving the Picture from a record, Updating the Picture of an existing record, and Deleting the Picture for the designated record. All of this trying to mimic the easiness of use we are used to when using the standard Xojo framework itself.</p>



<p>The user only needs to assign, paste or drop the Picture to display …&nbsp;and AXImageCanvas takes care of the rest.</p>



<p>So, for example, the binding behavior to a database is implemented in a way that tries to emulate one of the most appreciated features for Xojo users in the past: DataControl.</p>



<p>The user only needs to set the database instance they want to use (it may be a <strong>MySQL/MariaDB</strong>, <strong>PostgreSQL</strong> or <strong>SQLite</strong> database instance), the name of the table they want to use, the name of the column to store the pictures and (optionally) the name of the column to store the original path to a picture read from a <strong>FolderItem</strong>.</p>



<p>Even if there is only set the column to store the original Picture FolderItem path, then it will not save the Picture data itself, and it will recover the picture later to display based on the saved path information. This alleviates the database data overload for some use cases, when the developer of a solution prefers not to store the picture data in the database itself, just the path pointing to it.</p>



<p>The class is also smart enough to abstract the user from all the SQL queries it would have to write in function of the database engine used. It is completely transparent, as it is the navigation through the database records even if their IDs are not consecutive (this is a mandatory requirement: the table has to have an ID column).</p>



<p>The logic put in the class also gathers information about the database table itself, if for example it only has the two columns set to the instance (Picture column and Picture source path column; plus the mandatory ID column), then the Delete Record action will effectively delete the record from the assigned database table; otherwise, if the table has more columns, it will NOT delete the record, because it&#8217;s something you probably wouldn&#8217;t want to do … and it simply updates the displayed record to empty (nullify) the information for the Picture and (optionally) the Picture Path columns, keeping thus the rest of the record data intact.</p>



<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="AXImageCanvas" width="500" height="375" src="https://www.youtube.com/embed/IhbE5AdhiOE?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p>As for PostgreSQL database, there are two paths that can be taken regarding storing Pictures. We can say that the first one is the usual path, storing the Picture data itself in a column table (valid for data not exceeding 1 GB) and through Large Objects (<strong>pg_largeobject</strong>) via the previous acquisition of an <strong>OID</strong> value. AXImageCanvas uses the first technique.</p>



<p>In addition, it also properly deals with record navigation for all the supported databases engines even if the records IDs are not consecutive; and when the records navigation is set to the &#8220;wrap around&#8221; mode, it does it also correctly for all of the supported databases engines.</p>



<p>Another common quirk it deals with answers one of the usual questions: Database Server disconnections due to the timeout. AXImageCanvas takes care of it when the connection is lost and if it is something not transient, then properly raises the exception so it can be cached by the application logic.</p>



<p>But one of the most important things is that everything can be configurable through the properties shown in the <strong>Inspector Panel</strong> of the <strong>Xojo IDE</strong>, for the maximum simplicity in the AXImageCanvas setup; and also via code to give the maximum flexibility at runtime when the application is in use, so it can react to things like changing the database engine, or simply disabling things like moving or resizing the control among others.</p>



<h2 class="wp-block-heading">Pictures and Drawing Speed</h2>



<p>What about redrawing concerns? This is something that AXImageCanvas also takes care of. It applies several image caching techniques while keeping the set Picture at its full resolution.</p>



<p>This allows, for example, abstracting you from what you can see displayed in the AXImageCanvas control at the desired size, from what you can do with the original Picture itself: from previewing it (something you can do simply pressing the space bar when the AXImageCanvas has the focus), getting more information about the Picture and (optionally) original FolderItem (press the &#8216;I&#8217; key for that while the AXImageCanvas instance has the focus), or any other operation your app would want to do, like for example exporting the picture to other format.</p>



<p>In this sense, it also takes into consideration the operations done with the control itself during the redrawing or control size changes, minimizing the writing to the Database to the strictly necessary (always, of course, there is a database associated with the instance).</p>



<h2 class="wp-block-heading">The Goals</h2>



<p>To summarize, AXImageCanvas tries to be the simplest solution when dealing with Pictures and (optionally) its storage on databases. Just drop as many instances as you need in your layout, set the behaviour through the Inspector Panel Properties (even setting the initial picture to display) …&nbsp;and you&#8217;re done! The best part is that the behaviour will be the same for Windows, macOS and Linux deployed Desktop applications, both in 32 and 64 bits.</p>



<p>Of course, you can <a href="https://www.dropbox.com/s/4rc208njqel4o7g/AXImageCanvas%201.0.zip?dl=1">download the Xojo Project Example</a> and try it yourself! This is a fully functional demo without restrictions. I&#8217;d be glad to hear from you about suggestions or features you would want to be included for better fit your needs!</p>



<p><em>Javier Rodri­guez has been&nbsp;the Xojo Spanish&nbsp;Evangelist since 2008, he’s also a Developer, Consultant and Trainer who&nbsp;has be using&nbsp;Xojo since 1998. He manages&nbsp;<a href="http://www.aprendexojo.com">AprendeXojo.com</a> and is the developer behind the GuancheMOS plug-in for Xojo Developers, GuancheID, AXImageCanvas, Markdown Parser for Xojo, HTMLColorizer for Xojo and the Snippery app, among others.</em></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Canvas: How to Create Custom UI Controls</title>
		<link>https://blog.xojo.com/2019/04/15/canvas-how-to-create-custom-ui-controls/</link>
		
		<dc:creator><![CDATA[Javier Menendez]]></dc:creator>
		<pubDate>Mon, 15 Apr 2019 10:00:47 +0000</pubDate>
				<category><![CDATA[Cross-Platform]]></category>
		<category><![CDATA[Learning]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[AprendeXojo]]></category>
		<category><![CDATA[Beginner Tips]]></category>
		<category><![CDATA[Canvas]]></category>
		<category><![CDATA[iOSCanvas]]></category>
		<category><![CDATA[Multi-Platform Development]]></category>
		<category><![CDATA[UI]]></category>
		<category><![CDATA[User Interface]]></category>
		<category><![CDATA[WebCanvas]]></category>
		<category><![CDATA[Xojo Programming Language]]></category>
		<guid isPermaLink="false">https://blog.xojo.com/?p=5649</guid>

					<description><![CDATA[Sometimes, subclassing the available controls is the answer to add specific behaviors you need. But what happen when none of the controls offer what you need, whether visually or functionally? The answer is the Canvas class (for Desktop projects), WebCanvas class (for Web projects) and iOSCanvas class for iPhone and iPad devices. ]]></description>
										<content:encoded><![CDATA[<p>Xojo includes a good amount of <b>UI</b> controls available from the Library for <strong>Desktop</strong>, <strong>Web</strong>, <strong>iOS</strong> and <strong>Raspberry Pi</strong> targets. These are the pieces that allow you to layout the user interface of your apps: properties, methods and events that, when combined, define the specific behavior of the project at hand.</p>
<p>Sometimes, subclassing the available controls is the answer to add specific behaviors you need. But what happen when none of the controls offer what you need, whether visually or functionally? The answer is the Canvas class (for Desktop projects), WebCanvas class (for Web projects) and iOSCanvas class for iPhone and iPad devices. But how do you create your own UI controls from scratch? Read on to learn&#8230;<span id="more-5649"></span></p>
<p>Before starting with this basic tutorial about customized UI controls, there is much more to take into consideration about providing the same behavior on your designed controls for multiplatform deployments. For example, in the case of desktop projects, we should add to the mix some things like <strong>HiDPI</strong> / <strong>Retina</strong> detection and adaptation on the fly (specially in the case of Windows deployment, with multiple dpi / Windows OS version combinations), and <strong>Dark Mode</strong> support for macOS. A well as other performance hints and differences when it&#8217;s about doing desktop multiplatform layouts; for example, when to set the <code>Transparent</code> or <code>DoubleBuffer</code> properties to <code>True</code> or not.</p>
<p>As the name implies, the Canvas control acts like a painting canvas and you can set its look for all the supported states based on the available events. This is done through the <code>Paint</code> Event and all the <a href="http://documentation.xojo.com/api/graphics/graphics.html"><b>Graphic</b></a> classes availables in the Framework. In fact, the <b>Paint</b> event provides as a parameter the graphical context (canvas height and width) you can paint on. In addition, you can combine these graphic classes (or completely substitute them) with any prepared <b>Picture</b> of your choice as the customize control background (<a href="http://documentation.xojo.com/getting_started/using_the_ide/image_set_editor.html"><b>ImageSet</b></a> recommended, so it supports all the needed resolutions based on display dpi). In addition, and as you can do with the drawing via the Graphic class and functions, you can choose to use a different <a href="http://documentation.xojo.com/api/graphics/picture.html"><b>Picture</b></a> as the control background based on several events, for example, when the mouse pointer is entering or exiting the control limits in a Desktop or Web app, or as response to the user clicking on it.</p>
<h2>Canvas: A matter of Events</h2>
<p>The <a href="http://documentation.xojo.com/api/deprecated/canvas.html">Canvas class</a> provides all the needed Events you probably would want to implement in order to react to the user interaction. These are listed and described in the available documentation online and as part of the Xojo IDE interactive Help.</p>
<p>While you can drag and drop a Canvas instance directly to your project layout window or view, implementing and writing the code associated with  any of the available Events, the recommended way to go is to create your own subclass taking as its parent the Canvas class. This way, you can implement and fine-tune every aspect that makes you control unique and, most importantly, re-use your customized UI controls as many times you want both in current and future projects (or even <a href="https://documentation.xojo.com/Resources:Free_Source_Code_and_Tools">offer them</a> to the Xojo community or <a href="https://www.xojo.com/store/#addons">sell them</a> to other developers!).</p>
<p>As you probably already know, in an <b>OOP programming language</b>, subclassing is the method to get a specialized behavior from an existing Class: We get for free all the available properties, methods and events from the parent (and all its parent hierarchy), including also the code executed in the Paint event to truly paint or provide its look on screen; so we just need to implement the specific behavior and/or control drawing/painting we need over these.</p>
<p>This is also the way to go when you are in the inital stages of designing your own customized UI control: will you need to create even more specialized behaviors based on a &#8220;parent&#8221; or base customized control? Maybe variations on the behavior? In cases like these, you should define your UI control base class at the bare-minimum set of painting, behavior (events and methods) and properties that will be shared from all the future UI Controls inherited from your base/parent UI Control class. (i.e: more specialized or with behavior variations).</p>
<p>Creating a subclass in Xojo is truly simple: just drag and drop the Canvas icon from the <b>Library</b> to the <b>Navigator</b> (the leftmost column in the Xojo IDE), or choose <code>Insert &gt; Class</code> from the Insert menu.</p>
<p><img loading="lazy" decoding="async" class="size-full wp-image-5650 aligncenter" src="https://blog.xojo.com/wp-content/uploads/2019/04/Canvas-Library.png" alt="" width="260" height="317" /></p>
<h2>Points vs Pixels: HiDPI and Retina</h2>
<p>Once you have added the new Class to your project, select it, go to the Inspector and set the name you want to use for your new Class (using a &#8220;company&#8221; or personal prefix it&#8217;s always a good idea to avoid collision with other existing or future classes in the Xojo Framework, or when using third party classes). Then, in the <b>Super</b> field of the Inspector Panel, type <code>Canvas</code> and confirm the entry. You&#8217;ll see how your class icon changes to the one that uniquely identifies Canvas based classes and instances. The most important thing: your new subclass will have all the properties, events and methods you may expect from a Canvas.</p>
<p><img loading="lazy" decoding="async" class="size-full wp-image-5651 aligncenter" src="https://blog.xojo.com/wp-content/uploads/2019/04/Subclase-Canvas.png" alt="" width="261" height="234" /></p>
<p>This will be the base class in our short tutorial for creating a customized button that will change its associated image (picture) when the mouse pointer is inside the button area, outside the button bounds or when the user click on the control. In the last case, the button will change both the image and its internal state represented by a property as a Boolean value (named <code>Status</code>).</p>
<p>As our customized UI control will not draw itself via the Paint event, we will need to design the images so these precisely fit in the size we want to use for our button. In this example a size of 32 x 32 points.</p>
<p><img loading="lazy" decoding="async" class="size-full wp-image-5652 aligncenter" src="https://blog.xojo.com/wp-content/uploads/2019/04/Sketch-Graficos-1024x650.png" alt="" width="1024" height="650" /></p>
<p>In general, when designing images to use in our Xojo projects we need to change our mindset from thinking in pixels to points. That&#8217;s because Xojo apps do support <b>HiDPI</b> on Windows/Linux and <b>Retina</b> on macOS; that is: hi-def graphics. Thus, it&#8217;s important to use a design tool that simplifies the process. Personally, I use the vectorial app Sktech on macOS because it automates the 2x creation of the final images. (Remember that HiDPI/Retina is enabled by default in the Building Settings on every new Desktop project.)</p>
<p>How do you support HiDPI/Retina if you want to draw the control look on the fly? Avoid the use of pixels in your calculations or when setting the values of the existing Graphic class properties, and use Points instead. If you really need to access the Pixels values underneath, then you can resort to the <code>RGBSurface</code> class (if available) and make use of the <code>ScaleFactorChanged</code> event available on the Canvas class. This way, your class will be notified on every change between displays with or withour Retina/HiDPI support.</p>
<p>Good rule of thumb: do all your control drawing inside the Paint event! And, when you need to update or redraw it (maybe as consequence of some change in the app behavior, or from the change made in other UI control), invoke the method <code>Invalidate</code> instead of <code>Refresh</code>. In general, this will speed up the drawing and, thus, the main app performance.</p>
<h2>If you use an existing Event… Define the Event again</h2>
<p>As our customized class makes use of the <b>Open</b>, <b>MouseEnter</b>, <b>MouseExit</b> and <b>MouseDown</b> Events, we need to make sure we define these events again to the class, so they are also available for the developer using our canvas-based UI subclass. After all, it&#8217;s very probable he needs or wants to add extra code on top of ours! This is something we can do choosing <code>Add to "class_name" &gt; Event definition</code> when our subclass icon is selected in the Navigation Browser.</p>
<p>Thus, once we have created the same events (using the same parameters and returning the same kind of Type values as the original ones), we need to make sure we call them; usually as the last line of code for the already used Event. For example, this is the code for our implementation of the <code>MouseDown</code> event in our Canvas subclass:</p>
<pre>me.Backdrop = if(me.Status = false, ShellRunSelected, ShellRun)
me.Status = not me.Status
return RaiseEvent MouseDown(X, Y)</pre>
<p>Note how, in this case, our implementation of the <code>MouseDown</code> event returns the value returned by the consumer of our subclass instances, called with the <code>RaiseEvent</code> statement. Just remember that returning the <code>True</code> value from this event means that such events will not be propagated further along the Events Chain.</p>
<h2>Putting it all Together</h2>
<p>With this information at hand, and the basic concepts explained, <a href="https://youtu.be/7NYwpdXN-SA">this video</a> (in Spanish) shows how you can join all the needed pieces: pictures, events, definition of already consumed events by the subclass; creating a new very basic control from scratch. Obviously, from this point on, you can find in the available documentation all the information needed to create more complex UI controls based on the Canvas class (WebCanvas or iOSCanvas). The possibilities are limitless!</p>
<p>Other useful topics:</p>
<ul>
<li><a href="https://documentation.xojo.com/topics/user_interface/desktop/desktop_controls/canvas.html">User Guide: Desktop Canvas</a></li>
<li><a href="https://documentation.xojo.com/api/deprecated/canvas.html">Canvas</a>, <a href="https://documentation.xojo.com/api/graphics/graphics.html">Graphics</a> classes</li>
<li><a href="https://documentation.xojo.com/UserGuide:iOS_Canvas">User Guide: iOS Canvas</a></li>
<li><a href="https://documentation.xojo.com/topics/user_interface/web/controls/canvas.html">User Guide: Web Canvas</a></li>
</ul>
<p><em>Javier Rodri­guez has been the Xojo Spanish Evangelist since 2008, he’s also a Developer, Consultant and Trainer who has be using Xojo since 1998. He manages <a href="http://www.aprendexojo.com">AprendeXojo.com</a> and is the developer behind the GuancheMOS plug-in for Xojo Developers, Markdown Parser for Xojo, HTMLColorizer for Xojo and the Snippery app, among others.</em></p>
<p>*<a href="https://www.aprendexojo.com/2016/10/canvas-crea-tus-propios-controles/">Read this post in Spanish</a></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Recursion: Emptying a Folder</title>
		<link>https://blog.xojo.com/2019/02/04/recursion-emptying-a-folder/</link>
		
		<dc:creator><![CDATA[Javier Menendez]]></dc:creator>
		<pubDate>Mon, 04 Feb 2019 10:00:38 +0000</pubDate>
				<category><![CDATA[Learning]]></category>
		<category><![CDATA[AprendeXojo]]></category>
		<category><![CDATA[FolderItem]]></category>
		<category><![CDATA[Recursiveness]]></category>
		<category><![CDATA[Xojo Programming Language]]></category>
		<guid isPermaLink="false">https://blog.xojo.com/?p=5363</guid>

					<description><![CDATA[Do you need code to delete the files and folders from the selected folder? In that case, there is a technique I propose to you and that is based on the recursivity. That is, the hability of a function to calling itself until the task is complete; in this case, the function will call itself every time it detects a new folder/directory inside the designated original folder/directory.]]></description>
										<content:encoded><![CDATA[<p>Do you need code to delete the files and folders from the selected folder? In that case, there is a technique I propose to you and that is based on <strong>recursion</strong>. That is, the ability of a function to call itself repeatedly until the task is complete; in this case, the function will call itself every time it detects a new folder/directory inside the designated original folder/directory.<span id="more-5363"></span></p>
<p>But, beware! The following implementation will delete all the files and original containing folder every time it finds an alias… not just the alias. Anyway, it is easy to change this behavior in case you just want to delete the alias and not the original it points to.</p>
<p>As you probably already know, when we work with files or folders in Xojo we are actually using the <a href="http://documentation.xojo.com/api/files/folderitem.html">FolderItem</a> class, so we are able to access to all its properties and the methods acting on every instance: changing the file/folder/directory name, getting the creation date, create a copy, to move the file and/or folder to a new destination … and also for deleting the file or folder.</p>
<p>In addition, <b>recursion</b> is a technique that is not always appropriate because the function adds a new frame of data to the execution stack every time it calls itself, something that can cause a stack overflow error if it calls itself a large amount amount of times. This may occur, for example, if a folder or directory has many nested folders. To alleviate this, we can resort to the mechanism provided by the Xojo language itself and gracefully catch this situation on runtime.</p>
<p>Having said this, what is the best way to implement our recursive function so it is available to all the FolderItem instances? You may create a new FolderItem subclass, but that would mean that the method would only be available from the instances created from the subclass, and not for those created from the parent FolderItem class. The answer in this case is to apply it as a <a href="http://documentation.xojo.com/api/language/extends.html"><strong>Class Extension</strong></a> technique. This technique allows us to add additional functionality to a existing class without needing to subclass it previously.</p>
<p>The way to add a Class Extension in Xojo is through a <a href="http://documentation.xojo.com/api/language/module.html"><b>Module</b></a>, so it gives us the option to set the method as globally available from all the app code. This way, the Xojo compiler will know that we want to extend a particular class because we use the <code>Extends</code> keyword in the method definition, followed by the variable whose data type designates the class we want to extend.</p>
<p>So, our method (or function) signature will be:</p>
<p><code>DeleteAllFilesInside(extends f as FolderItem)</code></p>
<p>Once we&#8217;ve added that method to a Module it&#8217;s important to set the <code>Scope</code> to the value <code>Global</code> in the Inspector. Now we can put the following code inside the associated Code Editor for the method, so this is the responsible of deleting the files and call itself every time it detects a new folder/directory:</p>
<pre>  // We keep the initial (designated) FolderItem
  // So it doesn't get deleted.

  Static originFolder As String = f.NativePath

  // Is the pointed FolderItem a Directory?
  // then proceed to iterate the containing
  // files and (probably) folders.

  If f.Directory Then

    For n As Integer = f.Count DownTo 1

      If f.Item(n) &lt;&gt; Nil Then

        // Are we detecting a new folder
        // while iterating the current one?
        // then we call the function again!

        If f.item(n).Directory And f.Count &lt;&gt; 0 Then

          Dim f1 As FolderItem = f.item(n)

          f1.deleteAllFilesInside

        End If

        // Otherwhise, we proceed to delete the file/folder
        // always it is not the initial FolderItem
        // that is, the initial folder/directory

        If f.item(n) &lt;&gt; Nil And f.item(n).NativePath &lt;&gt; originfolder Then f.item(n).Delete

      End If
      
    Next
  End
  
  // we are outside a folder, so let's check
  // that the pointing FolderItem is not the initial one
  // if it doens't, then we can delete the file/folder

  If f &lt;&gt; Nil And f.NativePath &lt;&gt; originFolder Then f.Delete

</pre>
<p><em>Javier Rodri­guez has been the Xojo Spanish Evangelist since 2008, he’s also a Developer, Consultant and Trainer who has be using Xojo since 1998. He manages <a href="http://www.aprendexojo.com">AprendeXojo.com</a> and is the developer behind the GuancheMOS plug-in for Xojo Developers, Markdown Parser for Xojo, HTMLColorizer for Xojo and the Snippery app, among others.</em></p>
<p>*Watch a <a href="https://www.youtube.com/watch?v=1TNxnYs91xY">video of this Tutorial in Spanish</a></p>
<p>*<a href="https://www.aprendexojo.com/2019/01/recursividad-vaciar-contenido-de-una-carpeta/">Read this post in Spanish</a></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Tutorial: Saving WebCanvas Images to Disk</title>
		<link>https://blog.xojo.com/2018/10/11/tutorial-saving-webcanvas-images-to-disk/</link>
		
		<dc:creator><![CDATA[Javier Menendez]]></dc:creator>
		<pubDate>Thu, 11 Oct 2018 10:00:34 +0000</pubDate>
				<category><![CDATA[Learning]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[AprendeXojo]]></category>
		<category><![CDATA[Canvas]]></category>
		<category><![CDATA[HTML5]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[WebCanvas]]></category>
		<category><![CDATA[webdev]]></category>
		<category><![CDATA[Xojo Programming Language]]></category>
		<guid isPermaLink="false">https://blog.xojo.com/?p=5024</guid>

					<description><![CDATA[The WebCanvas control is used for drawing graphics in web apps. It takes advantage of the HTML5 Canvas making it fast and powerful. Sometimes is can be useful to be able to save the graphics drawn in the WebCanvas to an image file, but unfortunately there is no built-in Xojo method to do this. However, by using a little JavaScript you can easily add this capability to Xojo.]]></description>
										<content:encoded><![CDATA[<p>The <strong>WebCanvas</strong> control is used for drawing graphics in web apps. It takes advantage of the HTML5 Canvas making it fast and powerful. Sometimes is can be useful to be able to save the graphics drawn in the WebCanvas to an image file, but unfortunately there is no built-in Xojo method to do this.</p>
<p>However, by using a little JavaScript you can easily add this capability to Xojo.</p>
<p><span id="more-5024"></span></p>
<p>In order to follow this tutorial, create a new <b>Web</b> project and add a new <a href="http://developer.xojo.com/webcanvas"><b>WebCanvas</b></a> control from the Library to the default Web Page added to the project: <code>WebPage1</code>. With the WebCanvas selected in the Navigator, change its name to <code>cCanvas</code> using the Inspector and add the <code>Paint</code> Event Handler to it using the <code>Insert &gt; Event Handler</code> option from the menu. Use the following code to draw a black colored rectangle:</p>
<pre>g.FillRect 0, 0, g.Width, g.Height</pre>
<p>Obviously, you can draw anything you want in the WebCanvas or even <em>paint</em> a picture on it. The achieved result will be the same. For example, we can draw a picture added to our project (with the filename &#8220;landscape&#8221;), using this line of code in the Paint event of our <code>cCanvas</code> instance:</p>
<pre>g.DrawPicture landscape, 0, 0, g.Width, g.Height</pre>
<h2>Retrieving the WebCanvas image data</h2>
<p>The first interesting step is retrieving the underlying image represented by the WebCanvas and that is something we can get using a fragment of <b>JavaScript</b> code executed from the Xojo side. This is the process we will execute from the <code>Action</code> Event Handler of a <b>WebButton</b> added to the <code>WebPage1</code> from the Library. In fact, this will be the button in charge of calling the process to save the image as a picture file on the user disk.</p>
<p>Once the WebButton has been added to the WebPage from the Library, put the following code in its <code>Action</code> Event Handler:</p>
<pre>Dim js() As String
js.Append "var canvas = document.getElementById('" + cCanvas.ControlID + "_canvas');" // We get the item reference based on its ID
js.Append "var img = canvas.toDataURL(""image/png;base64;"");" // We access to the image data, encoded as a base64 string
js.Append "document.location.hash=img" // We assign that data to the document Hash property, so we can retrieve it from the Xojo side

Dim execute As String = Join(js,"")

ExecuteJavaScript execute // Finally, we execute the JavaScript code</pre>
<p>As you can see, the first line of the JavaScript code is in charge of retrieving the <code>cCanvas</code> reference from the DOM (document object model) of the Web Page. For that, we use the <code>ControlID</code> property on our WebCanvas instance, adding the &#8220;canvas&#8221; appended by Xojo to all these kind of objects when generating the source code for the page.</p>
<p>Once we get the reference to our Canvas instance, the following line of code retrieves the picture content itself and assigns it to the <code>img</code> variable. The <em>trick</em> here is that we retrieve that information in its URL format and, thus, encoded as <b>Base64</b> data that we can assign to other document properties without losing its original meaning.</p>
<p>Then, we assign the data to the document <b>Hash</b> property. This is the property that allows us to jump to other page sections previously tagged. However, we will use this property as a temporary storage container for passing the data between the HTML/JavaScript side of the web page and the Xojo side of our code. Why we do this? Well, because we can add the <b>HashTagChanged</b> Event Handler to the <b>Session</b> object so it will fire every time we change the value of the <code>Hash</code> property and we will be able to retrieve the data from that property.</p>
<h2>Retrieving the image, from the Xojo side</h2>
<p>So, the next step is adding the <code>HashTagChanged</code> event to the <b>Session</b> object of our example project, writing the following snippet of code in the associated Code Editor:</p>
<pre>Dim data As String = DecodeBase64(Hashtag.NthField(",",2) ) // We retrieve the information saved in the Hash, but just the relevant data for the image and not the URL part.
wp = New WebPicture(data,"My_Picture.png") // We create a new WebPicture instance using the previously retrieved image data in the constructor, and giving a default file name for the image
wp.ForceDownload = True // We want to force the file download instead of showing it
ShowURL wp.URL // and finally we start the file download process.

Hashtag = "" // Let's empty the hash property, just to make sure that the event will fire even if the WebCanvas doesn't change its contents</pre>
<p>As you can see, in the first line of code we retrieve the image data. We do that using the <code>NthField</code> command because we are only interested in the image data and not in the URL information that precedes it. In addition, we decode the previously encoded data as Base64, so we really get the bytes of the image in PNG format.</p>
<p>Once we get the picture data, we can use any of the available constructors for the <a href="http://developer.xojo.com/webpicture"><b>WebPicture</b></a> class; in this case the one that lets us create a new image from the passed data. In addition, we use this class because it is a subclass of <b>WebFile</b>, and that means that it is simpler to force the download as an image file instead of showing its contents in a new web page.</p>
<p>In fact, this is what we achieve setting the <code>ForceDownload</code> property to <code>True</code>, so when in the following line we use <code>ShowURL</code> we will be forcing the download of the file instead of displaying the image as a new page in the browser. Goal achieved!</p>
<p><img loading="lazy" decoding="async" class="size-full wp-image-5027 aligncenter" src="https://blog.xojo.com/wp-content/uploads/2018/10/WebCanvasToFile.png" alt="" width="500" height="279" /></p>
<h2>Download persistence</h2>
<p>You probably noted that the <code>wp</code> variable is not declared in the previous fragment of code. This is because we need to make sure that the object it points to is in scope during the file downloading process and won&#8217;t get destroyed once we exit the Event Handler (we would want a message error from the web browser in that case). The solution is pretty easy &#8211; we only need to add a new property to our <b>Session</b> object, using the following values:</p>
<ul>
<li><b>Name</b>: wp</li>
<li><b>Type</b>: WebPicture</li>
<li><b>Scope</b>: Private</li>
</ul>
<p>Now, every time you run the app web and click the button, you&#8217;ll see how the web browser downloads the WebCanvas image as a PNG file to disk.</p>
<p>To summarize, in this tutorial we have seen a way to &#8220;communicate&#8221; between the data generated executing JavaScript code in our web app so we can retrieve and use it from the Xojo side of our Web App; in this case applied to the retrieval and saving of the underlying picture represented by a WebCanvas object.</p>
<p>*Watch a <a href="https://www.youtube.com/watch?time_continue=29&amp;v=RTBuub8Atjw">video of this Tutorial in Spanish</a></p>
<p>*<a href="https://www.aprendexojo.com/2016/06/crear-servicio-web-con-xojo/">Read this Tutorial in Spanish</a></p>
<p><em>Javier Rodri­guez has been the Xojo Spanish Evangelist since 2008, he’s also a Developer, Consultant and Trainer who has be using Xojo since 1998. He manages <a href="http://www.aprendexojo.com">AprendeXojo.com</a> and is the developer behind the GuancheMOS plug-in for Xojo Developers, Markdown Parser for Xojo, HTMLColorizer for Xojo and the Snippery app, among others</em></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Software Distribution Simplified with GuancheMOS</title>
		<link>https://blog.xojo.com/2018/06/26/software-distribution-simplified-with-guanchemos/</link>
		
		<dc:creator><![CDATA[Javier Menendez]]></dc:creator>
		<pubDate>Tue, 26 Jun 2018 10:00:09 +0000</pubDate>
				<category><![CDATA[Cross-Platform]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[AprendeXojo]]></category>
		<category><![CDATA[Distribution]]></category>
		<category><![CDATA[Plugins]]></category>
		<guid isPermaLink="false">https://blog.xojo.com/?p=4476</guid>

					<description><![CDATA[For software, distribution usually means generating and validating unique serial numbers for each of your products and users. This helps you manage your users, possibly unlock a free trial or demo version for full use and, of course, to minimize the illegal use of your software.]]></description>
										<content:encoded><![CDATA[<p>In an ideal world there is a person responsible for every step in software development, from coding, UI design, distribution, documentation, marketing and support. All of this can seem really overwhelming for independent developers and small businesses. But if you break it down and take it one piece at a time, it&#8217;s manageable by even the smallest team of one. Right now, let&#8217;s look at <strong>software distribution</strong>.</p>
<p>For software, distribution usually means generating and validating unique serial numbers for each of your products and users. Serial numbers (or license keys) help you manage your users, unlock a free trial or demo version for full use and, of course, minimize illegal use of your apps.</p>
<p><span id="more-4476"></span></p>
<p>Let&#8217;s admit it, there is no silver bullet. Even the greatest companies (you know who you are) throw lots of money at implementing and improving serious protection schemes that are often quickly bypassed.  It comes down to: How much time, money and resources are <em>you</em> willing to spend implementing a protection or licensing scheme?</p>
<p>The <em>bad guys</em> will always find a way to break your software protection if they are interested in doing that. Does that mean giving up on protecting your software? Not at all! When I was faced with the problem myself, in order to protect my own products, I went to the drawing board to build a way to generate unique serial numbers —or licensing information— for all the Xojo supported platforms.</p>
<p>The result of this process was the <a href="https://www.aprendexojo.com/shop/guanchemos-serial-number-generation-and-validation-for-xojo-developers/"><b>GuancheMOS plug-in</b></a>. GuancheMOS is a fully multiplatform plug-in for desktop, web and console apps (not for iOS due to the fact that iOS only can link against static libraries), on 32-bit and 64-bit architectures.</p>
<p>The simplicity of GuancheMOS means that you can use it as is, or as the starting point to build your own private and unique serial number automations. Integrate it as part of the purchase process in your website, wrap it as the core piece of other unique information collection. It&#8217;s already used by dozens of developers around the world in ways I hadn&#8217;t ever thought of while designing it! The best part, is that implementing GuancheMOS in your product takes about 5 minutes.</p>
<p>You can download and try <a href="https://www.xojo.com/store/#addons">GuancheMOS</a> for free today.</p>
<p><em>Javier Rodri­guez has been the Xojo Spanish Evangelist since 2008, he’s also a Developer, Consultant and Trainer who has be using Xojo since 1998. He manages <a href="http://www.aprendexojo.com">AprendeXojo.com</a> and is the developer behind the GuancheMOS plug-in for Xojo Developers, Markdown Parser for Xojo, HTMLColorizer for Xojo and the Snippery app, among others</em></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Prepare Your Classes to Work in Simulated or Real Modes</title>
		<link>https://blog.xojo.com/2018/06/01/prepare-your-classes-to-work-in-simulated-or-real-modes/</link>
		
		<dc:creator><![CDATA[Javier Menendez]]></dc:creator>
		<pubDate>Fri, 01 Jun 2018 10:00:58 +0000</pubDate>
				<category><![CDATA[Learning]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[AprendeXojo]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Xojo Framework]]></category>
		<guid isPermaLink="false">https://blog.xojo.com/?p=4321</guid>

					<description><![CDATA[In many of our development projects, if not all, we are confronted with situations when we need to test the components before the final deployment of the project. It would be just as effective, and a lot less disruptive to those using your app, to test using  a mechanism that allows us tell our apps when to run in "simulated" mode or "real".]]></description>
										<content:encoded><![CDATA[<p>In many of our development projects, if not all, we are confronted with situations when we need to test our classes before the final deployment of a project. I&#8217;m not talking about <a href="https://github.com/xojo/XojoUnit">Unit Testing</a> here, though I highly recommend the excellent session on that topic from&nbsp;<a href="https://forum.xojo.com/47544-xdc-2018-session-videos-now-available">XDC 2018</a>.</p>
<p>For example, it would not be desirable to send hundreds of emails to all the entries in a database simply to test one of the workflow steps or to verify that emails are being delivered as expected. It would be a lot simpler, and less disruptive to those using your app, to test using a few email addresses that are under your control.</p>
<p>So let&#8217;s establish a mechanism that allows us tell our apps when to run in a &#8220;simulated&#8221; mode vs. a &#8220;real&#8221; mode for all or some of the components that we need to test along the development cycle.</p>
<p><span id="more-4321"></span></p>
<p>In fact, the way we can implement this is very simple and is based in the definition of a Boolean property in every class (let&#8217;s call it <code>Simulation</code>) that we can make visible under the <b>Inspector Panel</b> using the <b>Inspector Behavior</b> feature. Doing this, we can also change it when we drag and drop the class on the Window Layout tray in order to create an implicit instance.</p>
<p>In association with the property itself, we will implement every public method that will be called from the consumer (other component or code of the app) as usual, with the only difference that we will add two additional private methods for every public method we want to run in both modes: simulated and real. For example, let&#8217;s say we have a class that returns a <code>Dictionary</code> array with data from a database. We create a public method for the class, called <code>GetData</code>, but when we just need to test other components it provides some fake data instead of connecting and retrieving a bunch of real data from the remote database. In this case we could define the following methods for the class:</p>
<ul>
<li><code>GetData() As Dictionary()</code>. Public Method, part of the visible interface for the rest of the app.</li>
<li><code>GetRealData As Dictionary()</code>. Private Method, called if the <code>Simulation</code> property is set to <code>False</code>.</li>
<li><code>GetSimulationData As Dictionary()</code>. Private Method, called when the <code>Simulation</code> property is set to <code>True</code>.</li>
</ul>
<p>Then, the real code for our public method will be simply this:</p>
<p><code>Return if(Simulation = True and DebugBuild = True, GetSimulationData, GetRealData)</code></p>
<p>Simple, isn&#8217;t it? With this you will have the maximum flexibility to choose the functionality you want to test using real or simulated data: all, none, part of them … even when you deploy the compiled project it will work always with real data.</p>
<p><em>Javier Rodri­guez has been&nbsp;the Xojo Spanish&nbsp;Evangelist since 2008, he’s also a Developer, Consultant and Trainer who&nbsp;has be using&nbsp;Xojo since 1998. He manages&nbsp;<a href="http://www.aprendexojo.com">AprendeXojo.com</a> and is the developer behind the GuancheMOS plug-in for Xojo Developers, Markdown Parser for Xojo, HTMLColorizer for Xojo and the Snippery app, among others</em></p>
<p>*<a href="https://www.aprendexojo.com/2018/05/prepara-tus-clases-para-uso-en-modo-simulado-o-real/">Read this post in Spanish</a></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to Add User Interface Controls at Runtime</title>
		<link>https://blog.xojo.com/2018/01/26/how-to-add-ui-controls-at-runtime/</link>
		
		<dc:creator><![CDATA[Javier Menendez]]></dc:creator>
		<pubDate>Fri, 26 Jan 2018 07:10:59 +0000</pubDate>
				<category><![CDATA[Cross-Platform]]></category>
		<category><![CDATA[Learning]]></category>
		<category><![CDATA[AprendeXojo]]></category>
		<category><![CDATA[Control Set]]></category>
		<category><![CDATA[User Interface]]></category>
		<guid isPermaLink="false">https://blog.xojo.com/?p=3770</guid>

					<description><![CDATA[How can I add new UI controls to the Window at runtime? And if you are considering this too, then the good news is that the answer is more simple than you probably expect… sitting right there on the Inspector Panel under the Attributes tab. Yes, this is all about the Control Set!]]></description>
										<content:encoded><![CDATA[<p>Admit it &#8211; this is one of those questions that, sooner or later, arise to every Xojo newcomer: How can I add new UI controls to the Window at runtime? And if you are considering this too, then the good news is that the answer is more simple than you probably expect… sitting right there on the Inspector under the Attributes tab. Yes, this is all about the Control Set!<span id="more-3770"></span></p>
<p>Before we put our hands on it, let&#8217;s make some things clear about the <a href="http://developer.xojo.com/userguide/desktop-control-sets">Control Set</a>:</p>
<ul>
<li>You can use this feature to dynamically create any kind of control based on the <a href="http://developer.xojo.com/userguide/desktop-control-sets"><b>RectControl</b></a> class.</li>
<li>You can use Control Sets on <b>Desktop</b> and <b>Web</b> projects (although web projects cannot use Control Sets to dynamically create controls at runtime).</li>
<li>You cannot create Control Sets for Container Controls.</li>
<li>The Control Sets may seem like Arrays, because you will use an <b>index</b> to refer every instance from the same Control Set, but they are not. So, don&#8217;t think about them in that way.</li>
<li>All of the instances of the Control Set will share the same <b>Event Handlers</b>, so you will have to use the additional <b>index</b> argument, passed to the Event Handler, in order to identify over which instance are you handling.</li>
</ul>
<p>But, how can we create one of these Control Set after all? Well, we just need to put any control we want to use as a <em>clonation template</em> on the Window, even if it is placed outside the visible limits of the Window itself. Then, and with the control still selected, you just have to push on the attributes button (the one with the image of a gearwheel) on the Inspector, selecting the <code class="inlinecode">New Control Set</code> option from the <code class="inlinecode">Member Of</code> entry under the <code class="inlinecode">Control Set</code> Section.</p>
<blockquote><p><b>Tip</b>: If you change the name of the Control used to create a Control Set, then you will have to recreate the Control Set, so rename the template Control in the first place!</p></blockquote>
<p>Once you have created the new Control Set, you will see that the first instance of the Control Set is assigned the <b>index</b> number 0; succesive instances will have their index increassed by one, both the ones you may add to the Window (not what we want to do in this case), and those created at runtime (what we want to do).</p>
<p>Now, probably you will want to change the <code class="inlinecode">Visibility</code> Property to <code class="inlinecode">False</code> on this first cloning template control, so it will not be visible to the users of the app no matter the resizing of the containing Window.</p>
<p>Once our cloning control is all set, it’s time to reveal all the code we will need in order to create new instances of the control at run time. Let’s indicate that we have used as cloning template Control a PushButton and that we have named it <code class="inlinecode">btClon</code>. Then, we just need this to create a new instance, making it visible on the Window:</p>
<pre>Dim newInstance as PushButton = new btClon
newInstance.visible = true</pre>
<p>Remember that every <b>UI</b> component is based on (<em>inherits from</em>) the RectControl class, so you also can do this:</p>
<pre>Dim newInstance as RectControl = new btClon
PushButton(newinstance).visible = true</pre>
<p>As you can see, the difference is that in this case you have to <a href="http://developer.xojo.com/userguide/advanced-oop-features"><b>Cast</b></a> the generic RectControl instance to the PushButton class in order for you to use and access all the PushButton methods and properties from code.</p>
<p>Why should you use this formula, then? Well, if you are thinking about creating several Types of UI components at runtime, then you will probably prefer to create them using a more generic RectControl variable or reference (maybe a RectControl Array containing all of your dinamically created controls).</p>
<p>As you may expect, the new instances created from a template will have the same properties, events and methods the template control has, with the difference that it will also inherit the clone properties values. This is why once a new instance is created we need to make it visible again and you will want to change other properties too, for example the <code class="inlinecode">Caption</code> and the <code class="inlinecode">Left</code> and <code class="inlinecode">Top</code> properties among others.</p>
<h2>Modifying the Z axis order of the Control</h2>
<p>We already know that every new created instance of the Control Set gets its index increased by one. What you have to know is that every new instance is above the previous one on the Z axis of the Window. I mean, if the control with the <code class="inlinecode">Index</code> set to 2 partially overlays the position of the control with the <code class="inlinecode">Index</code> 1, then the first one will overlay the second. What if you decide to have a control with a low index value above the others?</p>
<p>Currently there is no easy way we can dynamically change the Z order of a control to any desired value, but there is an easy way we can move any control to the foreground, so it can stay in front of all of them!</p>
<p>Let’s say that we have our cloned control with the <code class="inlinecode">Index</code> 1 and want to show it in the foreground, with the highest possible value in the Z axis. All we have to do is assign it to another RectControl as its <code class="inlinecode">parent</code> property value, for example the control we are using as cloning template. Once done, we will assign the Window again as the <code class="inlinecode">parent</code> property value of the control. The code could be something similar to this:</p>
<pre>btClon(2).parent = btClon(0)
btClon(2).parent = Window1 //Or Self or Me, depending where you place the code</pre>
<p>In conclusion, as you can see, the creation of UI controls at runtime is something really easy to do in Xojo! But what if you need to dynamically add a group or layout of control at runtime? Well, in that case don&#8217;t forget about the <a href="https://blog.xojo.com/2017/04/26/containercontrol-making-a-multiplatform-search-field/" target="_blank" rel="noopener">ContainerControls</a>!</p>
<p><em>Javier Rodri­guez has been the Xojo Spanish Evangelist since 2008, he’s also a Developer, Consultant and Trainer who has be using Xojo since 1998. He manages <a href="http://www.aprendexojo.com">AprendeXojo.com</a> and is the developer behind the GuancheMOS plug-in for Xojo Developers and the Snippery app, among others.</em></p>
<p>*<a href="https://www.aprendexojo.com/2018/01/anadir-controles-de-ui-en-tiempo-de-ejecucion/">Read this post in Spanish</a></p>
<p>*<a href="https://www.youtube.com/watch?v=9NAap4Ipmnc">Watch the video in Spanish</a></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Make Your Own Classes Iterables</title>
		<link>https://blog.xojo.com/2017/12/13/make-your-own-classes-iterables/</link>
		
		<dc:creator><![CDATA[Javier Menendez]]></dc:creator>
		<pubDate>Wed, 13 Dec 2017 06:00:16 +0000</pubDate>
				<category><![CDATA[Learning]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[AprendeXojo]]></category>
		<category><![CDATA[Iterable]]></category>
		<category><![CDATA[Iterator]]></category>
		<guid isPermaLink="false">https://blog.xojo.com/?p=3608</guid>

					<description><![CDATA[By default in Xojo, we can find a couple of collections that are iterable: the already mentioned Arrays and also Dictionaries. Wouldn't it be great to extend this feature so we can add this behaviour to our own classes making them more flexible?]]></description>
										<content:encoded><![CDATA[<p>In programming, <a href="http://developer.xojo.com/xojo-core-iterator">iterators</a> are the mechanisms that allow us to walk all the members of a collection without needing to know in advance how many of them compose such a collection; and for that we can find in Xojo the commands&nbsp;<code>For Each… Next</code>. What are the main differences in comparison to the conventional <code>For… Next</code>?</p>
<p>The first difference is that with <code>For Each… Next</code> we can&#8217;t assume that we are iterating the members of the collection in order, as it is the case when using the variable of the conventional <code>For… Next</code> as the Index in order to access a known member of the collection. The second difference is that the iterator will be invalid when the iterated elements are modified, or when we modify the amount of elements in the collection during the iteration process.</p>
<p>By default in Xojo, there are a couple of collections that are iterable: the already mentioned Arrays and also <a href="http://developer.xojo.com/xojo-core-dictionary">Dictionaries</a> and <a href="http://developer.xojo.com/xojo-io-folderitem$Children">FolderItem.Children</a>. Wouldn&#8217;t it be great to extend this feature so we can add this behaviour to our own classes making them more flexible? The key to making this happen is using the two Class Interfaces already included in Xojo: <b>Iterator</b> and <b>Iterable</b>.</p>
<p><span id="more-3608"></span></p>
<p>You can download the example project used by this tutorial from this <a href="https://www.dropbox.com/s/gcjvnmewyc3wyb4/Ejemplo_Iterador.zip?dl=1">link</a>.</p>
<h2>Using Iterator</h2>
<p>In order to implement this behaviour in our classes so they can use the <code>For Each… Next</code> schema, the real work is under the <a href="http://developer.xojo.com/xojo-core-iterator"><b>Xojo.Core.Iterator</b></a> Class Interface. Under this interface we can find the definition of the methods that need to implement the class and that are responsible for advancing for every item of the collection, and for returning the current value of the collection:</p>
<ul>
<li><b>MoveNext</b>. Moves to the next element of the Collection, returning<br />
<code>True</code> if it has not reached the end of the collection, or <code>False</code> when reached past the last element in the Collection.</li>
<li><b>Value</b> This is the Class Interface method that returns the current element of the collection as an Auto data type.</li>
</ul>
<p>From this, it is easy to conclude that our iterable classes need to implement a counter (Property) that updates its value for every <code>MoveNext</code> invocation. We will also use this property to check if it has reached the maximum quantity of elements. The only thing we need to be aware of is that the property has to be initialized using the value -1 (that is, as an invalid value), as it is stated in the documentation that we have to invoke <code>MoveNext</code> before we can get the first iterable element from the collection.</p>
<p>On the other hand, we will handle all the error cases during the iteration process raising an <code>IteratorException</code>.</p>
<p>In order to see all this in action, let&#8217;s run through an example using the <code>Person</code> class in charge to store in their instances all the possible postal addresses associated with a person.</p>
<p>Let&#8217;s start defining our <code>Person</code> class as a simple set of Properties:</p>
<ul>
<li>firstName As String</li>
<li>middleName As String</li>
<li>secondName As String</li>
</ul>
<p>We will add also the Property in charge of referencing all the postal addresses assigned to the Person, using an Array:</p>
<ul>
<li>postalAddresses() as PostalAdress</li>
</ul>
<p>With that, we will have finished our Person class definition. It&#8217;s very simple but will work for the purpose of the example.</p>
<p>We will also create a simple (and incomplete) definition for the PostalAddress class using a set of public properties so they serve the purpose of the main topic.</p>
<ul>
<li>street As Text</li>
<li>streetNumber As Integer</li>
<li>streetFlat As Integer</li>
</ul>
<h2>Creating an Iterator</h2>
<p>Once we have the two classes needed for our example (Person and PostalAddress), we can define the Class responsible for acting as the iterator; that is, returning every element from the collection for the associated class. In this example we will return every object of the PostalAddress that is associated with an instance of the Person class. In fact, the Iterator is responsible of doing all the hard work, moving forward the counter to the next item, and returning the object or value when requested.</p>
<p>Let&#8217;s create a new Class with the name <code>PersonIterator</code>. In this case, use the associated Inspector to push on the <code>Choose</code> button related with the <code>Interfaces</code> label. As the result of the previous action, the Xojo IDE will display a window containing all the available Class Interfaces. Select the checkbox for <b>Xojo.Core.Iterator</b> and confirm the selection.</p>
<p>As result of the previous action, the IDE will add the following defined methods for the selected class interface:</p>
<ul>
<li><b>MoveNext</b>. The documentation states that this is the method invocated before calling the&nbsp;<code>Value</code> method in order to get a new value. In fact, in the method implementation we have to write the code that increases the counter value, and also to check if the counter value is over the available quantity of items. That is, we have to add a <code>counter</code> Property to our class, and initialice it with the value -1.</li>
<li><b>Value</b>. This is the method that will be called every time we need to get a new value. In our example, this will return a new PostalAddress object from the available items.</li>
</ul>
<p>Thus, the implementation for the <code>MoveNext</code> method could be the following:</p>
<pre>counter = counter + 1</pre>
<p>But the method signature and the class interface documentation states that the method has to return a boolean value&nbsp;<code>True</code> if there are remaining available items to iterate, and <code>False</code> when we have surpassed the quantity of iterable items; and in that case we should raise an exception in order to point this out.</p>
<p>For example, our class could check if the counter doesn&#8217;t exceed the quantity of items stored by the PostalAddresses Array, returning the corresponding boolean value.</p>
<p>But let&#8217;s fill in some holes before writing the final implementation for the <code>MoveNext</code> method. First, let&#8217;s add some more needed properties:</p>
<ul>
<li><b>maxPostalAddresses As Integer</b>. This will be responsible for storing the quantity of elements available under the PostalAddress Array.</li>
<li><b>source As Person</b>. This will be in charge of saving the reference to the Person object it has to iterate.</li>
<li>The Calculated Property <b>valid as Boolean</b>. We will use the <code>Get</code> method from this calculated property to know if the PostalAddress Array has been modified during the iteration of the object, returning <code>False</code> when this is the case. In fact, this is the code for the <code>Get</code><br />
method:</li>
</ul>
<pre>Return if(source.postalAddresses.Ubound = maxPostalAddresses, True, false)</pre>
<p>Next, we will add the <code>Constructor</code> method to the class using this signature:</p>
<pre>Constructor( value As Person )</pre>
<p>and the following code for the method:</p>
<pre>source = value
maxPostalAddresses = value.postalAddresses.Ubound</pre>
<p>That is: we initialize the previously declared property&#8217;s values with the reference to the Person object that we will use to iterate over, and the quantity of elements included in the Array when we initialize the class; thus, the original items quantity that we will use to check if it has been modified during the iteration process.</p>
<p>Now we can move back to the <code>MoveNext</code> method to write its final implementation:</p>
<pre>If valid Then
  counter = counter + 1
  Return If(counter &lt;= source.postalAddresses.Ubound, True, False)
Else
  Dim e As New Xojo.Core.IteratorException
  e.Reason = "Invalid Data"
  Raise e
End If</pre>
<p>Inside the method implementation we will check also if the object has been modified during the iteration, returning the corresponding value:</p>
<pre>If valid Then
  Return source.postalAddresses(counter)
Else
  Dim e As New Xojo.Core.IteratorException
  e.Reason = "Invalid Data"
  Raise e
End If</pre>
<p>As you can see, the Value method will return the PostalAddress item from the Person array, using as Index the value of the Counter property.</p>
<h2>Creating the Iterable Class</h2>
<p>Now we have to create the iterable class itself. For that we will add a new class to the project using<code>IterablePerson</code> as its name and making it a subclass from the Person class, so we have to write this data type in the <code>Super</code> field of the Inspector Panel. In addition, this class will be the one that implements the class interface <a href="http://developer.xojo.com/xojo-core-iterable"><b>Xojo.Core.Iterable</b></a>, so you have to push on the <code>Choose</code> button associated with the <code>Interfaces</code> label in order to select and confirm the addition of the corresponding methods. In fact, is just one method:</p>
<pre>GetIterator() As Xojo.Core.Iterator</pre>
<p>And this is the code you have to write for that method:</p>
<pre>Dim it As New iterablePerson(Self)
Return it</pre>
<p>With this we have all the definitions we need for the subclass: we get a new <code>IterablePerson</code> instance passing as parameter the iterable object (a Person subclass). That&#8217;s all! Finally, we return the iterator we get and that will be used inside the <code>For Each… Next</code> loop.</p>
<h2>Putting it all together</h2>
<p>Armed with all the needed classes for our example, we can finally put it all into practice. For this, we will use a <a href="http://developer.xojo.com/listbox">ListBox</a> in the main project Window (<code>Window1</code>). This is the control where we will add as many rows as postal addresses associated with a instance of the Person class used for the example. For this, add also a button to the window with the Action event and write the following code in the resulting Code Editor:</p>
<pre>Dim p As New iterablePerson
p.name = "Juan"
p.middleName = "Sin Miedo"
p.secondName = "De Nada"
Dim d As New PostalAddress
d.street = "Juan de Urbieta"
d.streetNumber = 6
d.streetFlat = 1
p.postalAddresses.Append d
d = new PostalAddress
d.street = "Mi calle bonita"
d.streetNumber = 8
d.streetFlat = 3
p.postalAddresses.Append d
d = new PostalAddress
d.street = "Princesa"
d.streetNumber = 5
d.streetFlat = 5
p.postalAddresses.Append d
For Each s As PostalAddress In p
  Listbox1.AddRow s.street + ", " + s.streetNumber.ToText + " Piso: " + s.streetFlat.ToText
Next</pre>
<p>Run the project, push the button and you will see how the <code>For Each… Next</code> loop iterates every postal address associated with the Person object. This is a more concise, stylish and OOP way of doing things when compared with the classic <code>For… Next</code> loop, where we have to get the upper value (or limit) and use a variable as index to get every collection object we are interested in.</p>
<p>For more on this topic:</p>
<ul>
<li><a href="http://developer.xojo.com/webinar-arrays-dictionaries-iterators">Video: Arrays, Dictionaries, Iterators</a></li>
<li><a href="http://developer.xojo.com/userguide/iterator-and-iterable-interfaces">User Guide: Iterator and Iterable Interfaces</a></li>
</ul>
<p><em>Javier Rodri­guez has been&nbsp;the Xojo Spanish&nbsp;Evangelist since 2008, he’s also a Developer, Consultant and Trainer who&nbsp;has be using&nbsp;Xojo since 1998. He manages&nbsp;<a href="http://www.aprendexojo.com">AprendeXojo.com</a> and is the developer behind the GuancheMOS plug-in for Xojo Developers and the Snippery app, among others.</em></p>
<p>*<a href="https://www.aprendexojo.com/2017/07/implementa-clases-iterables-en-xojo/">Read this post in Spanish</a></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Xojo and Community Growth in 2017</title>
		<link>https://blog.xojo.com/2017/12/11/xojo-and-community-growth-in-2017/</link>
		
		<dc:creator><![CDATA[Alyssa Foley]]></dc:creator>
		<pubDate>Mon, 11 Dec 2017 08:00:07 +0000</pubDate>
				<category><![CDATA[Community]]></category>
		<category><![CDATA[Fun]]></category>
		<category><![CDATA[Learning]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[XDC]]></category>
		<category><![CDATA[64-bit]]></category>
		<category><![CDATA[AprendeXojo]]></category>
		<category><![CDATA[IDE]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[LLVM]]></category>
		<guid isPermaLink="false">https://blog.xojo.com/?p=3611</guid>

					<description><![CDATA[2017 has been a good year for Xojo! We hit some bumps but we&#8217;re ending the year with the much-awaited Xojo 64-bit IDE released in Xojo&#8230;]]></description>
										<content:encoded><![CDATA[<div>2017 has been a good year for Xojo! We hit some bumps but we&#8217;re ending the year with the much-awaited Xojo 64-bit IDE released in <a href="https://www.xojo.com/download/">Xojo 2017r3</a>.</div>
<div></div>
<div>Though we didn&#8217;t have a XDC in 2017, we&#8217;re gearing up for <a href="https://www.xojo.com/xdc/">XDC 2018 in Denver</a> in April. This is the longest between conferences in many years and we&#8217;re seeing an increase in early registrations. If you are planning on attending, please register soon. We have sold out before!</div>
<p><span id="more-3611"></span></p>
<div>Some highlights from the Xojo Blog in 2017:</div>
<ul>
<li>Growing? Read how one Xojo user took his app from <a href="https://blog.xojo.com/2017/04/25/taking-your-app-from-in-house-to-commercial/">in-house to commercial</a>,</li>
<li>Transitioning Windows Graphics: <a href="https://blog.xojo.com/2017/04/12/windows-graphics-direct2ddirectwrite-direction/">Direct2D/DirectWrite</a>,</li>
<li><a href="http://blog.xojo.com/2017/03/28/raspberry-pi-remote-debugging/">Remote Debugger for Raspberry Pi</a> and the <a href="https://blog.xojo.com/2017/04/12/windows-graphics-direct2ddirectwrite-direction/">Programming with Raspberry Pi Book</a>,</li>
<li>Check out our highly popular <a href="https://jsonfeed.org">JSON Feed</a> blog post series for <a href="https://blog.xojo.com/2017/05/31/json-feed-ios-app/">iOS</a>, <a href="https://blog.xojo.com/2017/05/30/json-feed-web-app/">web</a> and <a href="https://blog.xojo.com/2017/06/01/json-feed-desktop-app/">Desktop</a>,</li>
<li>We updated Xojo&#8217;s Linux Desktop framework to <a href="https://blog.xojo.com/2017/08/15/goodbye-gtk-2-hello-gtk-3/">GTK3</a> and HiDPI,</li>
<li>Whatever happens, Xojo has your back if <a href="https://blog.xojo.com/2017/09/29/what-it-means-for-your-xojo-projects-if-mac-goes-arm/">Mac goes ARM</a>, and</li>
<li>Jump into our ongoing Compiler blog post series: <a href="https://blog.xojo.com/2017/12/04/llvm-everywhere/">LLVM Everywhere</a>, <a href="https://blog.xojo.com/2017/12/06/compilers-101-overview-and-lexer/">Compiler 101 &#8211; Overview and Lexer</a>, and <a href="https://blog.xojo.com/2017/12/08/compilers-102-parser/">Compilers 102 &#8211; Parser</a>.</li>
</ul>
<p>A special mention on the topic of Net Neutrality in the US. Geoff has <a href="https://blog.xojo.com/2017/12/01/the-last-mile-why-net-neutrality-is-a-must/">shared his point of view</a> and we hope you make your voice heard to the <a href="https://www.fcc.gov/ecfs/filings/express">FCC</a> before December 14th. This is an issue that effects us all.</p>
<p>The Xojo community continues to grow with developers switching from VB, emerging citizen developers and small businesses all discovering what they can with Xojo. In the last 12 months the <a href="https://forum.xojo.com">Xojo Forum</a> has welcomed 1,688 new forum members and 60,772 forum posts.</p>
<p>Our blog post from back in June, <a href="https://blog.xojo.com/2017/06/21/daring-to-defy-software-extinction-a-limited-history/">Daring to Defy Software Extinction</a> sums up Xojo and Dev Tool history with some perspective. We&#8217;re proud of what we, along with the Xojo Community, have built over the past 21 years and we look forward to 2018 &#8211; Android support, I&#8217;m looking at you!</p>
<p><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-3010" src="https://blog.xojo.com/wp-content/uploads/2017/06/Ltd-History-of-Dev-Tools-Info-Graphic.png" alt="" width="800" height="2000" /></p>
<p>From everyone at Xojo, thank you for your continued support. This community is truly one-of-a-kind and we look forward to all that 2018 has in store!</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Dates…What&#8217;s the difference?</title>
		<link>https://blog.xojo.com/2017/10/31/dateswhats-the-difference/</link>
		
		<dc:creator><![CDATA[Javier Menendez]]></dc:creator>
		<pubDate>Tue, 31 Oct 2017 07:43:09 +0000</pubDate>
				<category><![CDATA[Learning]]></category>
		<category><![CDATA[AprendeXojo]]></category>
		<category><![CDATA[Date Class]]></category>
		<guid isPermaLink="false">https://blog.xojo.com/?p=3487</guid>

					<description><![CDATA[The Xojo.Core.Date and Xojo.Core.DateInterval classes make it really easy to get the difference between two given dates. But what if you want to get the same function for your current code based on the classic Date class?]]></description>
										<content:encoded><![CDATA[<p>Some days ago (or long, long ago, depending when do you read these lines) I received an email from a developer that was porting code from his old <a href="http://developer.xojo.com/migrating-from-visual-basic"><b>VisualBasic</b></a> domain to the native, multi-platform Xojo. He asked me how can to get the difference between two dates? I&#8217;m pretty sure that most of you will have the answer, but I told him he&#8217;ll need <a href="http://developer.xojo.com/xojo-core-date"><b>Xojo.Core.Date</b></a> and <a href="http://developer.xojo.com/xojo-core-dateinterval"><b>Xojo.Core.DateInterval</b></a>. If you want to know how easy it is or how to get the same result for all your code based on the <em>old</em> date class, then I invite you to continue reading…<span id="more-3487"></span></p>
<h2>Use the new Framework, Luke</h2>
<p>The <strong>Xojo.Core.Date</strong> and <strong>Xojo.Core.DateInterval</strong> classes under the <em>new</em>, Xojo framework make it really easy to get the difference between two given dates. The code you&#8217;ll need for this is as easy as this:</p>
<pre>Using Xojo.Core
Dim dateA As date = New Date(2017,10,23, TimeZone.current)
Dim dateB As date = New Date(2017,11,23, TimeZone.Current)
Dim result As DateInterval = dateB - dateA
MsgBox result.Years.ToText+ " " + result.Months.ToText + " " + result.Days.ToText</pre>
<p>The key here is in the use of the subtract operator that gives as result a <b>TimeInterval</b> instance. Thus, accessing the properties of this instance will get the years, months and days elapsed between the two compared dates. Take into account the importance of the order of your Date operands when used with the subtract operator. I mean, if the rightmost date is higher than the leftmost date, then probably you will get some negative values for the properties. In some cases, this will be the expected behaviour for the logic of your app… other times, you will prefer to check this before getting the DateInterval instance in order to get proper values.</p>
<h2>Date difference for existing code</h2>
<p>But, what if you want to get the same function for your current code based on the <b>date</b> class? Here you can opt for several options. The one we are going to put in practice is based in the use of the Xojo <b>Module</b> in combination with the <a href="http://developer.xojo.com/extends"><b>Class Extension</b></a> OOP feature. In fact, Class Extension is the way we can <em>extend</em> the functionallity of an existing Class. Straight, right? So, in order to achieve this the first step, add a new <b>Module</b> to a Xojo project and name it using the <b>Inspector Panel</b> (for example, &#8220;Extents&#8221;). Then, select the newly created module and add a new <b>Method</b> to it using the following signature:</p>
<ul>
<li><b>Method Name</b>: <code>Difference</code></li>
<li><b>Parameters</b>: <code>Extends d As Date, RightDate As Date</code></li>
<li><b>Return Type</b>: <code>Dictionary</code></li>
</ul>
<p>Next, we will add some text constants to the Module, that will be used by the Method and help any calling code that wants to access the result.</p>
<ul>
<li>kDay As String = Day</li>
<li>kDay As String = Month</li>
<li>kYear As String = Year</li>
</ul>
<p>Afterwards, select the <code>Difference</code> method and type the following lines of code in the resulting Code Editor:</p>
<pre>Dim difference As Double = RightDate.TotalSeconds - d.TotalSeconds
Dim days As Integer
Dim years As Integer
Dim months As Integer
Dim dateResult As New date
dateResult.TotalSeconds = difference
days = dateResult.Day - 1
years = dateResult.Year - 1904
months = dateResult.Month - 1
Dim result As New Dictionary
result.Value(kDay) = days
result.Value(kYear) = years
result.Value(kMonth) = months
Return result</pre>
<p>As you can see, the code is simple enough. In order to simplify the code to a maximum, this example opts to give the result as an Instance of Dictionary and using the previously definied constant to store the &#8220;Year&#8221;, &#8220;Months&#8221; and &#8220;Days&#8221; of difference between the compared dates. If you want, you can use an additional Structure or Class to return the result (your own DateInterval?).</p>
<p>To test the new Class Extension, add an Open Event to the Window or App object of your project and type this lines of code:</p>
<pre>Dim d As New date(2017,10,24)
Dim d1 As New date(2017,11,30)
Dim interval As Dictionary = d.Difference(d1)
MsgBox interval.Value(kYear) + " " + interval.Value(kMonth) + " " + interval.value(kDay)</pre>
<h2>A new Date Class that makes the Difference</h2>
<p>There is a third option that we can explore that is more OOP oriented: create our own Date class and implement the subtract operator on it. More or less the thing that we do when using Xojo.Core.Date.</p>
<p>For that, the first step is adding a new class to a Xojo Project (Insert &gt; Class). Use the following data in the Inspector Panel:</p>
<ul>
<li><strong>Name:</strong> MyDateClass</li>
<li><strong>Super:</strong> Date</li>
</ul>
<p>Next, add to the class the same constant we defined in the previous section (kDay, kMonth and kYear). These will be used to define the keys in the resulting dictionary and to ease operations from the calling code too.</p>
<p>The most important thing is adding a new Method to our class with the following data:</p>
<ul>
<li><strong>Method Name:</strong> Operator_Subtract</li>
<li><strong>Parameters:</strong> rightMostDate as Date</li>
<li><strong>Return Type:</strong> Dictionary</li>
</ul>
<p>The <strong>Operator_Subtract</strong> method instructs the Xojo compiler so you can use the minus sign (-) between two instances of the class. Type these lines of code for the method:</p>
<pre>Dim difference As Double = self.TotalSeconds - rightMostDate.TotalSeconds

Dim days As Integer
Dim years As Integer
Dim months As Integer

Dim dateResult As New date

dateResult.TotalSeconds = difference

days = dateResult.Day - 1
years = dateResult.Year - 1904
months = dateResult.Month - 1

Dim result As New Dictionary

result.Value(kDay) = days
result.Value(kYear) = years
result.Value(kMonth) = months

Return result</pre>
<p>Then in the Open Event of a Window, or the App object, check the class with the following code:</p>
<pre>Dim d2 As New MyDateClass(2017,10,24)
Dim d3 As New MyDateClass(2017,11,30)

interval = d3 - d2

MsgBox interval.Value(kYear) + " " + interval.Value(kMonth) + " " + interval.value(kDay)</pre>
<p><em>Javier Rodri­guez has been the Xojo Spanish Evangelist since 2008, he’s also a Developer, Consultant and Trainer who has be using Xojo since 1998. He manages <a href="http://www.aprendexojo.com">AprendeXojo.com</a> and is the developer behind the GuancheMOS plug-in for Xojo Developers and the Snippery app, among others.</em></p>
<p>*<a href="https://www.aprendexojo.com/2017/10/truco-restar-fechas-en-xojo/">Read this post in Spanish</a></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>ipify for Xojo</title>
		<link>https://blog.xojo.com/2017/09/26/ipify-for-xojo/</link>
		
		<dc:creator><![CDATA[Javier Menendez]]></dc:creator>
		<pubDate>Tue, 26 Sep 2017 18:40:12 +0000</pubDate>
				<category><![CDATA[Cross-Platform]]></category>
		<category><![CDATA[Desktop]]></category>
		<category><![CDATA[Learning]]></category>
		<category><![CDATA[API]]></category>
		<category><![CDATA[AprendeXojo]]></category>
		<guid isPermaLink="false">https://blog.xojo.com/?p=3407</guid>

					<description><![CDATA[pify is a very useful web service (an API) that promises to always be available to attend requests, letting us know the public (or external) IP address we are using to connect to Internet. Nevertheless, I found ipify to be the simplest and easiest to use, plus it is highly available due to being hosted by Heroku. That means, for example, that if half the Internet is down…you still can be confident to reach the ipify service in order to get the information.]]></description>
										<content:encoded><![CDATA[
<p><a href="https://www.ipify.org"><b>ipify</b></a> is a very useful web service (an API) that promises to always be available to attend requests, letting us know the public (or external) IP address we are using to connect to Internet. We can get this small piece of information as pure Text or in JSON or XML formats.</p>



<p><strong>This post was <a href="https://blog.xojo.com/2021/09/03/update-ipify-for-xojo/">updated in 2021</a> to using Xojo&#8217;s API 2.0.</strong></p>



<span id="more-3407"></span>



<p>There are plenty of times when your Xojo apps might need to know what the public or external IP address in use is, and for that there are a lot of web sites or services that you can use from Xojo. Nevertheless, I found <strong>ipify</strong> to be the simplest and easiest to use, plus it is highly available due to being hosted by <a href="http://heroku.com">Heroku</a>. That means, for example, that if half the Internet is down…you still can be confident to reach the ipify service in order to get the information.</p>



<p>Using ipify from a Xojo desktop apps is as simple as using this code:</p>



<pre class="wp-block-preformatted">Dim request as New HTTPSSocket
Dim s as String = request.get("https://api.ipify.org",10)</pre>



<p>But sometimes we need additional information, for example knowing if the IP address has changed over time, or simply checking periodically for IP address changes. And that is something that you can find in the OpenSource project <strong>ip</strong><b>ify for Xojo</b> available in <a href="https://github.com/aprendexojo/IPify">this repository from GitHub</a>.</p>



<p><b>ipify for Xojo</b> is designed as a <a href="https://blog.xojo.com/2016/06/08/design-patterns-in-xojo-singleton/">Singleton class</a>, what means that you even don&#8217;t need to instatiate it in order to get the current IP address, know if the IP has changed over time, or even instruct the class to periodically check for the IP address, notifying the registered object every time with the current IP address in use and if it is the same or has changed from the last checking.</p>



<p><a href="https://github.com/aprendexojo/IPify">Download IPify for Xojo from GitHub</a></p>



<p><em>Javier Rodri­guez has been&nbsp;the Xojo Spanish&nbsp;Evangelist since 2008, he’s also a Developer, Consultant and Trainer who&nbsp;has be using&nbsp;Xojo since 1998. He manages&nbsp;<a href="http://www.aprendexojo.com">AprendeXojo.com</a> and is the developer behind the GuancheMOS plug-in for Xojo Developers and the Snippery app, among others.</em></p>



<p>*<a href="http://www.aprendexojo.com/2017/09/ipify-para-xojo/">Read this post in Spanish</a></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>RSA: Private/Public keys between Xojo and PHP</title>
		<link>https://blog.xojo.com/2017/06/06/rsa-privatepublic-keys-between-xojo-and-php/</link>
		
		<dc:creator><![CDATA[Javier Menendez]]></dc:creator>
		<pubDate>Tue, 06 Jun 2017 04:37:26 +0000</pubDate>
				<category><![CDATA[Learning]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[AprendeXojo]]></category>
		<category><![CDATA[Crypto]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[RSA]]></category>
		<guid isPermaLink="false">http://blog.xojo.com/?p=2767</guid>

					<description><![CDATA[Among other topics, Cryptography and data ciphering always fascinated me. Beyond their mathematical perspective, most of the time it is a matter of putting them&#8230;]]></description>
										<content:encoded><![CDATA[<p>Among other topics, Cryptography and data ciphering always fascinated me. Beyond their mathematical perspective, most of the time it is a matter of putting them in practice with developed solutions: dealing with data only visible between the transmitter and the receiver. As it happens, the Xojo framework makes it really easy to deal with ciphered data.<span id="more-2767"></span></p>
<p>All the methods related to cryptography and data ciphering are available under the <a href="http://developer.xojo.com/xojo-crypto"><b>Crypto</b></a> module of Xojo, using behind the scene the Crypto++ 5.6.3 library. From the practical side, this allows us to use the <strong>RSA</strong> public key ciphering and other algorithms to compute unique footprints for given data, as for example <a href="http://developer.xojo.com/xojo-crypto$Hash"><b>Hash</b></a>, <a href="http://developer.xojo.com/xojo-crypto$MD5"><b>MD5</b></a> or <a href="http://developer.xojo.com/xojo-crypto$SHA1"><b>SHA</b></a>. <a href="https://blog.xojo.com/2014/02/05/using-publicprivate-key-encryption-in-xojo/">Paul blogged</a> about using Public/Private Key Encryption in Xojo back when we added RSA encryption functions in 2014.</p>
<p>Among the methods related to RSA, we can find the ones to create the Private/Public keys, test the integrity of the public key, signing the given data and, of course, check the integrity of the signature, and ciphering / deciphering the given group of data.</p>
<p>As you probably already know, when we work with RSA we have to keep the Private key in a safe place, using the Public one to give to other people/service/app to whom we want to share information with in a safe manner. This way the users and/or apps and services will be able to use our public key to cipher the data that they want to share with us, and we will be able to use our private key to decipher that group of data so it is <em>legible</em> again.</p>
<h1>RSA: Creating and interchanging the keys</h1>
<p>Generating the pair of keys could not be more easy in Xojo, with this snippet of code:</p>
<pre>Dim publicKey As String
Dim privateKey As String
If Crypto.RSAGenerateKeyPair( 1024, privateKey, publicKey ) Then msgBox “Successfully generated Keys!"</pre>
<p>As you can see, the <a href="http://developer.xojo.com/xojo-crypto$RSAGenerateKeyPair"><b>RSAGenerateKeyPair</b></a> method receives the Integer number that indicates the strength (robustness) of the generated keys, followed by the String variables containing the generated Private and Public keys, passed by reference.</p>
<p>But in some cases it is possible that you want to use these keys beyond the scope of Xojo, for example when integrating your app with a service or solution developed in PHP. In these cases you have to consider that the keys generated with Xojo are in hexadecimal format.</p>
<p>What does this mean? Well, a public key generated with Xojo will look like this chunk of data:</p>
<pre>30819D300D06092A864886F70D010101050003818B0030818702818100B4B531D3402C250D8640E739601F01FBE8ABB39635BE1778A7F4E55C49419C0595EF5A5824EA8E7A1871FB63B8960EDBB97B08C2E7EA43229903AEBCB45B9FD9E24780B15BCADB5E026849592CC1FA9B399EBD8457CC4E7A686CF53E9146E1D867ACEB675728E8821DEDA4C2F807FD668A81601F551484C5D1334B62D5E90E33020111</pre>
<p>While other external libraries (as is the case in most of the web development frameworks), expect other data format codified as Base64. This is, something like this:</p>
<pre>-----BEGIN PUBLIC KEY-----

MIGHAoGBALS1MdNALCUNhkDnOWAfAfvoq7OWNb4XeKf05VxJQZwFle9aWCTqjnoYcftjuJYO27l7
CMLn6kMimQOuvLRbn9niR4CxW8rbXgJoSVkswfqbOZ69hFfMTnpobPU+kUbh2Ges62dXKOiCHe2k
wvgH/WaKgWAfVRSExdEzS2LV6Q4zAgER

-----END PUBLIC KEY-----</pre>
<p>So the first step to encode our Xojo keys (Public or Private ones) as Base64 is converting them previously from his hexadecimal form to the DER encoding (<em>Distinguished Encoding Rules</em>). Here is where we have to employ the <a href="http://developer.xojo.com/xojo-crypto$DEREncodePrivateKey"><b>DEREncodePrivateKey</b></a> and <a href="http://developer.xojo.com/xojo-crypto$DEREncodePublicKey"><b>DEREncodePublicKey</b></a> methods if we want to encode the Private or the Public key, respectively. Once we have done this, we will be able to encode the resulting chunk of data as Base64 without forgetting to add the header <code>“—–BEGIN PUBLIC KEY—–“</code> and the footer <code>“—–END PUBLIC KEY—–“</code> with the accompanying ends of lines, or maybe the header <code>“—–BEGIN CERTIFICATE—–”</code> and the footer <code>“—–END CERTIFICATE—–“</code> if we are dealing with a Public Key (for the Private keys we have to use the header <code>“—–BEGIN RSA PRIVATE KEY—–”</code> and the footer <code>“—–END RSA PRIVATE KEY—–“</code>).</p>
<p>You can interchange and use the Private and Public keys generated with Xojo using the <a href="http://phpseclib.sourceforge.net/">PHPSecLib</a> library.</p>
<p>In addition, as pointed by <a href="https://thezaz.com/">Thom McGrath</a>, you can use also these keys with OpenSSL this way:</p>
<pre>if (@openssl_public_encrypt($data, $result, $public_key, OPENSSL_PKCS1_OAEP_PADDING)) {
         return $result;
 } else {
         throw new \Exception('Unable to encrypt');
 }</pre>
<p>Xojo&#8217;s Crypto library will be able to use a private key to decrypt $result in this case.</p>
<p>Finally, if you are interested in the cryptography topic, let me recommend you some good books: <a href="https://www.schneier.com/books/applied_cryptography/" target="_blank" rel="noopener noreferrer">Applied Cryptography</a> and <a href="http://eu.wiley.com/WileyCDA/WileyTitle/productCd-0470474246.html" target="_blank" rel="noopener noreferrer">Cryptography Engineering</a>.</p>
<p><em>Javier Rodri­guez has been the Xojo Spanish Evangelist since 2008, he’s also a Developer, Consultant and Trainer who has be using Xojo since 1998. He manages <a href="http://www.aprendexojo.com/">AprendeXojo.com</a> and is the developer behind the GuancheMOS plug-in for Xojo Developers and the Snippery app, among others.</em></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>ContainerControl: Making a Multiplatform Search Field</title>
		<link>https://blog.xojo.com/2017/04/26/containercontrol-making-a-multiplatform-search-field/</link>
		
		<dc:creator><![CDATA[Javier Menendez]]></dc:creator>
		<pubDate>Wed, 26 Apr 2017 18:16:47 +0000</pubDate>
				<category><![CDATA[Cross-Platform]]></category>
		<category><![CDATA[Desktop]]></category>
		<category><![CDATA[Learning]]></category>
		<category><![CDATA[AprendeXojo]]></category>
		<category><![CDATA[Graphics]]></category>
		<category><![CDATA[Multi-Platform Development]]></category>
		<guid isPermaLink="false">http://blog.xojo.com/?p=2596</guid>

					<description><![CDATA[Create the basis of a multiplatform search field based on the ContainerControl class for Desktop and Web apps.]]></description>
										<content:encoded><![CDATA[<p>The ContainerControl is one of the most versatile control classes included in the Xojo framework both for Desktop and Web apps. In fact, it paves the way to complex UI controls creation with the same simplicity you are used to while designing your window layouts. Even better, once you create your complex UI controls using the ContainerControl, you will be able to add them to your Window layouts as if they were regular controls. Plus, you will enjoy the fruits of better OOP encapsulation and the fact that you can create and use the controls dynamically at run time. Want to see this in action? Follow this tutorial and video to create the basis of a multiplatform search field based on the ContainerControl class.<span id="more-2596"></span></p>
<p>The following tutorial is based on the Desktop Xojo project that you can <a href="https://www.dropbox.com/s/hwr2ehikiz41vop/Xojo-Search%20Control.zip?dl=1">download from this link</a>. In fact, this project was the foundation to the search filed control implemented in the <a href="http://www.aprendexojo.com/software/snippery/">Snippery</a> app. Thus, you can envision in more detail the kind of functionality you can achieve when used in a real app. Ok, maybe you are thinking &#8220;this is not the native control a user expects when using a true native app under certain OS&#8221;. That&#8217;s true; anyway there are a lot of apps around (some of them from the big players) that use non-native controls in favour of providing a unified UI between all supported platforms. This is the case of the final class exposed here, offering the same aspect and behaviour when running under macOS, Windows and Linux.</p>
<h2>Preparing the Ingredients</h2>
<p>In order to create our multiplatform search control we need to use a series of components (classes) that will cooperate with each other: a <a href="http://blog.xojo.com/2017/02/06/textfield-getting-the-user-input/">TextField</a> that will receive the user keyboard input (that is, where the user inputs the text to search); a Canvas subclass to display the typical magnifying glass icon and other decoration for the control (that also extends further to add more functionality); and a second Canvas subclass that will offer the classic &#8220;search text clean&#8221; widget functionality normally presented at the right of a search field.</p>
<p>Of course, you can create a search field using these classes as individual items on a Window layout, but in that case all the resizing operations and cooperation between the controls will be more messy &#8212; losing the encapsulation that a ContainerControl provides to the other components of the application as if it was a unique, simple control.</p>
<h2>Dealing with the Graphics</h2>
<p>The resulting control uses three pictures for a total of two functions: one for the magnifying glass and two for the &#8220;text cleaning&#8221; widget that will be displayed only when the TextField has text on it. The widget has to change its image when the pointer is on it so the user can see that this is an active &#8220;clickable&#8221; control.</p>
<p>Fortunately Xojo eases the management of multiresolution pictures in our apps, changing on the fly between the existing regular/normal resolution and the <a href="http://developer.xojo.com/hidpi-support">HiDPI/Retina</a> versions for the same given picture. Thus, we only need to use our favourite graphics editor app to draw and export the pictures with the required quality as PNG files (personally I use the <a href="https://www.sketchapp.com/">Sketch</a> on macOS).</p>
<p>In order for Xojo to be able to do its magic, you shouldn&#8217;t import the pictures to the app by dragging them from disk and dropping them on the Project Browser or Xojo will import the pictures as an alias. Instead, use the Insert &gt; Image option to add an Image instance to the project, showing the associated Editor where you&#8217;ll be able to assign every picture file for the supported resolutions of a same graphic. Of course the label you use as the Image name on the Inspector Panel will be the name you use to reference the Image from code or when assigned to other controls properties. If you explore the example project for this tutorial, you can see the three Images used: searchIcon, CloseSelected and Close in regular and HiDPI/Retina resolutions.</p>
<p><img loading="lazy" decoding="async" class="size-full wp-image-2597 aligncenter" src="https://blog.xojo.com/wp-content/uploads/2017/04/Image-Xojo.png" alt="" width="621" height="716" /></p>
<h2>Creating the Text Cleaning Widget</h2>
<p>We have already seen in a <a href="http://www.aprendexojo.com/2016/10/canvas-crea-tus-propios-controles/">previous tutorial</a> (in Spanish) how easy it is to create custom graphic controls in Xojo based on the Canvas Class. In order to create the widget providing the search text cleaning feature, we will follow that same principle here:</p>
<ul>
<li>Add a Canvas subclass and name it CloseButtonClean.</li>
<li>Add the Open, MouseEnter and MouseExit events to the subclass</li>
<li>Type the following code into the Open event, basically to assign the picture showing its initial state and making it invisible:</li>
</ul>
<pre>me.Backdrop = close
me.Visible = false</pre>
<ul>
<li>We will use the MouseEnter and MouseExit events to change the displayed picture in response to  the pointer cursor being inside or outside the limits of the control; showing that this is an active/clickable control. Put the following line of code in the MouseEnter event:</li>
</ul>
<pre>me.Backdrop = CloseSelected</pre>
<ul>
<li>And the following one in the MouseExit event of the control:</li>
</ul>
<pre>me.Backdrop = close</pre>
<p>We have completed the decoration of our little class, but it is also desirable to provide an external interface so other controls can easily change the state of the widget. We will do that by adding two methods to the class.</p>
<p>With the widget class still selected on the Project Browser, select the Insert &gt; Method option twice to add two Methods and using the Inspector Panel to change the Method names to &#8220;Activate&#8221; and &#8220;Deactivate&#8221;, respectively. Leave the Scope as Public for both methods, so they are reachable by other objects and not only those created from the class.</p>
<p>The select method simply changes the control visibility to True:</p>
<pre>me.Visible = true</pre>
<p>While the Deactivate method will do the opposite action:</p>
<pre>me.Visible = false
me.Backdrop = Close</pre>
<h2>Drawing the Search Control</h2>
<p>The second of the required classes based on the Canvas class is no more complex. In this case we will not assign a picture to the Backdrop property of the Canvas, instead we will use the Paint event to directly draw the decoration, including the magnifying glass picture at the appropriate coordinates of the control.</p>
<p>So, after adding a second Canvas subclass to the project —named cSearchBackground in our Example project—, we just need to add the Paint event to it, writing the following lines of code on the associated Code Editor:</p>
<pre>g.PenWidth = 1
g.PenWidth = 1
g.ForeColor = &amp;caaaaaa
g.DrawRoundRect(0,0,g.Width,g.Height,5,5)
g.ForeColor = &amp;cffffff
g.FillRoundRect(1,1,g.Width-2, g.Height-2,5,5)
dim midY as integer = (g.Height/2) - (searchIcon.Graphics.Height/2)
g.DrawPicture(searchIcon,5,midy)</pre>
<p>In essence, we are drawing the control border using the provided foreground color (&amp;caaaaaa, in hex notation), and filling the control background with the white color. After that, we will paint the magnifying glass icon using the DrawPicture method of the Graphic class provided as the drawing context for the Paint event.</p>
<h2>Container Control: Putting it all Together</h2>
<p>Once we have all the required items for our &#8220;complex&#8221; UI control, it&#8217;s time to add a ContainerControl to the project using the Insert &gt; ContainerControl option. The first thing you probably notice is that the Layout Editor is very similar to the one used for designing the windows of the app. After all, the ContainerControl is about adding, resizing and aligning several UI controls on it, as you do when designing a window.</p>
<p>With the added ContainerControl still selected, change the attribute Name to ContainerSearchField on the associated Inspector Panel.</p>
<p>Now we just need to add an instance of our cSearchBackground class to the ContainerControl, a TextField control from the Xojo Library Panel and our search text cancelation widget class to the right of the just added TextField. The final layout of the control should be something similar to this (after adjusting the own Container Control height and width):</p>
<p><img loading="lazy" decoding="async" class="size-full wp-image-2598 aligncenter" src="https://blog.xojo.com/wp-content/uploads/2017/04/ContainerControl.png" alt="" width="475" height="179" /></p>
<p>In order to correctly draw the control background when resizing the ContainerControl, select the cSearchBackground instance and add the Open event with the following line of code:</p>
<pre>me.Width = self.Width</pre>
<p>In addition, we also want that the TextField to show our search text cancellation widget only if the TextField has text on it. Select the TextField instance on the ContainerControl (searchField in the example project), and add the TextChange event with the following code in the associated Code Editor:</p>
<pre>if me.Text &lt;&gt; "" then
  CloseButtonClean1.activate
else
  CloseButtonClean1.deactivate
end if</pre>
<p>With the TextField still selected, set the CueText property under the Initial State section of the Inspector Panel to &#8220;Search&#8221;. This will be the text shown by default when the TextField is empty.</p>
<p>Of course we want to add functionality to the instance of our search text cancelation widget —named CloseButtonClean1 in the example project—. Add the MouseDown event and write the following line of code on the associated Code Editor:</p>
<pre>searchField.Text = ""</pre>
<p>When using a ContainerControl you will want to provide a way to resize every control inside of it in response to the resizing of the ContainerControl itself. We resolve this by adding the doResize method to our Container Control with the following code:</p>
<pre>closeButtonClean1.Left = me.Width - 24

searchField.Width = (Me.Width - 27) - searchField.Left

cSearchBackground1.Width = me.Width

cSearchBackground1.Invalidate</pre>
<p>As you can see this method simply does some calculations to reposition the controls based on their relative coordinates, updating also the width of the background control to reflect the same width of the ContainerControl itself. Finally it calls the invalidate method on the background instance class so the control can update the drawing.</p>
<p>In order to finish our ContainerControl subclass, we just need to add a couple of events: Open and Resizing. The first will be in charge of setting the initial state for the control, while the second will call the doResize method every time the ContainerControl is resized.</p>
<p>Once you&#8217;ve added these events, select them and simply write the call to the doResize method in both cases.</p>
<h2>Using the SearchField ContainerControl</h2>
<p><img loading="lazy" decoding="async" class="size-full wp-image-2599 aligncenter" src="https://blog.xojo.com/wp-content/uploads/2017/04/Control-Container-Search-en-uso-1024x605.png" alt="" width="1024" height="605" /></p>
<p>That&#8217;s all! You can start using the control by dragging it from the project browser to the Window Layout in order to create a new instance. Of course, we have not implemented the search functionality itself in this example project, mainly because it depends of the purpose of the final application itself. In addition, it would be easy for you to add extra functionality as <a href="http://blog.xojo.com/2016/08/10/textfield-with-autocomplete/">text autocompletion</a> as we have seen in a previous tutorial.</p>
<p><em>Javier Rodri­guez has been the Xojo Spanish Evangelist since 2008, he’s also a Developer, Consultant and Trainer who has be using Xojo since 1998. He manages <a href="http://www.aprendexojo.com">AprendeXojo.com</a> and is the developer behind the GuancheMOS plug-in for Xojo Developers and the Snippery app, among others.</em></p>
<p>*<a href="http://www.aprendexojo.com/2017/04/container-control-en-xojo/">Read this post in Spanish</a></p>
<p>*<a href="https://youtu.be/qC-EFl6xW9A">Watch the video in Spanish</a></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Raspberry Pi and Xojo: Configure for Remote Access</title>
		<link>https://blog.xojo.com/2016/12/09/raspberry-pi-and-xojo-configure-for-remote-access/</link>
		
		<dc:creator><![CDATA[Javier Menendez]]></dc:creator>
		<pubDate>Fri, 09 Dec 2016 17:38:02 +0000</pubDate>
				<category><![CDATA[Learning]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[Raspberry Pi]]></category>
		<category><![CDATA[AprendeXojo]]></category>
		<category><![CDATA[GPIO]]></category>
		<category><![CDATA[RPi]]></category>
		<category><![CDATA[Xojo Programming Language]]></category>
		<guid isPermaLink="false">http://blog.xojo.com/?p=2117</guid>

					<description><![CDATA[A simple, step-by-step guide to configure your Raspberry Pi so you can use your display, keyboard and mouse to start building RPi apps in Xojo.]]></description>
										<content:encoded><![CDATA[<p><strong>Xojo</strong> is a superb choice for developing and deploying apps for <strong>Raspberry Pi</strong>. After all, Xojo not only simplifies making the User Interface of your apps via drag and drop, it&#8217;s an object-oriented and event oriented programming language that builds native <strong>Linux</strong> apps based on the <strong>ARM</strong> processor architecture for the Raspberry Pi (<a href="https://blog.xojo.com/2015/10/23/true-cross-platform-in-a-single-license-xojo-pro/">among other platforms</a>).</p>
<p><span id="more-2117"></span><br />
The Raspberry Pi is a complete computer —and a very cheap one!— with USB, HDMI, Ethernet and a <a href="http://developer.xojo.com/gpio" target="_blank" rel="noopener"><strong>GPIO</strong></a> that gives the access to design, create, and control a lot of things (think IoT). The perfect combination to create and deploy complete solutions with Xojo.</p>
<p>Nevertheless, you probably don&#8217;t want to use an exclusive display, keyboard and mouse just to control and interact with your Raspberry Pi. What about accessing it remotely via <strong>SSH</strong> and/or <strong>VNC</strong>? I bet this is the first thought you had, and here is a step-by-step guide to configure it so you can use your current display, keyboard and mouse from you main computer (the one you use to run the Xojo IDE) to control the Raspberry Pi.</p>
<p>First of all, while you can access your RPi via SSH, displaying your well trained Geek super powers, it is really more convenient to control it via the GUI, as you do your computer. For that you&#8217;ll need a VNC client app. There are a lot out there, but <a href="https://www.realvnc.com/download/viewer/" target="_blank" rel="noopener"><strong>VNC Viewer</strong></a> is one that runs just fine and is available for the main platforms. Just download it, run the installer, follow the steps… and you will have completed the first part of the process.</p>
<p>In order to access the Raspberry Pi from the VNC client you will need to know what IP address is using the Pi. How to get that information? Easy! (This assumes that your local network uses DHCP to assign IP addresses, the most common scenario.)</p>
<p>If you use macOS, open the Terminal app (Applications &gt; Terminal) and run the command:</p>
<pre>$ ping 192.168.1.255</pre>
<p>Changing the &#8216;192.168.1&#8217; part of the IP address for the one of your local network. What is important here is the &#8216;255&#8217; number, because this is the Broadcast IP address for your local network.</p>
<p>What happens when we ping the broadcast address? In brief: the packets are sent to every host of the local area so they can respond, giving their IP address in the process. The second piece of the needed information, the MAC Address, is automatically obtained from the hardware interface used by the device to reply the packet request.</p>
<p>Let the ping command do its work for several seconds and break the process pressing Control + C. (If you are using Linux, execute the command as &#8216;<code>ping -b xxx.xxx.xxx.255</code>&#8216;.</p>
<p>The Mac Address is all the information needed by <strong>ARP</strong>: the inner cache table used by your router/switch device (and computer too), to link the unique hardware address (MAC Address) used by every device in the network with the IP address used by the device. So, executing the command:</p>
<pre>$ arp -a</pre>
<p>will give us a complete list of evey active IP address and the linked MAC Address. Knowing what IP addresses are already used by the devices of our network (computers, printers, cell phones, tablets…), it will be easy to identify the IP address assigned by <strong>DHCP</strong> to the Raspberry Pi.</p>
<p><img loading="lazy" decoding="async" class="alignnone size-full wp-image-2118" src="https://blog.xojo.com/wp-content/uploads/2016/11/ARP.jpg" alt="arp" width="699" height="237" /></p>
<p>So with these two pieces of information you can use the DHCP Binding feature of your home switch/router (all the home/SOHO routers have this feature), in order to assign the same IP address to the Raspberry PI every time you turn the device on and, connect it to the network. DHCP Binding looks for the MAC Address of the device… and matches it with the reserved IP address from the DHCP pool.</p>
<p><img loading="lazy" decoding="async" class="alignnone size-full wp-image-2119" src="https://blog.xojo.com/wp-content/uploads/2016/11/DHCPBinding.jpg" alt="dhcpbinding" width="748" height="99" /></p>
<h2>Starting the VNC Server on the Raspberry Pi</h2>
<p>Don&#8217;t close the Terminal window yet, there are a couple of things that we need to do first. The first one is starting the VNC Server on the Raspberry Pi, so we can start new remote sessions from our client. For that we need to start an SSH session with:</p>
<pre>$ ssh pi@raspberry-pi-address-here</pre>
<p>Typing &#8216;raspberry&#8217; as the password when requested. (&#8216;pi&#8217; and &#8216;raspbery&#8217; are the user and password configured by default on every Raspberry Pi out there.)</p>
<p>Once started the SSH session, type the following:</p>
<pre>pi@raspberrypi:~$ sudo raspi-config

<img loading="lazy" decoding="async" class="alignnone size-full wp-image-2120" src="https://blog.xojo.com/wp-content/uploads/2016/11/ConfigurationTool.png" alt="configurationtool" width="682" height="501" /></pre>
<p>This will open the <strong>Configuration Tool</strong>. Use the cursor keys to choose the &#8216;Advanced Options&#8217; entry and press the Return key to advance to a new screen with options. Select the VNC entry (A5) and press the Return key again. Finally, make sure that VNC Server is enabled or enable it if not. Lastly, select the &lt;Finish&gt; option to exit the Configuration Tool.</p>
<h2>Adjusting the Display Resolution used by VNC</h2>
<p>Great, we have the IP address used by the Raspberry Pi, and the VNC Server enabled so we can start a VNC Client session… just to discover that it shows an endemic resolution of 800 x 600 pixels on our full-fledged Full HD display. Not the most productive thing we can expect.</p>
<p>Time to return to our Terminal windows, where the SSH session is still open (or start a new one if not). This time, we will edit the configuration file to instruct the Raspberry Pi to use a better fixed display resolution. For that, type the command:</p>
<pre>pi@raspberrypi:~$ sudo nano /boot/config.txt</pre>
<p>Go to the end of the opened file and write these lines:</p>
<pre> hdmi_force_hotplug=1
 hdmi_ignore_edid=0xa5000080
 hdmi_group=2
 hdmi_mode=51</pre>
<p>In this case we are telling the Raspberry Pi to use a resolution of 1.600 x 1.200 pixels, but you can choose other changing the &#8216;hdmi_mode&#8217; option to anyone of the settings you can find in <a href="https://www.raspberrypi.org/documentation/configuration/config-txt.md" target="_blank" rel="noopener">this support page of Raspberry Pi</a>.</p>
<p>Save the changes and exit from the Nano editor, and reboot the Raspberry Pi so the changes take effect:</p>
<pre> pi@raspberrypi:~$ sudo su
 pi@raspberrypi:~$ reboot

</pre>
<pre><img loading="lazy" decoding="async" class="alignnone size-full wp-image-2121" src="https://blog.xojo.com/wp-content/uploads/2016/11/VNC-Session.png" alt="vnc-session" width="1908" height="1090" /></pre>
<p>Ready! From now on, you can remotely access your Raspberry Pi via VNC and SSH.</p>
<p>You can watch <a href="https://www.youtube.com/watch?v=6sKkbj6rxuU" target="_blank" rel="noopener">the video</a> (in Spanish only) that talks you though this example.</p>
<p><em>Javier Rodri­guez has been the Xojo Spanish Evangelist since 2008, he’s also a Developer, Consultant and Trainer who has used Xojo since 1998. He is in charge of <a href="http://www.aprendexojo.com">AprendeXojo.com</a> and the developer behind the GuancheMOS plug-in for Xojo Developers and the Snippery app, among others.</em></p>
<p>*<a href="http://www.aprendexojo.com/2016/11/configuracion-inicial-de-tu-raspberry-pi/">Read this post in Spanish</a></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Design Patterns in Xojo: Observer, Part II</title>
		<link>https://blog.xojo.com/2016/11/15/design-patterns-observer-part-ii/</link>
		
		<dc:creator><![CDATA[Javier Menendez]]></dc:creator>
		<pubDate>Tue, 15 Nov 2016 07:24:08 +0000</pubDate>
				<category><![CDATA[Learning]]></category>
		<category><![CDATA[AprendeXojo]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Object-Oriented]]></category>
		<category><![CDATA[Observer]]></category>
		<category><![CDATA[Singleton]]></category>
		<guid isPermaLink="false">http://blog.xojo.com/?p=2070</guid>

					<description><![CDATA[In previous blog entries we saw how easy it is to implement the Design Pattern Singleton and how we can find the Observer Design Pattern&#8230;]]></description>
										<content:encoded><![CDATA[<p>In previous blog entries we saw how easy it is to implement the Design Pattern <a href="http://blog.xojo.com/2016/06/08/design-patterns-in-xojo-singleton/">Singleton</a> and how we can find the <a href="http://blog.xojo.com/2016/06/15/design-patterns-in-xojo-observer-part-1/">Observer</a> Design Pattern already implemented on several Xojo features by default, greatly simplifying our code and interaction between the objects. Now, as promised, it is time to put it all in practice, creating our own Notification Center: a class that will allow us to share the same unique instance for the entire App (Singleton), and that can use any object in order to register itself for receiving notifications by the observed Control, for one or more message (the notifications themselves).<span id="more-2070"></span><br />
In addition, the designed Class will allow you to unsubscribe any of the previously registered objects, either to stop receiving notifications by the observed object at all, or just some of the previously registered notifications.</p>
<p>The <a href="http://blog.xojo.com/2016/06/08/design-patterns-in-xojo-singleton/">Singleton</a> and <a href="http://blog.xojo.com/2016/06/15/design-patterns-in-xojo-observer-part-1/">Observer</a> Design Patterns have been described in previous blog entries and I highly recommend to read them now so you can get the flavor of the fundamentals behind them. I&#8217;ll wait here for you, I promise! Then we will deal with the code that varies to implement our <strong>NotificationCenter</strong> class, and to put it in practice with a Desktop example project.</p>
<p>Of course, before of continuing reading, you can <a href="https://www.dropbox.com/s/ry6ip9oe5jkm4av/Xojo-Observer-II.zip?dl=1">download the example project,</a> run it and review the code to get a first glance of what it does and how it works. Then, you can come back and continue reading if you want to better understand the <strong>NotificationCenter</strong> class inner, or how other objects can use this class.</p>
<h2>The NotificationCenter Class</h2>
<p>Execute the <strong>Xojo</strong> IDE and create a new Desktop project. Add a new class using <strong>Insert &gt; Class</strong>. Go to the Inspector and change the <strong>Name</strong> attribute to &#8220;NotificationCenter&#8221;. This is the name of the new class we are designing (and, thus, a new Data Type).</p>
<p>With the new class still selected in the Navigator (the leftmost column on the Xojo IDE), add a new <strong>Shared Property</strong> (<strong>Insert &gt; Shared Property</strong>). Use the Inspector again to change the <strong>Name</strong> attribute to &#8220;Instance&#8221;, the Type field to &#8220;NotificationCenter&#8221; and the <strong>Scope</strong> to &#8220;Private&#8221;. (You know, a Shared Property or Shared Method are those that you can access from the class itself, without needing to create previously a new instance from the class.)</p>
<p>Add a second Property to the class, this time via <strong>Insert &gt; Property</strong> (this is, an instance property). Use this values on the associated Inspector:</p>
<ul>
<li><strong>Name:</strong> Objects</li>
<li><strong>Type:</strong> Xojo.Core.Dictionary</li>
<li><strong>Scope:</strong> Private</li>
</ul>
<p>Next, add a new Method (<strong>Insert &gt; Method</strong>). Use the Inspector to choose the <strong>Constructor</strong> option from the &#8220;Method Name&#8221; dropdown menu, and set the method Scope to Private.</p>
<p>Write the following code on the associated Code Editor for the method:</p>
<pre>Objects = new xojo.core.Dictionary</pre>
<p>Defining the Constructor method with a Private scope prohibits the creation of several instances from the class. Instead of that, the class consumers will have to use the convenience method defined by us in order to retrieve the same —and unique— instance for all the cases.</p>
<p>So, now we will add a new Shared Method using <strong>Insert &gt; Shared Method</strong>. Use the Inspector to put the following values on the created method:</p>
<ul>
<li><strong>Name:</strong> SharedInstance</li>
<li><strong>Return Type:</strong> NotificationCenter</li>
</ul>
<p>And write the following code in the associated Code Editor for the method:</p>
<pre>if instance = nil then instance = new NotificationCenter
Return instance</pre>
<p>These are the wires to write our Singleton class and to define our Data Model: the &#8220;Objects&#8221; property of data type <a href="http://developer.xojo.com/xojo-core-dictionary"><strong>Xojo.Core.Dictionary</strong></a>. This property will be responsible for storing the registered objects as observers of the desired Control(s), as well as the messages for whom it is interested in receiving notifications for the observed object(s). Probably this is better understood in the following figure:</p>
<p><img loading="lazy" decoding="async" class="size-full wp-image-2072 aligncenter" src="https://blog.xojo.com/wp-content/uploads/2016/11/DataModel.png" alt="Data Model for Notification Center Class" width="485" height="551" />That is, the &#8220;Observers&#8221; Xojo.Core.Dictionary Property uses as <strong>Key</strong> any object of <a href="http://developer.xojo.com/rectcontrol">RectControl</a> data type (the observed object). The associated value for that key is a new Xojo.Core.Dictionary, whose entries will use as Key the Notification (message as Text data type) for what an object wants to register as observer for such Control.</p>
<p>This way, one same object can be registered to several controls and also to several messages (Notifications) on one or several controls.</p>
<p>Finally, the associated value for every <strong>Key</strong> on this second Xojo.Core.Dictionary is an <strong>Array</strong> data type whose items are instances of the <strong>NotificationReceiver</strong> data type.</p>
<p>I know, I know… Stop. Breathe. Execute again the example project. Review the code on the &#8220;Register&#8221; method to get a better grasp… and back to follow!</p>
<h3>Registering Observers</h3>
<p>With the class still selected on the Navigator, add a new method (<strong>Insert &gt; Method</strong>) using the following values. This is the method responsible for registering the new observers on the shared Notification Center instance:</p>
<ul>
<li><strong>Name:</strong> Register</li>
<li><strong>Parameters:</strong> sourceControl as NotificationReceiver, observedObject as RectControl, message as Text</li>
<li><strong>Scope:</strong> Public</li>
</ul>
<p>As you can see in &#8220;Parameters&#8221;, the first parameter is the Observer object (this is the interesed object in receiving the notifications); the second parameter is the observed object (that is from which we want to receive notifications); and the third parameter is the message from which we are interested in receiving the notifications by the observed object.</p>
<p>Write the following code on the Code Editor associated for this method:</p>
<pre>dim observedObjects as xojo.Core.Dictionary = Objects.Lookup( observedObject, new xojo.core.Dictionary )
dim messages() as NotificationReceiver
if observedObjects.HasKey( message ) then messages = observedObjects.Value( message )
messages.Append sourceControl
observedObjects.Value( message) = messages
objects.Value( observedObject ) = observedObjects</pre>
<h3>Sending Notifications</h3>
<p>Now is time to add to the class the method responsible to send the notifications to those objects interested in receiving them from any previously registered object. Insert a new method for the <strong>NotificationCenter</strong> class and use the following values in the associated Inspector:</p>
<ul>
<li><strong>Name:</strong> sendNotification</li>
<li><strong>Parameters:</strong> sourceObject as RectControl, message as text, value as Auto</li>
<li><strong>Scope:</strong> Public</li>
</ul>
<p>And the following code in the Code Editor associated with the method:</p>
<pre>dim observedObjects as xojo.Core.Dictionary = objects.Lookup(sourceObject, nil)
if observedObjects &lt;&gt; nil then
  dim sourceObjects() as NotificationReceiver
  if observedObjects.haskey(message) then sourceObjects = observedObjects.Value( message )
  for n as integer = 0 to sourceObjects.Ubound
    dim target as NotificationReceiver = sourceObjects(n)
    target.valueReceived( value, message )
  next
end if</pre>
<p>As you can see, the first parameter of the method is the control that wants to send a notification (second parameter) to all the possible registered objects, passing the value that such objects can be interested to receive for processing it (third parameter).</p>
<h3>Stop receiving Notifications</h3>
<p>However, it is probable that one object wants to stop receiving notifications from any previously registered control. For that, we need to add a new method to the NotificationCenter class using this values:</p>
<ul>
<li><strong>Name:</strong> RemoveObserver</li>
<li><strong>Parameters:</strong> sourceControl as NotificationReceiver</li>
</ul>
<p>And the following code on the associated Code Editor:</p>
<pre>for each observedObjects as xojo.Core.DictionaryEntry in objects
  dim d as xojo.Core.Dictionary = objects.Value(observedObjects.Key)
  for each messagesForObject as xojo.Core.DictionaryEntry in d
    dim sourceObjects() as NotificationReceiver = d.Value(messagesForObject.Key)
    for n as integer = sourceObjects.Ubound DownTo 0
      if sourceObjects(n) = sourceControl then sourceObjects.Remove(n)
    next
  next
next</pre>
<h3>Stop receiving some Notifications</h3>
<p>It may also be the case that one object wants to unsuscribe from the Notification Center to stop receiving just one particular notification. For that, add a new method and use the following values on the Inspector:</p>
<ul>
<li><strong>Name:</strong> removeObserverForMessage</li>
<li><strong>Parameters:</strong> sourceControl as NotificationReceiver, message as text</li>
</ul>
<p>And write the following code in the associated Code Editor:</p>
<pre>for each observedObjects as xojo.Core.DictionaryEntry in objects
  dim d as xojo.Core.Dictionary = objects.Value(observedObjects.Key)
  for each messagesForObject as xojo.Core.DictionaryEntry in d
    if messagesForObject.Key = message then
      dim sourceObjects() as NotificationReceiver = d.Value(messagesForObject.Key)
      for n as integer = sourceObjects.Ubound DownTo 0
        if sourceObjects(n) = sourceControl then sourceObjects.Remove(n)
      next
    end if
  next
next</pre>
<h2>One Class Interface that runs them all: NotificationReceiver</h2>
<p>Along the implementation of our Notification Center class we have seen several times the reference to the <strong>NotificationReceiver</strong> data type. This is what we are going to get our hands on next.</p>
<p>In fact this is a <strong>Class Interface;</strong> what means that it works as a &#8220;glue&#8221; in order that any object can implement their defined methods. This way the objects can be seen as their native class and also as an instance from <strong>NotificationReceiver</strong>, so they can be registered as observers on the Notification Center independently the native class they are based on.</p>
<p>Use <strong>Insert &gt; Class</strong> Interface to add a new Class Interface to the project. Next, write the following values in the associated Inspector:</p>
<ul>
<li><strong>Name:</strong> NotificationReceiver</li>
</ul>
<p>With the Class Interface still selected in the Navigator, add a new method using the following signature in the Inspector:</p>
<ul>
<li><strong>Method Name:</strong> valueReceived</li>
<li><strong>Parameters:</strong> value as Auto, message as Text</li>
</ul>
<p>Done! Depending on your own needs, you can add more methods for the interface class in combination with the Notification Center class itself.</p>
<h2>Testing the Notification Center</h2>
<p>Now it is time to design the user interface in order to test the Notification Center class. The changes made on a <strong>TextField</strong> control will automatically update the contents of a <strong>Label</strong> control, a <strong>Slider</strong> control, a <strong>ListBox</strong> control and a <strong>Canvas</strong> control. Moreover, the Label instance will subscribe in the Notification Center to receive two types of notifications, changing his behaviour (the text shown) based on the received notification.</p>
<p>We will also add a couple of <strong>CheckBox</strong> controls to test the functionality to unsuscribe the Label control from all or just some notifications.</p>
<p>But before we start with that, and as we have seen in the previous step, we need that all the objects that want to be able to register on the Notification Center be of the <strong>NotificationReceiver</strong> data type. That means that we need to create our own subclases for the Label, Slider, ListBox and Canvas controles. Let&#8217;s start with the Label!</p>
<h3>Label Subclass</h3>
<p>Create a new sublcass for the Label Class. You can do that selecting the Label control from the <strong>Library</strong> and choosing the &#8220;New Subclass&#8221; option from the contextual menu; or you can drag and drop the control from the Library to the Navigator. Anyway, the result will be the same: you will have created a new subclass with the name &#8220;CustomLabel&#8221; (it can vary, depending the Xojo release you use). By the way, you also can use <strong>Insert &gt; Class</strong> in order to create a new subclass.</p>
<p>Regardless of the method used to create the new subclass, choose it in the Navigator and use this values in the associated Inspector:</p>
<ul>
<li><strong>Name:</strong> MyLabel</li>
<li><strong>Super:</strong> Label // This way, our sublcass will inherit all the methods, events and properties from the base class.</li>
<li><strong>Interfaces:</strong> Click on the button and choose &#8220;NotificationReceived&#8221; from the resulting panel/Window. Confirm the selection clicking on the &#8220;OK&#8221; button.</li>
</ul>
<p>As result of the last action, Xojo will automatically added the ValueReceived method to the class. Write the following code in the associated Code Editor:</p>
<pre>RaiseEvent newValueReceived value, message</pre>
<p>Here we raise a new event (not defined yet), so every instance from the class can be in charge of implement the real behavior in base of the parameters received.</p>
<p>So, with the &#8220;MyLabel&#8221; class still selected, use <strong>Insert &gt; Event Definition</strong> to add the event definition we need. Use the following values in the associated Inspector:</p>
<ul>
<li><strong>Event Name:</strong> newValueReceived</li>
<li><strong>Parameters:</strong> value as auto, message as Text</li>
</ul>
<h3>Slider Subclass</h3>
<p>Add a new subclass and use these values in the associated Inspector:</p>
<ul>
<li><strong>Name:</strong> MySlider</li>
<li><strong>Super:</strong> Slider</li>
<li><strong>Interfaces:</strong> Add the NotificationReceiver Class Interface as seen in the previous step.</li>
</ul>
<p>Write the following code for the ValueReceived method:</p>
<pre>RaiseEvent newValueReceived val(value)</pre>
<p>And add the event definition using <strong>Insert &gt; Event Definition</strong>, as we have seen in the previous step. Use this signature in the Inspector:</p>
<ul>
<li><strong>Event Name:</strong> newValueReceived</li>
<li><strong>Parameters:</strong> value as integer</li>
</ul>
<h3>ListBox Subclass</h3>
<p>Let&#8217;s create now the subclass for the ListBox, following basically the same steps already done with the previous subclasses. Use the following values:</p>
<ul>
<li><strong>Name:</strong> MyListBox</li>
<li><strong>Super:</strong> ListBox</li>
<li><strong>Interfaces:</strong> NotificationReceiver</li>
</ul>
<p>Write the following code in the Code Editor associated with the ValueReceived method added by the Class Interface:</p>
<pre>RaiseEvent newValueReceived val(value)</pre>
<p>And add the corresponding Event Definition using this signature:</p>
<ul>
<li><strong>Event Name:</strong> newValueReceived</li>
<li><strong>Parameters:</strong> value as integer</li>
</ul>
<h3>Canvas Subclass</h3>
<p>We have arrived to the last subclass definition for our example project. Add a new subclass to the project and use this values in the associated Inspector:</p>
<ul>
<li><strong>Name:</strong> MyCanvas</li>
<li><strong>Super:</strong> Canvas</li>
<li><strong>Interfaces:</strong> NotificationReceiver</li>
</ul>
<p>Write the following code for the ValueReceived method:</p>
<pre>dim s as string = value
newValue = s.ToText
me.Refresh</pre>
<p>Next, use <strong>Insert &gt; Event Handler</strong> to add the Paint event to the subclass. Write this code in the associated Code Editor:</p>
<pre>dim size as integer = val(newValue)
g.TextSize = size
dim centerx as integer = g.Width/2 - g.StringWidth(newValue)/2
dim centery as integer = g.Height/2+g.StringHeight(newValue,g.Width)/2
g.ForeColor = rgb(size, size, size)
g.FillRect(0,0,g.Width,g.Height)
g.ForeColor = if(size &lt;= 50, rgb(255,255,255), rgb(0,0,0))
g.DrawString(newValue,centerx,centery)</pre>
<p>Lastly, add a new property to the subclass using <strong>Insert &gt; Property</strong>, and using this values:</p>
<ul>
<li><strong>Name:</strong> newValue</li>
<li><strong>Type:</strong> Text</li>
<li><strong>Scope:</strong> Private</li>
</ul>
<h2>Designing the User Interface</h2>
<p>Once we have created the subclasses for the Controls we will use as observers in our example app, it is time to design the user interface. For that, choose the window by default for the project (Window1).</p>
<p>Xojo will show the <strong>Layout Designer</strong> for the selected Window. Drag the subclass controls from the Navigator (or from the Library) so they are arranged as shown in this picture. In addition, drag a couple of CheckBox controls and one TextField too from the Library to the layout.</p>
<p><img loading="lazy" decoding="async" class="alignnone size-full wp-image-2073" src="https://blog.xojo.com/wp-content/uploads/2016/11/Captura-de-pantalla-2016-11-10-a-las-13.23.55.png" alt="captura-de-pantalla-2016-11-10-a-las-13-23-55" width="910" height="534" /></p>
<p>Choose the label instance (with the name &#8220;Label2&#8221; in the example project) and use <strong>Insert &gt; Event Handler</strong> to add the &#8220;newValueReceived&#8221; event handler previously defined in our class. Write the following code in the associated Code Editor:</p>
<pre>dim s as string = value
Select case message
  case "valueChanged"
    me.Text = "Value on source Control: "+ s
  case "charValue"
    me.Text = "ASCII Code for last keystroke: "+ str(asc(s))
End Select</pre>
<p>As you can see, the event uses the received message to decide how to work with the value sent by the observed object. In one case it will show the value as is, and for the other it will show the ASCII code for the value received as Text.</p>
<p>Select now the Slider instance (with the name &#8220;Slider1&#8221; in the example project), and repeat the action to add the Event Handler &#8220;newValueReceived&#8221; to the control. Write the following code in the associated Code Editor:</p>
<pre>me.Value = value</pre>
<p>In this case, the control will simply assign to his &#8220;value&#8221; property the value received.</p>
<p>Select now the ListBox instance (&#8220;ListBox1&#8221; in the example project). Add the Event Handler &#8220;newValueReceived&#8221; and write this line of code:</p>
<pre>me.ListIndex = value</pre>
<p>We will also add the &#8220;Open&#8221; Event Handler, so we can populate some default values to use in the example. Once we&#8217;ve added this event, write the following code in the associated Code Editor:</p>
<pre>for n as integer = 0 to 99
  me.AddRow str(n)
next</pre>
<p>Lastly, select the TextField instance (&#8220;TextField1&#8221; in the example project), and add the &#8220;Keydown&#8221; and &#8220;Lost Focus&#8221; Event Handlers. Once added, select the <strong>KeyDown</strong> event handler and write the following code:</p>
<pre>dim myNotificationCenter as NotificationCenter = NotificationCenter.sharedInstance
myNotificationCenter.sendNotification(me,"charValue",key)</pre>
<p>Next, select the <strong>LostFocus</strong> event and writhe the following code:</p>
<pre>dim myNotificationCenter as NotificationCenter = NotificationCenter.sharedInstance
mynotificationcenter.sendNotification(me,"valueChanged",me.Text)</pre>
<p>For both cases, we retrieve the shared instance from the Notification Center class and publish a new notification, passing along the own control as first argument (acting as originator), the message or published notification as second argument, and the value sent as the third argument. From this point on, the Notification Center will be in charge of propagate the received notification to all the interested objects.</p>
<h3>Subscribing and Unsubscribing to Notifications</h3>
<p>Let&#8217;s get in charge of the user interface controls whose function is to enable and disable the notifications for our MyLabel instance (Label1).</p>
<p>Select the <strong>CheckBox1</strong> control, add the Action event handler and write the following code in the associated Code Editor:</p>
<pre>dim miNotificationCenter as NotificationCenter = NotificationCenter.sharedInstance
select case me.Value
  case true
    miNotificationCenter.register(Label2,TextField1, "valueChanged")
    miNotificationCenter.register(Label2, TextField1, "charValue")
  case False
    miNotificationCenter.removeObserver(Label2)
    CheckBox2.value = false
end select</pre>
<p>Select now the <strong>CheckBox2</strong> control, add the Action event handler and write the following code:</p>
<pre>dim miNotificationCenter as NotificationCenter = NotificationCenter.sharedInstance
select case me.Value
  case true
    miNotificationCenter.register(Label2,TextField1, "valueChanged")
  case False
    miNotificationCenter.removeObserverForMessage(Label2,"valueChanged")
end select</pre>
<p>As you can see, in the first block of code we register the &#8220;Label2&#8221; control so it can receive both notifications when the checkbox value is <strong>True</strong>, and unsubscribe the control from receiving any notification when the checkbox is <strong>False</strong>. For the second block of code, the &#8220;Label2&#8221; control just subscribe or unsubscribe for one of the two notifications, respectively.</p>
<h2>Starting engines!</h2>
<p>What we need to put all to work? Add the <strong>Open</strong> event handler to &#8220;Window1&#8221; and write the following code.</p>
<pre>dim miNotificationCenter as NotificationCenter = NotificationCenter.sharedInstance
miNotificationCenter.register(Label2,TextField1, "valueChanged")
miNotificationCenter.register(Label2, TextField1, "charValue")
miNotificationCenter.register(Listbox1,TextField1, "valueChanged")
miNotificationCenter.register(Slider1,TextField1, "valueChanged")
miNotificationCenter.register(canvas1,TextField1, "valueChanged")</pre>
<p>This code will register the interested controls (observers) to the Notification Center for those Notifications they are interested in. Of course, this can also be done inside the Open event handler for every interested control!</p>
<h2>In brief</h2>
<p>As we have seen, with the combination of the <strong>Observer</strong> and <strong>Singleton</strong> Design Patterns, and the help of one <strong>Class Interface</strong> definition, we have created our own Notification Center from scratch to greatly automatice and simplify the communication between the objects, their processes and easying also the maintenance and extension of the app functionallity.</p>
<p>You can watch <a href="https://youtu.be/bCsGtHKM5GA">the video</a> (in Spanish only) that talks you though this example.</p>
<p><em>Javier Rodri­guez has been the Xojo Spanish Evangelist since 2008, he’s also a Developer, Consultant and Trainer who has used Xojo since 1998. He is in charge of <a href="http://www.aprendexojo.com">AprendeXojo.com</a> and the developer behind the GuancheMOS plug-in for Xojo Developers and the Snippery app, among others.</em></p>
<p>*<a href="http://www.aprendexojo.com/2016/11/patrones-de-diseno-observer-y-ii/">Read this post in Spanish</a></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>TextField with Autocomplete</title>
		<link>https://blog.xojo.com/2016/08/10/textfield-with-autocomplete/</link>
					<comments>https://blog.xojo.com/2016/08/10/textfield-with-autocomplete/#comments</comments>
		
		<dc:creator><![CDATA[Javier Menendez]]></dc:creator>
		<pubDate>Wed, 10 Aug 2016 08:00:51 +0000</pubDate>
				<category><![CDATA[Cross-Platform]]></category>
		<category><![CDATA[Learning]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[AprendeXojo]]></category>
		<category><![CDATA[Constructor]]></category>
		<guid isPermaLink="false">http://blog.xojo.com/?p=1540</guid>

					<description><![CDATA[Wouldn&#8217;t it be nice to have&#160;a TextField with Autocomplete for&#160;Xojo Apps, like&#160;we are used to in the Xojo IDE? You know, you start to type&#8230;]]></description>
										<content:encoded><![CDATA[<p>Wouldn&#8217;t it be nice to have&nbsp;a <strong>TextField</strong> with Autocomplete for&nbsp;<strong>Xojo</strong> Apps, like&nbsp;we are used to in the Xojo IDE? You know, you start to type a word and the autocomplete feature suggests a possible matching word and finally you just have to press the &#8216;Tab&#8217; key in order to complete the writing of the word. Let&#8217;s see how we can implement it, using&nbsp;language features like Subclassing and Class Interface, among others!</p>
<h2>Creating the Class Interface</h2>
<p>Our Xojo project will use&nbsp;three main items: a subclass from the TextField class, a Class Interface definition, and a Class that will do the job of&nbsp;the Dictionary containing the suggested words for the Autocomplete feature and that will conform to the Class Interface. This way, you&#8217;ll be able to use any object as the Dictionary source, as long as&nbsp;it conforms to the expected Class Interface.</p>
<p><strong>Note</strong>: The Dictionary referred to here is not the Xojo Dictionary class, but is our collection of suggested words for use by autocomplete.</p>
<p>In fact let&#8217;s start creating a Class Interface; so run the Xojo IDE and create a new Desktop project.</p>
<p><img loading="lazy" decoding="async" class="wp-image-7071 size-full aligncenter" src="https://blog.xojo.com/wp-content/uploads/2016/08/AddClassInterface.png" alt="" width="322" height="289" srcset="https://blog.xojo.com/wp-content/uploads/2016/08/AddClassInterface.png 322w, https://blog.xojo.com/wp-content/uploads/2016/08/AddClassInterface-300x269.png 300w" sizes="auto, (max-width: 322px) 100vw, 322px" /></p>
<ol>
<li>Add a new <a href="http://developer.xojo.com/userguide/interfaces">Class Interface</a> to the project selecting <strong>Insert &gt; Class Interface</strong>.</li>
<li>Write &#8216;TextAutocompleteSource&#8221; in the Name field of the Inspector. This one will be the Data Type for the created Class Interface.</li>
<li>Select the icon for the&nbsp;&#8216;TextAutocompleteSource&#8217; in the Navigator&nbsp;(the leftmost column in the IDE Window), open the contextual menu and choose the &#8216;Add to &#8220;TextAutocompleteSource&#8221; &gt; Method&#8217; option. This action will bring us to the Inspector, so we can define the new Method signature.</li>
<li>The first of the methods will be in charge of adding a new word to the dictionary, so use &#8216;AddWordToDictionary&#8217; as the Method Name, and type &#8216;Value As String&#8217; in the Parameters field.</li>
<li>Add a second Method, name it &#8216;Match&#8217;, type &#8216;Value As String&#8217; in the Parameters field, and &#8216;String&#8217; for the &#8216;Return Type&#8217; field. This will be the invoked method in order to find and return a word suggested for the received string.</li>
</ol>
<p>That&#8217;s all we need for our Class Interface. Simple, isn&#8217;t? Remember that Class Interfaces just deal with Method definitions, and the classes that conform to it will be responsible for&nbsp;implementing the code for the&nbsp;methods.</p>
<h2>Defining our Dictionary</h2>
<p>Now is time to create a new class that will play the role of the main Dictionary for the app of this Tutorial. This one will implement, in fact, the Class Interface defined in the previous section. This means that will implement the real functionality for the methods defined in the TextAutocompleteSource Class Interface.</p>
<ul>
<li>Create a new <a href="http://developer.xojo.com/userguide/classes">Class</a> selecting Insert &gt; Class from the main Toolbar or from the Insert menu.</li>
<li>Type &#8216;StringStack&#8217; in the Inspector as the name of the new Class. This will be the name for the just created Data Type.</li>
<li>From the Inspector, click on the Choose button near to the &#8216;Interfaces&#8217; label. As a result, this action will open a new Window showing all the available Class Interfaces…&nbsp;including the one created by us in the previous section! Select this one (TextAutocompleteSource) and confirm the selection clicking the &#8216;OK&#8217; button.</li>
</ul>
<p><img loading="lazy" decoding="async" class="aligncenter wp-image-7072 size-medium" src="https://blog.xojo.com/wp-content/uploads/2016/08/AddInterface-300x282.png" alt="" width="300" height="282" srcset="https://blog.xojo.com/wp-content/uploads/2016/08/AddInterface-300x282.png 300w, https://blog.xojo.com/wp-content/uploads/2016/08/AddInterface-768x723.png 768w, https://blog.xojo.com/wp-content/uploads/2016/08/AddInterface.png 1024w" sizes="auto, (max-width: 300px) 100vw, 300px" /></p>
<ul>
<li>As result, Xojo will add the methods declared in the selected Class Interface. We will implement the code for these two methods in a later step.</li>
</ul>
<p><img loading="lazy" decoding="async" class="wp-image-7074 size-full aligncenter" src="https://blog.xojo.com/wp-content/uploads/2016/08/InterfaceMethods.png" alt="" width="410" height="156" srcset="https://blog.xojo.com/wp-content/uploads/2016/08/InterfaceMethods.png 410w, https://blog.xojo.com/wp-content/uploads/2016/08/InterfaceMethods-300x114.png 300w" sizes="auto, (max-width: 410px) 100vw, 410px" /></p>
<ul>
<li>Add a new Property to the class: with StringBack selected, choose Insert &gt; Property. In the resulting Inspector, type &#8216;Collector(-1)&#8217; in the Name field. This means, that our Property will be an Empty Array. Type &#8216;String&#8217; for the &#8216;Type&#8217; field and choose &#8216;Private&#8217; as the Scope for the property.</li>
<li>Let&#8217;s implement the code for the Class Interface methods! Select the &#8216;addWordToDictionary&#8217; method and type the following code in the associated Code Editor:</li>
</ul>
<pre>if not Value.IsEmpty then Collector.Addrow(Value)</pre>
<p>Select now the &#8216;Match&#8217; method and type the following code in the associated Code Editor:</p>
<pre>Var n As Integer = Value.Length
Var t As String
For Each item As String In Collector
  t = element.Middle(0, n)
  if t = Value then return item
Next
Return ""</pre>
<p>This method is the one responsible to find a suggested word for the received string. Probably you&#8217;ll want to improve the algorithm in your own implementation (depending mainly on the kind of object you will use as a Dictionary), but this one will serve for our testing app.</p>
<h2>Adding a Constructor to the Class</h2>
<p>Now we are going to define a very special method to the Class: the <a href="http://developer.xojo.com/userguide/constructors-and-destructors$Constructors">Constructor</a>. When a Class has this method it will execute the code from this method every time we create a new instance (object) from the Class. Usually we use the class Constructor (you can have several of them thanks to the OOP feature of <a href="http://developer.xojo.com/userguide/oop-design-concepts$Overloading">Method Overloading</a>) to define the initial state of the new instantiated object. In our case, we will use the Constructor to assign the initial state of the dictionary (the Collector property we&#8217;ve defined in a previous step) during the instantiation of the object.</p>
<p><img loading="lazy" decoding="async" class="wp-image-7075 size-full aligncenter" src="https://blog.xojo.com/wp-content/uploads/2016/08/Constructor.png" alt="" width="400" height="207" srcset="https://blog.xojo.com/wp-content/uploads/2016/08/Constructor.png 400w, https://blog.xojo.com/wp-content/uploads/2016/08/Constructor-300x155.png 300w" sizes="auto, (max-width: 400px) 100vw, 400px" /></p>
<ol>
<li>Add a new method to the Class (Insert &gt; Method). Next, select the &#8216;Constructor&#8217; item from the &#8216;Method Name&#8217; drop-down menu or type it.</li>
<li>As we would do with a regular Method, we can modify the Constructor method signature to define, for example, the amount and type of the parameters. In fact, for our Constructor we will type &#8216;Value() As String&#8217; for the Parameters field.</li>
</ol>
<p>Add the following code to it:</p>
<pre>Collector = Value</pre>
<h2>Subclassing: TextField Specialization</h2>
<p>We have finished the auxiliary items needed for the project, so it is time to focus on the main point: create a TextField subclass to include the autocomplete feature on it.</p>
<ol>
<li>Add a new class to the project using Insert &gt; Class. Type &#8216;TextFieldAutocomplete&#8217; as the Class name in the Inspector, and type &#8216;TextField&#8217; as its &#8216;Super&#8217; class.</li>
<li>Add a new property (Insert &gt; Property). Type &#8216;Autocomplete&#8217; as the property Name, &#8216;Boolean&#8217; as the Type, and &#8216;True&#8217; for the Default field. Finally, select the &#8216;Public&#8217; option for the scope. This property will let us to use the objects from the class as regular TextField, without autocompletion, or with the Autocomplete functionality.</li>
<li>Add another property, typing &#8216;AutocompleteSource&#8217; for the property Name, setting the scope to &#8216;Public&#8217; and its type to &#8216;TextAutocompleteSource&#8217;. That is the Data Type we have created as a Class Interface. This allows us to use any object that conforms to TextAutocompleteSource as the source for the Autocompletion Dictionary.</li>
<li>Let&#8217;s add a third property. In this case, use &#8216;TabKeyAutcompletes&#8217; as the property name, &#8216;Boolean&#8217; for the Type, set the Scope to Public, and its default value to &#8216;True&#8217;. We will use this property to set the behaviour of the Tab key between autocomplete the suggested word, or change to its regular behaviour when used on a TextField control.</li>
</ol>
<h2>Shared Properties</h2>
<p>All the properties created for the subclass are <a href="http://developer.xojo.com/userguide/properties-methods-and-events$InstanceProperties">Instance Properties</a>. That is, every new instance (object) from this class will have its own set of values for these properties. In some cases, however, we want to share the value of one or several properties for all the class instances…and this is what we can achieve using the <a href="http://developer.xojo.com/userguide/properties-methods-and-events$Shared%20Properties">Shared Properties</a>.</p>
<p>We will use two of these shared properties for our TextFieldAutocomplete class to see them in action. One of these will let us use the Suggestions Dictionary globally for all the class instances, always the property is not set to Nil. The second one will be an Array of Strings that will contain all the characters that we want to exclude from the typed on the textfield.</p>
<ol>
<li>Add a new Shared Property to the Class, typing &#8216;globalAutocompleteSource&#8217; for the Name field, setting the Scope to &#8216;Public&#8217; and typing &#8216;TextAutocompleteSource&#8217; as the Data Type for the Property.</li>
<li>Add the second Shared Property typing &#8216;SpecialCharacters(-1)&#8217; as its name, setting the Scope to &#8216;Protected&#8217; and &#8216;String&#8217; for the Data Type.</li>
</ol>
<h2>TextFieldAutocomplete: a Matter of Methods</h2>
<p>The next step is to add a couple of method to our class: the public interface. With them, the user of the class can set the no allowed characters.</p>
<ul>
<li>Add a new method to the class typing &#8216;AddSpecialCharacters&#8217; as the name, &#8216;Value() as String&#8217; for the Parameters field, and setting the Scope to &#8216;Public&#8217;. Type this line of code in the associated Code Editor for the method:</li>
</ul>
<pre>SpecialCharacters = Value</pre>
<ul>
<li>Add the second method, using &#8216;SpecialCharacter&#8217; as the method name, &#8216;Value as String&#8217; for the parameters field, &#8216;Boolean&#8217; as returned Type and setting the Scope to &#8216;Protected&#8217;. Type this block of code for the method:</li>
</ul>
<pre>If SpecialCharacters.LastRowIndex &gt; 0 Then
  For Each item As String In SpecialCharacters
    If item = Value then Return true
  Next
End If
Return False</pre>
<h2>Handling Events</h2>
<p>Our TextFieldAutocomplete class needs to be aware of every key down, so we are going to add the handler triggered in response of this event.</p>
<ul>
<li>Make sure that the &#8216;TextFieldAutocomplete&#8217; item is selected on the Navigator&nbsp;and select Insert &gt; Event Handler. This action will show&nbsp;a new window with&nbsp;all the available Events for the class. Select the KeyDown event and confirm clicking on the &#8216;OK&#8217; button.</li>
</ul>
<p><img loading="lazy" decoding="async" class="wp-image-7076 size-full aligncenter" src="https://blog.xojo.com/wp-content/uploads/2016/08/KeyDownEvent.png" alt="" width="605" height="326" srcset="https://blog.xojo.com/wp-content/uploads/2016/08/KeyDownEvent.png 605w, https://blog.xojo.com/wp-content/uploads/2016/08/KeyDownEvent-300x162.png 300w" sizes="auto, (max-width: 605px) 100vw, 605px" /></p>
<ul>
<li>Select the just added KeyDown event and type the following block of code. This is the place where we put the main logic for the class!</li>
</ul>
<pre>If Autocomplete = False Then Return RaiseEvent KeyDown(Key)

If SpecialCharacter(key) = True Then Return False

If Asc(key) = 9 And TabKeyAutocompletes = True And Me.SelectionLength &gt; 0 Then
  Me.SelectionStart = Me.value.Length
  Me.SelectionLength = 0
  Return True
End If

Var tempText As String = Me.Value.Left(Me.SelectionStart) + key

Var matchingText As String

If AutocompleteSource &lt;&gt; Nil Then

  matchingText = AutocompleteSource.Match(tempText)

Elseif GlobalAutocompleteSource &lt;&gt; Nil Then

  matchingText = GlobalAutocompleteSource.Match(tempText)
End If

If matchingText &lt;&gt; "" Then
  Me.Value = matchingText
  Var startOffset As Integer = tempText.Length
  Me.SelectionStart = startOffset
  Me.SelectionLength = matchingText.Length-startOffset
  Return True
End If

Return false</pre>
<h2>Adding Class Events</h2>
<p>Our class uses&nbsp;the KeyDown event, and that means that it will not be available for the new controls added to the project that would be based on this class. The solution? The Xojo language allows us to <a href="http://developer.xojo.com/userguide/properties-methods-and-events$Events">define new events</a> for&nbsp;our classes, and we will use that feature in order to &#8220;duplicate&#8221; the signature of the used event on the class.</p>
<p>Make sure it is selected the &#8216;TextFieldAutocomplete&#8217; item in the Navigator&nbsp;and then select Insert &gt; Event Definition. The last action will bring us to the Inspector. Type &#8216;KeyDown&#8217; as the Event Name, &#8216;Key as String&#8217; as the Parameter, and &#8216;Boolean&#8217; as Returned Type.</p>
<p>As you can see in the block of code of the previous section, we will call our defined event using the statement &#8216;RaiseEvent&#8217;, passing as parameter the same &#8216;Key&#8217; String received in the original event.</p>
<h2>Design the User Interface</h2>
<p>Everything is now ready to test our Autocomplete TextField with Xojo! The first step is to choose the Window1 item in the Navigator, using the available UI Controls in the Library in order to design the interface as shown in this screenshot:</p>
<p><img loading="lazy" decoding="async" class="alignnone wp-image-7077 size-large" src="https://blog.xojo.com/wp-content/uploads/2016/08/CompleteInterface-1024x379.png" alt="" width="1024" height="379" srcset="https://blog.xojo.com/wp-content/uploads/2016/08/CompleteInterface-1024x379.png 1024w, https://blog.xojo.com/wp-content/uploads/2016/08/CompleteInterface-300x111.png 300w, https://blog.xojo.com/wp-content/uploads/2016/08/CompleteInterface-768x284.png 768w, https://blog.xojo.com/wp-content/uploads/2016/08/CompleteInterface.png 1304w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></p>
<p>In fact, you have to use two CheckBox controls, one PushButton and one TextFieldAutocomplete, dragging the last one from the Navigator&nbsp;over the Window1 Layout Editor.</p>
<p><img loading="lazy" decoding="async" class="alignnone wp-image-7078 size-full" src="https://blog.xojo.com/wp-content/uploads/2016/08/TextFieldSuperClass.png" alt="" width="1006" height="379" srcset="https://blog.xojo.com/wp-content/uploads/2016/08/TextFieldSuperClass.png 1006w, https://blog.xojo.com/wp-content/uploads/2016/08/TextFieldSuperClass-300x113.png 300w, https://blog.xojo.com/wp-content/uploads/2016/08/TextFieldSuperClass-768x289.png 768w" sizes="auto, (max-width: 1006px) 100vw, 1006px" /></p>
<p>Double click the &#8216;CheckBox1&#8217; labeled as &#8216;Autocomplete&#8217; and add a new Event Handler. Choose &#8216;Action&#8217; and click on &#8216;Ok&#8217; to confirm the selection. Type the following line of code in the resulting Code Editor for the added &#8216;Action&#8217; Event Handler:</p>
<pre>TextField1.Autocomplete = me.Value</pre>
<p>Repeat the same operation on the &#8220;CheckBox2&#8221;. In this case, type the following line of code on the &#8216;Action&#8217; Event Handler:</p>
<pre>TextField1.TabKeyAutocompletes = me.Value</pre>
<p>Lastly, add the &#8216;Action&#8217; Event Handler on the &#8216;PushButton1&#8217; control, typing the following line of code:</p>
<pre>Stack.AddWordToDictionary TextField1.Text</pre>
<h2>Start Your&nbsp;Engines!</h2>
<p>Now we need to&nbsp;define the &#8216;Stack&#8217;&nbsp;and the code responsible of putting our demo to work.</p>
<p>Make sure that the &#8216;Window1&#8217; item is selected in the Navigator&nbsp;and add a new Property using &#8216;Stack&#8217; as its name, set the Scope to &#8216;Public&#8217; and the Type to &#8216;StringStack&#8217;. That is the base class previously defined and that conforms to the TextAutocompleteSource protocol.</p>
<p>Now, add the &#8216;Open&#8217; Event Handler to &#8216;Window1&#8217; and type the following block of code:</p>
<pre>Stack = New StringStack(Array("object", "objection", "objective", "objector", _
  "desert", "deserve", "descend", "destroyer", "destruction", _
  "trail", "train", "trainer", "cup", "cure", "curiosity"))

TextField1.AddSpecialCharacters(array(chr(8)))
TextField1.AutocompleteSource = Stack</pre>
<p>As you can see, when we instantiate a new object from the StringStack class, we use the Constructor to pass the Array of Strings. This way we have a simple dictionary whose contents allow us to test the Autocomplete TextField. Obviously, we can change the Dictionary used to any other object that conforms to the &#8216;TextAutocompleteSource&#8217; protocol… even if it is a database!</p>
<p><img loading="lazy" decoding="async" class="alignnone wp-image-7079 size-full" src="https://blog.xojo.com/wp-content/uploads/2016/08/ProjectRunning.png" alt="" width="690" height="288" srcset="https://blog.xojo.com/wp-content/uploads/2016/08/ProjectRunning.png 690w, https://blog.xojo.com/wp-content/uploads/2016/08/ProjectRunning-300x125.png 300w" sizes="auto, (max-width: 690px) 100vw, 690px" /></p>
<p>Run the project and start to type on the Autocomplete TextField. If you start typing the characters&nbsp;of any of the words in the &#8220;Dictionary&#8221;, you&#8217;ll see the TextField will show a suggestion for Autocompletion. Press the &#8216;Tab&#8217; key… and done!</p>
<p>You can download the Example Project used in this tutorial from <a href="https://www.dropbox.com/s/0yovqk1uvb8tqx1/TextField-Autocomplete.zip?dl=1">this link</a>.</p>
<p>You can <a href="https://youtu.be/VIrKvjZfNGs" target="_blank" rel="noopener noreferrer">watch the video</a> (in Spanish only) that&nbsp;talks you though this example.</p>
<p><a href="http://www.aprendexojo.com/2015/09/subclases-e-interfaces-de-clase-en-xojo/" target="_blank" rel="noopener noreferrer">*Read this post in Spanish</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.xojo.com/2016/08/10/textfield-with-autocomplete/feed/</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
			</item>
		<item>
		<title>Make an RSS Reader with Xojo…in 33 lines of code.</title>
		<link>https://blog.xojo.com/2016/07/25/make-an-rss-reader-with-xojoin-33-lines-of-code/</link>
					<comments>https://blog.xojo.com/2016/07/25/make-an-rss-reader-with-xojoin-33-lines-of-code/#comments</comments>
		
		<dc:creator><![CDATA[Javier Menendez]]></dc:creator>
		<pubDate>Mon, 25 Jul 2016 17:38:07 +0000</pubDate>
				<category><![CDATA[Cross-Platform]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[AprendeXojo]]></category>
		<category><![CDATA[RSS]]></category>
		<guid isPermaLink="false">http://blog.xojo.com/?p=1108</guid>

					<description><![CDATA[You have heard it many times: coding with Xojo is not just powerful and fun, it is fast, really fast! This is thanks to the&#8230;]]></description>
										<content:encoded><![CDATA[<p>You have heard it many times: coding with Xojo is not just powerful and fun, it is fast, really fast! This is thanks to the fact that you have at your disposal the powerful <strong>Xojo Framework</strong>, with a lot of classes ready to use&nbsp;doing the&nbsp;hard work behind the scenes. In fact, this article shows you how can create a multi-platform <strong>RSS Reader</strong>…writing just 33 lines of code!</p>
<p><span id="more-1108"></span><br><img loading="lazy" decoding="async" class="wp-image-1112 alignleft" src="https://blog.xojo.com/wp-content/uploads/2016/06/RSS_Xojo.png" alt="RSS Reader Made in Xojo" width="300" height="300"></p>
<p>It won&#8217;t be&nbsp;an RSS Reader with all the bells and whistles &#8211; 33 lines of code does have its limits. But you will learn&nbsp;how useful some of the available Xojo classes are, and you can use the code as the starting point for your own more&nbsp;dazzling RSS Reader. Ready? Start your engines with the&nbsp;Xojo IDE!</p>
<h2>URLConnection, the class to talk HTTP</h2>
<p>Undoubtedly, URLConnection is the main class we are going to use in&nbsp;this tutorial. In fact, we will create our own subclass based on <a href="http://developer.xojo.com/httpsocket" target="_blank" rel="noopener noreferrer">URLConnec</a>tion, so we can write the specialized behaviour that we expect from an RSS feed parser.</p>
<p>But before that, and as you can read in&nbsp;the documentation available about the URLConnection, this class allows us to receive and send information using the HTTP protocol. So, using a new instance (object) from our class we will be able to get the <strong>XML</strong> data associated with an RSS feed. For that we just have to make the request against the remote Web Server using the &#8220;Get&#8221; method from our URLConnection sublcass.</p>
<p>For instance, we can get the data associated with an RSS feed using the standard URLConnection class this way:</p>
<pre>Var http as new URLConnection
Var feedXML As String = http.Send("GET,"http://blog.xojo.com/feed/")</pre>
<p>As you can see, the &#8220;Send&#8221; method expects two mandatory parameters. The first one is the &#8220;Method&#8221; —Get in this case—, and the second is the source URL we are going to use to get the response (the data). The third parameter is optional and it allows us to set the timeout period associated with the request (defaults to 60 seconds).</p>
<p>Whether we use the timeout parameter or not, we would be using this method in a asynchronous way. That is, the code execution flow will continue is way while the connections retrieve the requested data.</p>
<h2>The RSSReader Class</h2>
<p>Now is time to write the subclass that will do the main work: get the XML data associated with the RSS source, and parse the nodes to retrieve just the information we want to use. For instance, in this tutorial we are interested only on the &#8220;Title&#8221; and the associated URL, so when the user selects any of the available items, we can show the full article on an <a href="http://developer.xojo.com/htmlviewer" target="_blank" rel="noopener noreferrer"><strong>HTML Viewer</strong></a>.</p>
<ol>
<li>Add a new Class to the project using Insert &gt; Class, and write &#8220;RSSReader&#8221; as the Class &#8220;Name&#8221; on the associated Inspector.</li>
<li>Add &#8220;URLConnection&#8221; on the &#8220;Super&#8221; field of the Inspector. This is the way we have to identify our class as a subclass of the standard URLConnection, thus inheriting its exposed methods, events and properties.</li>
<li>Add a Property, using &#8220;items(-1)&#8221; for the &#8220;Name&#8221; field of the associated Inspector, and &#8220;Pair&#8221; for the &#8220;Type&#8221; field. This will be Array in charge of storing all the retrieved items from the RSS feed.</li>
<li>Add a new Method named &#8220;GetFeed&#8221;, typing &#8220;url As String&#8221; on the &#8220;Parameters&#8221; field of the associated Inspector. Write this line of code in the Code Editor for the method (we could have opted for using a Computed Property or assigning directly the property with a Public scope, at your choice!):</li>
</ol>
<pre>If url &lt;&gt; "" Then Me.Send("Get",url)</pre>
<h2>ContentReceived, here comes the data</h2>
<p>Let&#8217;s write the code in charge of parsing the received data from the requested URL! For that, we need to add the ContentReceived Event to our Class.</p>
<p><img loading="lazy" decoding="async" class="wp-image-6805 size-full aligncenter" src="https://blog.xojo.com/wp-content/uploads/2016/07/ContentReceived.png" alt="" width="604" height="325" srcset="https://blog.xojo.com/wp-content/uploads/2016/07/ContentReceived.png 604w, https://blog.xojo.com/wp-content/uploads/2016/07/ContentReceived-300x161.png 300w" sizes="auto, (max-width: 604px) 100vw, 604px" /></p>
<p>Make sure to select the RSSReader item in the Project Navigator and choose the Insert &gt; Event Definition option from the menu. On the resulting window, select the ContentReceived item and confirm pushing the &#8220;OK&#8221; button. As result, Xojo will add the selected event to our class, with the Code Editor avilable and ready so you can write the following code:</p>
<pre>If httpStatus = 200 Then
  content = DefineEncoding(content, encodings.UTF8)
  parseNodes(content)
  RaiseEvent refresh(items)
end</pre>
<p>After we define the text encoding&nbsp;for the received content (UTF8), the following line calls the &#8220;parseNodes&#8221; method (not created yet). This method is the one&nbsp;responsible of parsing the received data. Once this has been done, the next line of code will raise the &#8220;refresh&#8221; event on the class instance, passing along the already parsed data.</p>
<h2>Define your own Event: communication with the instance</h2>
<p>Raising an Event is the way our class has to communicate with the instance you&#8217;ll add to the project, so it can interact with other UI components or methods, for example. For that, and with the RSSReader item still selected in the Project Navigator, select the Add to &#8220;RSSReader&#8221; &gt; Event Definition option. Type &#8220;Refresh&#8221; in the Event Name field, and &#8220;items() as Pair&#8221; in the Parameters field. That&#8217;s all, you&#8217;ve created your own Event Handler for the subclass!</p>
<h2>XMLDocument and XPath</h2>
<p>Time to add the &#8220;parseNodes&#8221; method to the RSSReader Class, typing &#8220;content as String&#8221; as Parameter on the associated Inspector. Don&#8217;t forget to define the Scope of this method as Private, so it can&#8217;t be called from outside the class. Then, write the following code for the just created method:</p>
<pre>Try
  Var xml As New XmlDocument(content)
  If xml &lt;&gt; Nil Then 
    Var nodes As XmlNodeList = xml.Xql("//item")
    Var title, url As String
    For n As Integer = 0 To nodes.Length - 1
      title = nodes.item(n).Xql("title").Item(0).FirstChild.Value
      url = nodes.item(n).Xql("link").Item(0).FirstChild.Value
      items.Append( New pair( title, url ) )
    next
  End If
Catch e As XmlException
  MessageBox e.Reason
End Try</pre>
<p>The <a href="http://developer.xojo.com/xmldocument">XMLDocument</a> class available in the Xojo Framework allows us to easily edit and travel the XML structure, as is the case of the RSS feeds! In addition, we can use <a href="https://en.wikipedia.org/wiki/XPath" target="_blank" rel="noopener noreferrer">XPath (1.0)</a> to make the queries on the XML structure. As you can see, I used the &#8220;//item&#8221; expression combined with the <a href="http://documentation.xojo.com/api/text/xml/xmlnode.html#xmlnode-xql" target="_blank" rel="noopener noreferrer">Xql method</a> to get a list with all the nodes of interest from the XML document.</p>
<p>Once we have the nodes, we just need to use the For… Next loop in order to retrieve the &#8220;fields&#8221; that we are interested on from each available node. For that, we are going to use the Xql method too. Finally, we just need to create a new Pair with that information and store it on the Items property.</p>
<h2>The User Interface</h2>
<p>We have finished all the &#8220;hard work&#8221;, so now is time to create the user interface for our RSS Reader!</p>
<p>Choose the Window1 control in the Navigator&nbsp;to access its&nbsp;Layout Window. Then, add a new <a href="http://developer.xojo.com/listbox" target="_blank" rel="noopener noreferrer">ListBox</a> and <a href="http://developer.xojo.com/htmlviewer">HTMLViewer</a> from the Library and arrange these controls as shown by the following image:</p>
<p><img loading="lazy" decoding="async" class="aligncenter wp-image-6806 size-full" src="https://blog.xojo.com/wp-content/uploads/2016/07/RSSReaderUI.png" alt="" width="837" height="790" srcset="https://blog.xojo.com/wp-content/uploads/2016/07/RSSReaderUI.png 837w, https://blog.xojo.com/wp-content/uploads/2016/07/RSSReaderUI-300x283.png 300w, https://blog.xojo.com/wp-content/uploads/2016/07/RSSReaderUI-768x725.png 768w" sizes="auto, (max-width: 837px) 100vw, 837px" /></p>
<p>As you can see in the bottom of the Layout Editor, we added a RSSReader instance to the Window1 tray. For that, you only need to drag the RSSReader item from the Navigator and drop it in that area of the Layout Editor.</p>
<h2>Adding the Refresh Event Handler to our instance!</h2>
<p>We are mostly done! With the just added RSSReader1 instance to our project, select it in the Project Navigator and use the contextual menu to choose the Add to &#8220;RSSReader1&#8221; &gt; Event Handler option. In the resulting dialog, select the &#8220;Refresh&#8221; Event Handler and click on the &#8220;OK&#8221; button in order to get it added to the instance.</p>
<p>Write the following code snippet for the added &#8220;Refresh&#8221; method:</p>
<pre>Listbox2.RemoveAllRows

For Each item As pair In items<br>  Listbox2.AddRow item.Left.StringValue
  listbox2.RowTagAt(Listbox2.LastAddedRowIndex) = item.Right.StringValue  
Next</pre>
<h2>Showing a Webpage on the HTMLViewer</h2>
<p>Choose the Listbox1 control on the Project Browser an add the Change Event. The only line of code you have to write is the responsible to load the webpage associated with the item choosen by the user on the ListBox:</p>
<pre>If Me.SelectedRowIndex &lt;&gt; -1 Then HTMLViewer1.LoadURL me.RowTagAt(me.SelectedRowIndex)</pre>
<h2>Start engines!</h2>
<p>In order to finish the tutorial, we just need to add a line of code to<span style="font-size: inherit">&nbsp;the Open Event to the Window1:</span></p>
<pre>RSSReader1.GetFeed("https://blog.xojo.com/feed" )</pre>
<p>As you can see, it was really easy and works seamless on macOS, Windows and Linux!</p>
<p>You can download the Xojo Project from <a href="https://www.dropbox.com/s/cnp5cwslfjd6s6b/RSSReader%20Project_DEMO.zip?dl=1" target="_blank" rel="noopener noreferrer">this link</a>.</p>
<p><img loading="lazy" decoding="async" class="wp-image-6807 size-full aligncenter" src="https://blog.xojo.com/wp-content/uploads/2016/07/RSSReaderRunning.png" alt="" width="949" height="612" srcset="https://blog.xojo.com/wp-content/uploads/2016/07/RSSReaderRunning.png 949w, https://blog.xojo.com/wp-content/uploads/2016/07/RSSReaderRunning-300x193.png 300w, https://blog.xojo.com/wp-content/uploads/2016/07/RSSReaderRunning-768x495.png 768w" sizes="auto, (max-width: 949px) 100vw, 949px" /></p>
<p>You can <a href="https://www.youtube.com/watch?v=2xvBCivagSc&amp;index=16" target="_blank" rel="noopener noreferrer">watch the video</a> (in Spanish only) that&nbsp;talks you though this example.</p>
<p><a href="http://www.aprendexojo.com/2016/05/patron-de-diseno-observer-en-xojo/" target="_blank" rel="noopener noreferrer">*Read this post in Spanish</a></p>


<p></p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.xojo.com/2016/07/25/make-an-rss-reader-with-xojoin-33-lines-of-code/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>Design Patterns in Xojo: Singleton</title>
		<link>https://blog.xojo.com/2016/06/08/design-patterns-in-xojo-singleton/</link>
		
		<dc:creator><![CDATA[Javier Menendez]]></dc:creator>
		<pubDate>Wed, 08 Jun 2016 00:00:00 +0000</pubDate>
				<category><![CDATA[Technology]]></category>
		<category><![CDATA[AprendeXojo]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Object-Oriented]]></category>
		<guid isPermaLink="false">http://blogtemp.xojo.com/2016/06/08/design-patterns-in-xojo-singleton/</guid>

					<description><![CDATA[In this post I am going to focus on one of these particular Design Patterns and how to implement it in Xojo: Singleton.]]></description>
										<content:encoded><![CDATA[<p>One of the best things that <strong>Xojo</strong> offers to programming newcomers is that they can simply jump-in and start to write code. In a matter of a few hours they&#8217;ll have a functional app! Nothing new here. (Or for not-so-newcomers, a fast way of creating a functional prototype from a idea).</p>
<p><img loading="lazy" decoding="async" style="display: block; margin-left: auto; margin-right: auto;" src="https://blog.xojo.com/wp-content/uploads/2016/06/CandyMachine.pngt1466486449161ampwidth227ampheight369" sizes="auto, (max-width: 227px) 100vw, 227px" alt="CandyMachine.png" width="227" height="369" />But as these users advance in their Xojo skills, they probably will care about coding better and to embrace the <strong>OOP</strong> way of doing things. After all, Xojo is a modern programming language with <strong>Classes</strong>, <strong>Inheritance</strong>, <strong>Interfaces</strong> and a bunch of the usual OOP paradigms that have much to offer: reusability, better maintainability and a lot of flexibility.<br />
<span id="more-269"></span></p>
<p>When we talk about OOP, Design Patterns arise! Design Patterns are like  recipes, well known solutions or best practices, to a series of problems or situations that emerge again and again in our OOP designs.</p>
<p>These <strong>Design Patterns</strong> are so common that you are probably already using some without knowing it. And if you are curious about what are the most common and the code design problems they solve, then you have to definetly take a look into the BOOK (yes, in uppercase): &#8220;<a href="https://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612/" target="_blank">Design Patterns: Elements of Reusable Object-Oriented Software</a>&#8221;</p>
<p>In this post I am going to focus on one of these particular Design Patterns and how to implement it in Xojo: <a href="https://en.wikipedia.org/wiki/Singleton_pattern" target="_blank">Singleton</a>.</p>
<p>OOP is mainly about the instantiation âor object creationâ from a Class definition that acts like a template; so we can have several of these objects around sharing the same behaviour but with a state of their own. Well, the Singleton pattern is the &#8220;opposite&#8221; thing. The answer to having (generally) just one object around from a particular Class.</p>
<p>Why should we want this? The short answer: to limit the access or &#8220;enty point&#8221; to a main functionality of your apps, or when the created object has a high cost or high impact in used resources.</p>
<h2>Implementing the Singleton Pattern</h2>
<p>The key to implement this Design Pattern in your apps is to limit the instantiation of the Class to just one object. So let&#8217;s see how can we achieve this using the Xojo language features. These are the ingredients to the recipe!</p>
<p>A Class Constructor whose scope is set to Private. This is the way we will ensure that the Class consumer will not be able to create several instances using the usual syntax:</p>
<pre>Dim myInstance as MyClass = new MyClass
Dim myInstance as new Myclass</pre>
<p>A <strong>Shared Method</strong> (also known as Static Method or Class Method in other programming languages). This will be the entry point we will use in order to retrieve the unique instance allowed by the Class.</p>
<p>A <strong>Shared Property</strong> whose scope is set to <strong>Private</strong>. This one will be the responsible to hold (point to) the unique instance fromâ¦ the same Class!</p>
<p>Now that we know what the ingredients are, let&#8217;s create our own &#8220;Hello Machine&#8221; as a Singleton Class. Obviously this is not the most useful class in the world, but maintaining the functionality to a minimum will help to focus on the main point about how to implement this Design Pattern in Xojo.</p>
<h2>The &#8220;Hello Machine&#8221; Singleton</h2>
<p>Start the new project creating a new Class using <strong>Insert &gt; Class</strong>. Then, go to the Inspector panel and name the Class as &#8220;HelloMachine&#8221;.</p>
<p>With the new Class item selected in the Project Browser panel (the leftmost), add a new property to it using <strong>Insert &gt; Property</strong>. Name the new property as &#8220;Counter&#8221;, set the Type as Integer and the &#8220;Default Value&#8221; to 1. This is the property that will inform us about how many times has been invoked the class.</p>
<p>Add a new method to the HelloMachine Class (<strong>Insert &gt; Method</strong>). This will be in charge of providing the real functionality to our Singleton class. Use &#8220;Greet&#8221; for the method name and set the Scope to Public. Now, type the following code for the just created method:</p>
<pre>MsgBox "Hello World! Is not funny being the only one instance on Earth?" + endofline + endofline + "You have invoked me " + counter.totext + " times."
counter = counter + 1</pre>
<p>Now it is time to create the class members that will make our HelloMachine behave as a Singleton one.</p>
<p>Start adding the Shared Property that will be in charge to hold the unique class instance used by the App. Use <strong>Insert &gt; Shared Property</strong> for that. Select the just added shared property and using the Inspector panel type &#8220;sharedInstance&#8221; for the &#8220;Name&#8221;, and set the type to &#8220;HelloMachine&#8221;; that is, the same Class type we are just defining (it sounds kind of weird, I know).</p>
<p>Now is time to add our <strong>Class Constructor</strong>. Remember that this one is the special Method whose code is executed every time we want to create a new instance (object) from a particular class.</p>
<p>Use <strong>Insert &gt; Method</strong> and type &#8220;Constructor&#8221; on the &#8220;Method Name&#8221; field of the associated Inspector panel (or choose &#8220;Constructor&#8221; from the dropdown menu). Make sure you set the Scope of the Constructor method as Private. This way we will be sure that nobody will be able to directly instantiate new objects from the class.</p>
<p>Finally we will write the method that will act as the entry point to retrieve the unique instance available from the class; that is, the instance shared among the App.</p>
<p>Use <strong>Insert &gt; Shared Method</strong> and type &#8220;getInstance&#8221; for the &#8220;Method Name&#8221; field. Make sure to set the &#8220;Return Type&#8221; field to &#8220;HelloMachine&#8221;.</p>
<p>Select the &#8220;getInstance&#8221; shared method and type the following code on the associated Code Editor:</p>
<pre>If sharedInstance is Nil then sharedInstance = new HelloMachine
Return sharedInstance</pre>
<p>As you can see, all the &#8220;magic&#8221; consists to verify if has been created already a HelloMachine instance (holded by the sharedInstance Property), returning it if is the case or instantiating and returning it, if otherwise. VoilÃ¡, a Singleton Class!</p>
<h2>Singleton At Work</h2>
<p>Once we have finished our Singleton class definition, let&#8217;s use it in our App. Add the Open event to the default window, for example, and type the following code in the Code Editor:</p>
<pre>Dim myHelloMachine as HelloMachine = HelloMachine.getInstance
myHelloMachine.Greet
Dim myOtherHelloMachine as HelloMachine = HelloMachine.getInstance
myOtherHelloMachine.Greet</pre>
<p>As you can see, we are not instantiating new objects from the Class, just using the Public method to retrieve the unique instance managed by the own Class.</p>
<p>Just for fun, try to instantiate a new object from the class using the regular syntax (I mean, with &#8220;Dim myHellowMachine as new HelloMachine&#8221;) and you will get a Compiler error. That is, no way to have several objects around!</p>
<p>Download an example using the Singleton Design Patter <a href="https://www.dropbox.com/s/znvae5jyvxryz4q/OOP%20Singleton.zip?dl=0" target="_blank">from this link</a>.</p>
<p>You can <a href="https://youtu.be/61KYjND2Vz0" target="_blank">watch the video</a> (in Spanish only) that talks you though this example.</p>
<p><em>Javier RodrÃ­guez has been the Xojo Spanish Evangelist since 2008, he&#8217;s also a Developer, Consultant and Trainer who has used Xojo since 1998. He is in charge of AprendeXojo.com and the developer behind the GuancheMOS plug-in for Xojo Developers and the Snippery app, among others.</em></p>
<p>More Posts From Javier:</p>
<p><!--HubSpot Call-to-Action Code --> <span id="hs-cta-wrapper-2f91fd6d-fb29-4bba-96f2-4a07775b851e" class="hs-cta-wrapper"> <span id="hs-cta-2f91fd6d-fb29-4bba-96f2-4a07775b851e" class="hs-cta-node hs-cta-2f91fd6d-fb29-4bba-96f2-4a07775b851e"><br />
<!-- [if lte IE 8]>


<div id="hs-cta-ie-element"></div>


<![endif]--> <a href="http://blog.xojo.com/2016/05/25/methods-overloading-computed-properties-setters-and-getters/" target="_blank"><img loading="lazy" decoding="async" id="hs-cta-img-2f91fd6d-fb29-4bba-96f2-4a07775b851e" class="hs-cta-img aligncenter" style="border-width: 0px; margin: 0 auto; display: block; margin-top: 20px; margin-bottom: 20px;" src="https://blog.xojo.com/wp-content/uploads/2016/06/2f91fd6d-fb29-4bba-96f2-4a07775b851e.png" alt="Methods Overloading: Computed Properties, Setters and Getters" width="390" height="64" align="middle" /></a> </span><script src="https://js.hscta.net/cta/current.js" charset="utf-8">// <![CDATA[
<script type="text/javascript"><![CDATA[ hbspt.cta.load(608515, '2f91fd6d-fb29-4bba-96f2-4a07775b851e', {});
// ]]&gt;</script></span><br />
<!-- end HubSpot Call-to-Action Code --></p>
<p><a href="http://www.aprendexojo.com/2015/11/patron-singleton-en-xojo/" target="_blank">*Read this post in Spanish</a></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Methods Overloading: Computed Properties, Setters and Getters</title>
		<link>https://blog.xojo.com/2016/05/25/methods-overloading-computed-properties-setters-and-getters/</link>
		
		<dc:creator><![CDATA[Javier Menendez]]></dc:creator>
		<pubDate>Wed, 25 May 2016 00:00:00 +0000</pubDate>
				<category><![CDATA[Technology]]></category>
		<category><![CDATA[AprendeXojo]]></category>
		<category><![CDATA[Object-Oriented]]></category>
		<guid isPermaLink="false">http://blogtemp.xojo.com/2016/05/25/methods-overloading-computed-properties-setters-and-getters/</guid>

					<description><![CDATA[Learn about the concept of Method Overloading in Object-Oriented Programming (OOP).]]></description>
										<content:encoded><![CDATA[<p>Some years ago, Xojo introduced the ability to use Computed Properties, something that is present in other programming languages too and is based on the use of dedicated methods to assign and retrieve the property value itself. So, in other programming languages, the first of these dedicated methods (or functions), the Setter, is the one invoked every time we want to modify the value of the associated property, while the Getter method is the one used from our code to retrieve the associated value. The <a href="http://developer.xojo.com/userguide/object-oriented-programming" target="_blank">Object-Oriented Programming</a> (OOP) concept found behind this feature is <a href="https://en.wikipedia.org/wiki/Function_overloading" target="_blank">Method Overloading</a>. Nevertheless, let&#8217;s make clear that Xojo Computed Properties are not methods. They aren&#8217;t! But they make our life as developers much easier compared with regular Properties.</p>
<p><span id="more-299"></span><br />
<img decoding="async" style="width: 300px; margin: 0px auto 10px; display: block;" title="Bifurcation.png" src="https://blog.xojo.com/wp-content/uploads/2016/05/Bifurcation.pngt1466486449161ampwidth300" sizes="(max-width: 300px) 100vw, 300px" alt="Bifurcation.png" width="300" data-constrained="true" />As developers, the computed properties definitions don&#8217;t differ a lot from regular ones. For example, every time we create one of these properties via <strong>Insert &gt; Computed Property</strong>, we will define the property name, type and scope as we would do in the case of a regular property; and when we refer to these kind of properties from our code, we will use the usual dot notation and, at the same time, we will assign new values using the habitual equal symbol (&#8220;=&#8221;).</p>
<p><img loading="lazy" decoding="async" style="display: block; margin-left: auto; margin-right: auto;" title="Definicion-de-Propiedad-Calculada-en-Xojo_full.png" src="https://blog.xojo.com/wp-content/uploads/2016/05/Definicion-de-Propiedad-Calculada-en-Xojo_full.pngt1466486449161ampwidth250ampheight117" sizes="auto, (max-width: 250px) 100vw, 250px" alt="Definicion-de-Propiedad-Calculada-en-Xojo_full.png" width="250" height="117" /></p>
<p>As you can see in the screenshot, below the property name we find both methods: <strong>Get</strong> and <strong>Set</strong>. &#8216;Get&#8217; is automatically invoked (and showed by the Debugger) every time we write for instance:</p>
<pre>Dim textVar As String = myProperty</pre>
<p>While &#8216;Set&#8217;  is the one automatically invoked every time we want to assign a new value to the property, using, for instance, a sentence like:</p>
<pre>miPropiedad = MyTextField.text</pre>
<p>But if you try to execute these examples just as they are, you will get errors from the Compiler. The property itself doesn&#8217;t exists yet, just this wireframe or umbrella! When we create a new Computed Property this way, we are creating the wrapper but still have to define the real container (the property itself) in charge to store the values processed by Set and Get. This is something we can fix very easily; just a matter of adding a new property and defining its scope as private. This way we will be sure that no other object can directly access the property. The only way to get and/or set its value would be from the Computed Property methods previously created.</p>
<p>In fact, the way you can more clearly see the relationship between a regular property and the Calculated Property wrapper is by defining the regular property in first place. Add a new property, select it from the Project Browser, access the contextual menu and select the &#8216;<strong>Convert to Computed Property</strong>&#8216; option, as showed in the following screenshot:</p>
<p><img loading="lazy" decoding="async" style="display: block; margin-left: auto; margin-right: auto;" title="Convertir-Propiedad-en-Propiedad-Calculada_thumb.png" src="https://blog.xojo.com/wp-content/uploads/2016/05/Convertir-Propiedad-en-Propiedad-Calculada_thumb.pngt1466486449161ampwidth373ampheight333" sizes="auto, (max-width: 373px) 100vw, 373px" alt="Convertir-Propiedad-en-Propiedad-Calculada_thumb.png" width="373" height="333" /></p>
<p>As result, you&#8217;ll find that Xojo&#8217;s IDE has included the wrapper previously seen, modifying the original property&#8217;s name to include the &#8220;m&#8221; character as prefix. At the same time, the scope will change to Private too.</p>
<h2>The magic behind Set and Get</h2>
<p>Behind of the sugar syntax they provide, the real power found in Computed Properties, when compared with regular ones, resides in the code that we can write on both, and that will be executed just before we retrieve the property value or just before we make a new assignation to it.</p>
<p>Following with our example, if we would be using the property to store a person name, we could use Set on such property to provide a default value if the received one is an empty string:</p>
<pre>Set (Value As String)</pre>
<pre>If Value = "" then mMyProperty = "New User"</pre>
<p>On the other hand, we could use the Get on the property to retrieve the associated value using a predefined format. In our example, this could be getting the name using TitleCase (I know, I knowâ¦ we can do this from the Set too, but just wanted to illustrate the topic exposed).</p>
<pre>Get As String</pre>
<pre>Return mMyProperty.Titlecase</pre>
<h2>Method Overloading</h2>
<p>Did you know Computed Properties always were feasible in Xojo? I mean, what we find behind the Computed Properties on Xojo&#8217;s IDE is a help to us as developers in order to simplify the process (and from an organizational point of view of our code).</p>
<p>The truth is that we always could achieve the same results (and still is possible) using the feature available in every <strong><strong>Object Oriented Programming</strong></strong> language, as is the case of Xojo! I&#8217;m referring to <strong>Method Overloading</strong>. This doesn&#8217;t mean that you have to choose between using Computed Properties or Method Overloadingâ¦ the point here is to introduce what Method Overloading.</p>
<p>Method Overloading is the ability we have to define multiple methods using the same name, as long as their parameters types and/or number varies, and/or the type returned from the method itself. So, it&#8217;s time to see how we can achieve the same results of a Computed Property using Method Overloading.</p>
<p>Start adding a new property via <strong>Insert &gt; Property</strong>. Define its type (String in this example) and its scope as Private. Make sure to add the &#8220;m&#8221; character at the beginning of the property name! (in fact you can use any other character, but we use the &#8220;m&#8221; as convention).</p>
<p>Now it&#8217;s time to create our Setter method. For that, use <strong>Insert &gt; Method</strong> on the same project item where you created the property. Use the same name of the property without the initial &#8220;m&#8221; as the Method name, and write the following code in the Parameters field on the Method&#8217;s Inspector Panel:</p>
<pre>Assigns Value as String</pre>
<p>Leave empty the Return Type field (type returned by the method) and select Public as the Method Scope.</p>
<p>The &#8216;<a href="http://developer.xojo.com/assigns" target="_blank">Assigns</a>&#8216; keyword provides the syntax sugar to use the equal symbol (&#8220;=&#8221;) on the parameter pass to the method. This way, we can invoke our method (myProperty on the example) as follows:</p>
<pre>myProperty = "New Value"</pre>
<p>Does it seems like we are not calling a method but making an assignation to a Property?</p>
<p>Let&#8217;s create the method in charge of the Getter and, for that, we will repeat the same steps involved in the creation of a new method. When done, using the same name, you&#8217;ll see that the Project Browser will group together both methods. In this case, as we want to define the Getter, we don&#8217;t need to define the parameters, just the returned type (String for this example).</p>
<p>This is the way it will look in the Project Browser:</p>
<p><img loading="lazy" decoding="async" style="display: block; margin-left: auto; margin-right: auto;" title="Sobrecarga-de-metodos-en-Xojo._thumb.png" src="https://blog.xojo.com/wp-content/uploads/2016/05/Sobrecarga-de-metodos-en-Xojo._thumb.pngt1466486449161ampwidth250ampheight118" sizes="auto, (max-width: 250px) 100vw, 250px" alt="Sobrecarga-de-metodos-en-Xojo._thumb.png" width="250" height="118" /></p>
<p>As we have previously seen, the method overloading is possible because they differ in the provided parameters and/or returned type, despite they use the same name. That way, the Compiler will know exactly which one has to execute on runtime based on such information.</p>
<p>Done! You&#8217;ve learned what Computed Properties are and how they work from the OOP side of the Xojo&#8217;s language.</p>
<p>Finally, probably you want to know too that:</p>
<p>* Computed Properties appear in the debugger and cannot be overloaded on subclassses<br />
* Getter/Setter method overloading does not appear in the debugger, but can be overloaded on subclasses and specified in interfaces.</p>
<p>You can <a href="https://youtu.be/3cvYYkZbdOE" target="_blank">watch the video</a> (in Spanish only) that talks you though this example.</p>
<p><em>Javier RodrÃ­guez has been the Xojo Spanish Evangelist since 2008, he&#8217;s also a Developer, Consultant and Trainer who has used Xojo since 1998. He is in charge of AprendeXojo.com and the developer behind the GuancheMOS plug-in for Xojo Developers and the Snippery app, among others.</em></p>
<p>More Posts From Javier:<br />
<!--HubSpot Call-to-Action Code --> <span id="hs-cta-wrapper-a66218db-ec5e-4a96-a292-57d093659074" class="hs-cta-wrapper"> <span id="hs-cta-a66218db-ec5e-4a96-a292-57d093659074" class="hs-cta-node hs-cta-a66218db-ec5e-4a96-a292-57d093659074"><br />
<!-- [if lte IE 8]>


<div id="hs-cta-ie-element"></div>


<![endif]--> <a href="http://blog.xojo.com/2016/05/09/let-your-os-x-desktop-app-react-to-custom-uris/" target="_blank"><img loading="lazy" decoding="async" id="hs-cta-img-a66218db-ec5e-4a96-a292-57d093659074" class="hs-cta-img aligncenter" style="border-width: 0px; margin: 0 auto; display: block; margin-top: 20px; margin-bottom: 20px;" src="https://blog.xojo.com/wp-content/uploads/2016/05/a66218db-ec5e-4a96-a292-57d093659074.png" alt="Let Your OS X Desktop App React to Custom URIs" width="455" height="84" align="middle" /></a> </span><script src="https://js.hscta.net/cta/current.js" charset="utf-8">// <![CDATA[
<script type="text/javascript"><![CDATA[ hbspt.cta.load(608515, 'a66218db-ec5e-4a96-a292-57d093659074', {});
// ]]&gt;</script></span><br />
<!-- end HubSpot Call-to-Action Code --></p>
<p><a href="http://www.aprendexojo.com/2016/05/sobrecarga-de-metodos/" target="_blank">*Read this post in Spanish</a></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Let Your OS X Desktop App React to Custom URIs</title>
		<link>https://blog.xojo.com/2016/05/09/let-your-os-x-desktop-app-react-to-custom-uris/</link>
		
		<dc:creator><![CDATA[Javier Menendez]]></dc:creator>
		<pubDate>Mon, 09 May 2016 00:00:00 +0000</pubDate>
				<category><![CDATA[Mac]]></category>
		<category><![CDATA[AprendeXojo]]></category>
		<category><![CDATA[Custom URI URL Protocol]]></category>
		<guid isPermaLink="false">http://blogtemp.xojo.com/2016/05/09/let-your-os-x-desktop-app-react-to-custom-uris/</guid>

					<description><![CDATA[The truth is that implementing Uniform Resource Identifiers in your OS X apps is not rocket science! Follow these simple steps in order to register a custom URI from your app. ]]></description>
										<content:encoded><![CDATA[<p>Have you ever wondered how the magic behind the &#8220;mailto://&#8221; or other similar <em><a href="https://en.wikipedia.org/wiki/Uniform_Resource_Identifier" target="_blank" rel="noopener">Uniform Resource Identifiers</a> (URI) </em>work? Whether&nbsp;from the web browser URL field or from Xojo via&nbsp;the <a href="http://documentation.xojo.com/api/deprecated/showurl.html" target="_blank" rel="noopener">ShowURL</a> function, when URIs are executed the registered app opens showing the passed parameters (for example, in the Mail app for the &#8216;To&#8217;, &#8216;Subject&#8217; and &#8216;Body&#8217; fields).</p>
<p>Implementing this kind of behavior&nbsp;in your OS X apps is not rocket science! Follow these simple steps in order to register a custom URI from your app.</p>
<p><span id="more-297"></span></p>
<h2><img decoding="async" style="width: 320px;margin: 0px auto" title="hearing.jpg" src="https://blog.xojo.com/wp-content/uploads/2016/05/hearing.jpgt1466486449161ampwidth320" alt="hearing.jpg" width="320"></h2>
<h2>Register the custom URI you want to manage</h2>
<p>You&#8217;ll need to modify&nbsp;the &#8220;info.plist&#8221; file generated by Xojo every time the app is compiled, so it necessarily involves the use of the powerful <a href="/2013/12/18/build_automation/" target="_blank" rel="noopener">Build Steps</a>! To smooth the road, follow these steps first:</p>
<ol>
<li>Control + Click the OS X item under the <strong>Build Settings</strong> section of the Project Browser panel (the leftmost column in the Xojo IDE)</li>
<li>Select the option Add to &#8220;Build Settings&#8221; &gt; Build Step &gt; Script.</li>
<li>Paste the following code (make sure PlistBuddy from Apple&#8217;s Developer Tools is installed on your Mac!):</li>
</ol>
<pre>Dim App As String = CurrentBuildLocation + "/" + CurrentBuildAppName
call DoShellCommand("/usr/libexec/PlistBuddy -c ""add :CFBundleURLTypes array"" " + App + "/Contents/Info.plist" )
call DoShellCommand("/usr/libexec/PlistBuddy -c ""add :CFBundleURLTypes:0 dict"" " + App + "/Contents/Info.plist" )
call DoShellCommand("/usr/libexec/PlistBuddy -c ""add :CFBundleURLTypes:0:CFBundleURLName string 'Demo'"" " + App + "/Contents/Info.plist" )
call DoShellCommand("/usr/libexec/PlistBuddy -c ""add :CFBundleURLTypes:0:CFBundleURLSchemes array"" " + App + "/Contents/Info.plist" )
call DoShellCommand("/usr/libexec/PlistBuddy -c ""add :CFBundleURLTypes:0:CFBundleURLSchemes:0 string 'demo'"" " + App + "/Contents/Info.plist" )</pre>
<p>Observe the use of the strings &#8216;Demo&#8217; and &#8216;demo&#8217; for the CFBundleURLName and CFBundleURLSchemes keys, respectively. The second one, CFBundleURLSchemes, is the customized URI that anyone will be able to use to pass information to our application.</p>
<p>Make sure to select the option &#8220;Both&#8221; on the Inspector for this build step, and type a name to identify this script&nbsp; (for example, &#8220;Insert URI on Plist&#8221;). This way the URI will be registered every time&nbsp;you run the app from the Debugger or once it is compiled for deployment (release or standalone app).</p>
<h2>Let your app react to the URI</h2>
<p>The second main step is letting your Xojo app react to the URI, this is something you can do by adding the <a href="http://documentation.xojo.com/api/deprecated/application.html#application-handleappleevent" target="_blank" rel="noopener">HandleAppleEvent</a> event to the App Object.</p>
<p>As for the code, you&nbsp;will probably want to to use inside this Event, the main point is to identify the received Event and compare it to the &#8220;GURL&#8221; string, because this is the identifier used by OS X for sending an URI event:</p>
<pre>&nbsp;&nbsp;&nbsp; if eventClass = "GURL" then
&nbsp;&nbsp; &nbsp;  //do your thing
&nbsp;&nbsp; &nbsp;  return true
&nbsp;&nbsp; &nbsp;end if
&nbsp;&nbsp; &nbsp;return false</pre>
<p>This way the app doesn&#8217;t interferes with the events we are not interested in.</p>
<p>It is very important to point out&nbsp;that the HandleAppleEvent event should exit with Return False for the ignored Events. Otherwise the user of your app probably will&nbsp;experience malfunctions using keyboard shortcuts on TextFields or TextAreas among other problems.</p>
<h2>Getting the information</h2>
<p>The final step is to extract the passed information along the &#8220;GURL&#8221; event. <a href="http://documentation.xojo.com/api/language/app.htmlleEvent" target="_blank" rel="noopener">Xojo provides several methods</a> that helps you do this; but for this example we are going to provide the code for the most common uses: getting the information sent as a text String.</p>
<pre>&nbsp;&nbsp;&nbsp; dim s() as string = DecodeURLComponent(theEvent.StringParam("----")).DefineEncoding(encodings.UTF8).Split(":")
&nbsp;&nbsp;&nbsp; s.Remove(0)</pre>
<p>The main point here is the &#8216;theEvent.StringParam(&#8220;&#8212;-&#8220;)&#8217; code. This gets the string available and that is associated with the keyDirectObject key of the Dictionary (the value of that constant is the &#8220;&#8212;-&#8221; string used here.)</p>
<p>The second thing to highlight is that you have to assign a Text Encoding for the received string and use the <a href="http://documentation.xojo.com/api/text/encoding_text/decodeurlcomponent.html" target="_blank" rel="noopener">DecodeURLComponent</a> function to restore the original text sent along the URI (&#8220;demo:&#8221;, for this example).</p>
<p>Lastly, you can use the Split function to get an Array of strings so you can discard the first component from the received string (the URI itself) and join the remaining elements to get the final string.</p>
<p>You can <a href="https://www.youtube.com/watch?v=N-WLwbfp7Nw" target="_blank" rel="noopener">watch the video</a> (in Spanish only) that&nbsp;talks you though this example.</p>
<p>Visit this post to&nbsp;learn how to <a href="http://blog.xojo.com/2016/08/16/custom-uri-schemes-on-windows/">Customize URI Schemes on Windows</a>.</p>
<p><em>Javier RodrÃ­guez has been&nbsp;the Xojo Spanish&nbsp;Evangelist since 2008, he&#8217;s also a Developer, Consultant and Trainer who&nbsp;has used&nbsp;Xojo since 1998. He is in charge of AprendeXojo.com and the developer behind the GuancheMOS plug-in for Xojo Developers and the Snippery app among others.</em></p>
<p><a href="http://www.aprendexojo.com/2016/05/uri-personalizado-en-apps-xojo/" target="_blank" rel="noopener"><span style="text-decoration: underline"><em>*Read this post in Spanish.</em></span></a></p>
<p><span style="text-decoration: underline"><em><br />
<!--HubSpot Call-to-Action Code --> <span id="hs-cta-wrapper-390ec0e5-4f95-4882-b8d1-4213c52807ce" class="hs-cta-wrapper"> <span id="hs-cta-390ec0e5-4f95-4882-b8d1-4213c52807ce" class="hs-cta-node hs-cta-390ec0e5-4f95-4882-b8d1-4213c52807ce"><br />
<!-- [if lte IE 8]&gt;--></p>
<div id="hs-cta-ie-element"></div>
<p> <a href="http://blog.xojo.com/2016/04/07/advanced-retinahidpi-bitmapforcaching-and-scalefactorchanged/" target="_blank" rel="noopener"><img loading="lazy" decoding="async" id="hs-cta-img-390ec0e5-4f95-4882-b8d1-4213c52807ce" class="hs-cta-img aligncenter" style="border-width: 0px;margin: 0 auto;margin-top: 20px;margin-bottom: 20px" src="https://blog.xojo.com/wp-content/uploads/2016/05/390ec0e5-4f95-4882-b8d1-4213c52807ce.png" alt="Advanced Retina/HiDPI: BitmapForCaching and ScaleFactorChanged" width="443" height="77" align="middle"></a></span></span> <!-- end HubSpot Call-to-Action Code --></em></span></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>WeakRef and Memory Management</title>
		<link>https://blog.xojo.com/2016/04/20/weakref-and-memory-management/</link>
		
		<dc:creator><![CDATA[Javier Menendez]]></dc:creator>
		<pubDate>Wed, 20 Apr 2016 00:00:00 +0000</pubDate>
				<category><![CDATA[Mac]]></category>
		<category><![CDATA[Windows]]></category>
		<category><![CDATA[AprendeXojo]]></category>
		<category><![CDATA[Memory]]></category>
		<category><![CDATA[Object-Oriented]]></category>
		<guid isPermaLink="false">http://blogtemp.xojo.com/2016/04/20/weakref-and-memory-management/</guid>

					<description><![CDATA[Sometimes apps can simply reach unstable situations by their very nature. Keep memory management under control with the help of the WeakRef class.]]></description>
										<content:encoded><![CDATA[<p>Object Oriented Programming with Xojo, and in this case Event Oriented Programming as well, is simply wonderful. You create objects (Instances) from the defined classes that act as templates and just let them roll. From there, the interactions made by the user are those that determine how objects interact with each other via sending messages to each other (method calls), the access to properties and also the execution of events.</p>
<p>However, sometimes the combination can simply reach unstable situations by the very nature of our applications and here is where failures can arise in memory management. Fortunately, we can keep this under control with the help of the <a href="http://developer.xojo.com/xojo-core-weakref" target="_blank" rel="noopener">WeakRef class</a>.<br />
<span id="more-281"></span><br />
This is, in fact, what happened to me recently while implementing a new feature in <a href="http://www.aprendexojo.com/software/snippery" target="_blank" rel="noopener">Snippery</a> my productivity application where one of those unlikely but possible cases one of the objects left in an unstable state. What does this mean? The referenced Control object stored in a property was not marked as nil once it was out of scope because its containing window was closed, so it was simply unsafe (an dangerous!) to check or access its properties and methods through a simple verification of the type:</p>
<p><span style="font-family: 'courier new', courier;">if miPropiedad &lt;&gt; nil then</span></p>
<p>Despite the object referenced through the property would have been released, this condition will execute the code inside the block resulting in a unexpectedly exit from the app! In fact inspecting the object via Xojo&#8217;s debugger shows that the reference is still there but it inner structure is void.</p>
<p>So executing the previous code will bring a beautiful error message from OS X:</p>
<p><span style="font-family: 'courier new', courier;">EXC_BAD_ACCESS (SIGSEGV)</span></p>
<p>That is an attempt to access a memory vector where we expected to find a data structure that is not there anymore.</p>
<p>I have to say that after further research on the subject I have found that this kind of error does not always occur and that it may depend on the type of object that we maintain the reference to, or even the property we want to access, or the method we try to call when the objects is in this &#8220;unstable&#8221; state. In the best of the cases, simply nothing happens. In the worst case, your application will suffer an unexpected exit you will not be able to trap using the Try &#8230; Catch block or exception handling mechanism offered by the Xojo language.</p>
<p>If you want to see for yourself what I&#8217;m talking about, you can download the <a href="https://www.dropbox.com/s/l1az8r9jq0q2aps/WeakRef%20Example.zip?dl=0">example application</a> that reproduces this kind of problem related with memory management.</p>
<p><strong>WeakRef to the rescue!</strong></p>
<p>How can we solve these kinds of situations? Easy! The WeakRef class allows code to maintain weak references to objects. When you wrap the object you&#8217;re interested in an instance of the class WeakRef, we will ensure that such reference is released (and thus becomes nil) through proper memory management. So, problem solved! From this point on we can perform and trust a conditional test of the reference against &#8216;nil&#8217; before trying to access any of the properties of the object itself.</p>
<p>In the case of our sample application, we can fix the problem with the following changes:</p>
<p>1. We define the property SourceControl Worker class to be of the WeakRef Data Type<br />
2. We make the following changes to Worker class constructor (where the referenced Control instance is now wrapped into a WeakRef instance):</p>
<p><span style="font-family: 'courier new', courier;">sourceControl = new weakref( c )</span></p>
<p>3. We modify the conditional block of code for the Worker method to:</p>
<p><span style="font-family: 'courier new', courier;">if sourceControl.Value &lt;&gt; nil then</span><br />
<span style="font-family: 'courier new', courier;">  textArea(sourceControl).<wbr />SelLength = 0</span><br />
<span style="font-family: 'courier new', courier;">  textArea(sourceControl).Text = &#8220;This is a test&#8221;</span><br />
<span style="font-family: 'courier new', courier;">end if</span></p>
<p>Note that in this case we Cast SourceControl to TextArea, so  we can work with the properties and methods of the control that we know are actually a control of TextArea type.</p>
<p>Make the changes, run the app again and you&#8217;ll notice that this time the app will continue running without errors once all the windows are closed.</p>
<p>You can watch <a href="https://youtu.be/5-8iwlvNSsY" target="_blank" rel="noopener">the video</a> (in Spanish only) that talks you though this example.</p>
<p><em>Javier RodrÃ­guez has been the Xojo Spanish Evangelist since 2008, he&#8217;s also a Developer, Consultant and Trainer who has used Xojo since 1998. He is in charge of AprendeXojo.com and the developer behind the GuancheMOS plug-in for Xojo Developers and the Snippery app among others.</em></p>
<p><span style="text-decoration: underline;"><em><a href="http://www.aprendexojo.com/2016/04/weakref-y-la-gestion-de-memoria/" target="_blank" rel="noopener">*Read this post in Spanish</a>.</em></span></p>
<p><!--HubSpot Call-to-Action Code --> <span id="hs-cta-wrapper-abfc1e1f-d1ee-4de3-bd9e-7bfe6930b212" class="hs-cta-wrapper"> <span id="hs-cta-abfc1e1f-d1ee-4de3-bd9e-7bfe6930b212" class="hs-cta-node hs-cta-abfc1e1f-d1ee-4de3-bd9e-7bfe6930b212"><br />
<!-- [if lte IE 8]>


<div id="hs-cta-ie-element"></div>


<![endif]--> <a href="http://developer.xojo.com/international-resources" target="_blank" rel="noopener"><img loading="lazy" decoding="async" id="hs-cta-img-abfc1e1f-d1ee-4de3-bd9e-7bfe6930b212" class="hs-cta-img aligncenter" style="border-width: 0px; margin: 0 auto; display: block; margin-top: 20px; margin-bottom: 20px;" src="https://blog.xojo.com/wp-content/uploads/2016/04/abfc1e1f-d1ee-4de3-bd9e-7bfe6930b212.png" alt="International Resources Xojo" width="417" height="229" align="middle" /></a> </span><script src="https://js.hscta.net/cta/current.js" charset="utf-8">// <![CDATA[
<script type="text/javascript"><![CDATA[ hbspt.cta.load(608515, 'abfc1e1f-d1ee-4de3-bd9e-7bfe6930b212', {}); // ]]&gt;</script></span><br />
<!-- end HubSpot Call-to-Action Code --></p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
