CacheEngine, a subclass of the Xojo Timer class, can be used to cache data on the server, which can greatly improve performance for some applications. The cache itself is implemented as a Dictionary. As a result, you can cache nearly any value or object type.
With CacheEngine, you can specify when an entry expires. CacheEngine automatically handles expired content, both when cache entries are requests and proactively via a timer. As a result, no "stale" cached entries are ever returned, and no entries are ever "orphaned."
Use the Delete method to remove an entry from the cache. For example:
To retrieve a value from the cache, use the Get method. This method will check to see if the cached value has expired or not. If the requested entry is either not found or has expired, the method will return a Nil value. Otherwise, it returns a Dictionary with three entries: Content, which is the actual cached value. Expiration, which is the entry's expiration date, represented as a Date. And Entered, which is the date/time that the entry was added to the cached (represented as a Date).
// Try to get the cached content. Dim CacheEntry As Dictionary = App.CacheEngine.Get("DrummersTable") If CacheEntry <> Nil Then // Use the cached content. TableHTML = CacheEntry.Value("Content") Else ... End If
To add an entry to the cache, use the Put method. The method takes three parameters: Name, which is the unique entry name. Content, which is the value to be cached. And ExpirationSecs, which is an integer value representing the number of seconds that the entry should be cached before it is considered to be "stale."
App.CacheEngine.Put("DrummersTable", TableHTML, 60)
To easily remove all entries from the cache, use the Reset method.
The Sweep method is used internally, and called on a timer, to evaluate all cached entries and remove those that have expired.
Starting with Aloe Express v3.0, persistent connections (also known as "Keep-Alives") are supported and enabled by default. ConnectionSweeper, a subclass of the Xojo Timer class, periodically removes any connections that have timed out (i.e., that have been idle for too long, based on the server's KeepAliveTimeout property.
ConnectionSweeper was enhanced in Aloe Express v4.0 to also "sweep" expired WebSocket connections (based on the Server.WSTimeout property.
An instance of this class is automatically created when a server instance runs. The interval with which the sweep occurs is controlled by the server's ConnSweepIntervalSecs property. Its default is 15 seconds.
Xojo uses a co-operative threading model, and as a result, all threads must run on a single core. To make use of other cores, Xojo suggests using separate processes in the form of "helper apps." (For more information on Xojo's support for threads and this "helper app" concept, please see "Supporting Multiple Cores" by Norman Palardy and "Take advantage of your multi-core processor" by Paul Lefebvre.)
The Aloe Express HelperApp class has been designed to make it easy for you to implement helper apps. The class is a subclass of Xojo's Shell class. It handles the execution of a helper app as well as the handling of its response.
In this example, the Aloe Express-based app is using a helper app named "Aloe-Express-Demo-Helper" and passing it a single parameter ("Kirk"). The app is being run in an asynchronous shell, so that no blocking occurs. When the helper app has finished processing, the result is available to the caller via the HelperApp's "Result" property.
// Create, configure, and launch an instance of a helper app. Dim HelperApp As New AloeExpress.HelperApp HelperApp.Name = "Aloe-Express-Demo-Helper" HelperApp.Parameters = Request.GET.Lookup("captain", "Kirk") HelperApp.Launch // Set the response content to be the helper app's result. Request.Response.Content = HelperApp.Result // Update the content type. Request.Response.Headers.Value("Content-Type") = AloeExpress.MIMETypeGet("json") // Close the helper app. HelperApp.Close
Launches the helper app, and waits for it to complete. The helper app is run in an asynchronous shell, so that no blocking occurs.
Refer to the Xojo Shell class for additional methods.
The name of the helper app.
Any command-line parameters that are to be passed to the helper app.
The result that is returned by the helper app.
An internal property that indicates if the helper app is running.
Refer to the Xojo Shell class for additional properties.
The Logger class can be used to generate a log of requests and responses in the industry standard Extended Log File Format. It is primarily intended for use with browser-based Web apps and traditional Web sites, so that traffic and usage can be analyzed. The Logger class is a subclass of Xojo's Thread class.
Starting with Aloe Express v3.0, the Logger class automatically takes into account any "X-Forwarded-For" headers, which are used when apps are being proxied.
This method, which is called internally when the Logger thread runs, logs the request.
Runs the Logger thread, which in turn calls the RequestLog method.
Specifies the directory in which the log files are to be written. By default, the directory is named "logs" and it is located in the parent folder of the app itself.
The IP address of the client that made the request. By default, this is derived from the Request itself (Request.RemoteAddress). However, in some cases, such as when the app is running behind a proxy server, the IP address might need to be derived from a header value. For example, the true IP address might be available via the "X-Forwarded-For" HTTP header. This property gives you the ability to specify the alternative value.
This is the Request object itself, from which the Logger instance can derive information about the request (path, method, etc) as well as from the associated Response object (status, content length, etc).
Dim Logger As New AloeExpress.Logger Logger.Folder = GetFolderItem("").Parent.Child("logs") Logger.Request = Request Logger.IPAddress = Request.Headers.Lookup("X-Forwarded-For", Request.RemoteAddress) Logger.Run
The Request class provides access to request properties (headers, parameters, etc) as well as several methods that assist with the processing of a request and generating a response. It is a subclass of Xojo's SSLSocket class.
Resets a request's properties before calling Super.Close. This is intended to prevent WebSocket connections and persistent connections from inadvertently maintaining state as sockets are recycled.
The Dump method can be used to generate HTML that lists many of the Request instance's properties. It is useful when debugging applications.
The MapToFile method can be used to easily map a request to a static file in a directory specifed by the Request's StaticPath property.
By default, the StaticPath points to an "htdocs" folder that is located in the app's parent directory. To specify an alternative directory, adjust the Request's StaticPath property.
The method also uses the IndexFilenames property, which can be used to specify default index file names. This property is an array of strings, and by default includes "index.html" and "index.htm" values.
Starting in Aloe Express v3.0, ETag support has been added via the Request.MapToFile method, which provides web cache validation. By default, ETags are used when serving static resources via the method. You can disable this feature by calling the method and passing False as the "UseEtags" parameter.
This method sets the Request's Response content to Aloe's standard 404 "Not Found" content. While the method can be called directly, it is also used by the MapToFile method in cases where a request cannot be mapped to a static file.
To obtain or restore a session for a given session, call the SessionGet method. You can optionally pass a AssignNewID Boolean parameter to indicate whether a new Session ID should be assigned to the session. By default, this is set to True to prevent session fixation attacks. In some cases, such as when processing XHRs (XMLHttpRequests), you might want to obtain a session without generating a new Session ID. To use this method, the Server must have sessions enabled.
To terminate a request's session, simply call the SessionTerminate method. To use this method, the Server must have sessions enabled.
If the request is servicing a WebSocket connection, then this method can be used to close the WebSocket connection and close the socket.
This method is used internally by the Request.DataAvailable event handler to process an incoming WebSocket message. If the message is a request to close the connection, the WSConnectionClose method is called. Otherwise, frame decoding logic is used to build the message in its entirety and provide it to the app (via the Request.Body property) for processing.
Sends a WebSocket (text) message to a client. As ov v4.0, only text frames (Opcode 1) are supported. For details, refer to RFC 6455 Section 11.8 ("WebSocket Opcode Registry"). Binary frames (Opcode 2) might be supported in a future version. Similarly, pings (Opcode 9) and pongs (Opcode 10) are not currently supported.
The Body property consists of the request content excluding the the request headers. It is typically used when making POST, PUT, and PATCH requests, where the content being sent to the server is not "x-www-form-urlencoded." For example, a client might send a JSON or XML request body.
Cookies provides access to any cookies that were received in the request. It is a Dictionary.
To access a cookie, use its name as a dictionary key. For example:
Dim PreferredLanguage As String = Request.Cookies.Lookup("PreferredLanguage", "English")
A dictionary that can be used to store values for application-specific attributes about a request, which persists between requests when the socket is being held open (for example, when it is servicing a WebSocket connection). For an example of how it can be used, see the WebSocket demo. Note that the dictionary is initialized in the Request.Prepare method.
The Files property, a Dictionary, provides information about any files that have been uploaded.
The GET property provides access to any URL parameters that were included in the request. It is a Dictionary.
For example, consider a request made using this URL:
The GET dictionary would include two entries, one with key "x" and a value of "1" and a second with key "y" and value of "2." You would access the GET values like this:
Dim X As String = Request.GET.Lookup("x", "") Dim Y As String = Request.GET.Lookup("y", "")
Note that when Aloe Express generates the GET dictionary, it automatically URL decodes the parameter values.
The Headers property is a Dictionary. It includes entries for any HTTP headers that were included in the request.
You might access the value of a "User-Agent" Header like this:
Dim UserAgent As String = Request.Headers.Lookup("User-Agent", "")
This property can be used to determine the HTTP version that was used to make the request.
IndexFilenames is an array of strings. It's used by the MapToFile method to map a request to a static file. The MapToFile method takes the IndexFilenames values into account when mapping requests that end with a backslash.
The Method property (a string) is set based on the the HTTP method that was used to make the request. For example, GET, POST, PUT, PATCH, DELETE, HEAD, etc.
The Path property (a string) indicates the path of the resource that was requested. Note that the Path will not include any URL parameters that were specified. To access those, refer to the URLParams property, or the GET property.
PathComponents is an array of strings, where each string represents a component of the request path. This is provided as a convenience to help with routing requests.
A dictionary representation of the PathComponents array, which can be used to more easily evaluate a request's path for routing and processing.
The POST property provides access to any parameters that were included in the request's body, where the request is actually a form that has been submitted with a "application/x-www-form-urlencoded" content type. POST is a Dictionary.
Every Request instance is assigned an instance of the Response class, which can be used to craft a response to the request.
The Aloe Express Server instance that the request is associated with.
The Session property, which is a dictionary, is used to conveniently associate a session with the Request. See the SessionGet and SessionTerminate methods for more info.
SocketID is a unique ID that was assigned to the Request when it was added to the server's socket pool.
This property specifies the directory in which the MapToFile method will attempt to map requests to static files. By default, the directory is named "htdocs" and it is located in the parent folder of the app itself.
URLParams is a string containing any URL parameters that were passed as part of the request. Refer to the GET property for a more convenient way to access the URL params.
WSStatus is a boolean value indicating the status of the request's WebSocket connection, if applicable. The default value is Inactive.
To prevent long-running requests from blocking other requests, Aloe Express uses a multi-threaded model. When a Request is ready for processing, it is assigned to a RequestThread instance, which removes it from the main thread.
The Response class is designed to make it easy to craft responses to incoming requests. You can easily assign a response's status, headers, and content. Each Request instance is assigned a Response class.
Calling this method will result in the response's content being compressed (gzipped). Additionally, a "Content-Encoding" header will be added to the response, indicating that the content has been compressed.
Note that this method will be called automatically when a request returns content, if the Compress property is set to True.
This method makes it easy to return cookies as part of a response.
There are two ways to call CookieSet. First, you can specify a cookie name, value, and the cookie's expiration date as a Date. For example:
Dim ExpirationDate As Date Dim DateInterval As Xojo.Core.DateInterval = New Xojo.Core.DateInterval(0, 0, 0, 0, 0, 30) ExpirationDate = Xojo.Core.Date.Now + DateInterval Request.Response.CookieSet("x", "ABC", ExpirationDate) Request.Response.CookieSet("y", "123", ExpirationDate)
You can also call CookieSet by passing a cookie name, value, and integers that represent its expiration based on a number of days, hours, minutes, and seconds. For example:
Request.Response.CookieSet("x", "ABC", 0, 0, 0, 30) Request.Response.CookieSet("y", "123", 30)
Before returning a response, Aloe Express automatically creates any "Set-Cookie" response headers that are needed, based on the cookies that have been specified.
The Dump method can be used to generate HTML that lists many of the Response's properties. It is useful when debugging applications.
The MetaRefresh method is provided as a convenience. With it, you can easily generate an HTML response that performs a meta-refresh to a specified URL.Can be helpful when the response needs to both set cookies and redirect the user.
The SecurityHeadersSet method is provided as a convenience. It sets several security-related headers, including:
Indicates if the response content should be compressed. By default, the property is set to False.
When a Request instance creates a Response instance, the request is evaluated to determine if the response should be compressed. Specifically, the "Accept-Encoding" header is evaluated, and if gzipped content is accept by the client, then the Compress property is automatically set to True. For implementation details, see the Request.ResponseCompressDefault method.
The Content property (a string) is used to specify the content that will be returned in the response.
Cookies is a Dictionary that is used to specify any cookies that should be returned as part of the request. It is used by the CookieSet method, but can also be accessed and modified directly.
The Headers property, a Dictionary, is used to specify any HTTP headers that should be included in the response.
Several default headers are assigned to the dictionary when a Response instance is created. They include:
Note that you can remove and override the default response headers as needed.
To learn more about HTTP headers, see https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
This property indicates the HTTP version used for the response. The default value is 1.1.
The Aloe Express Request instance that the response is associated with.
Use the Status property to specify the HTTP status code that is to be returned. By default, the Status is set to "200 OK."
To learn more about HTTP status codes, see https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
All Aloe Express-based apps include an instance of the Server class. The class includes a ServerSocket as a property, which listens on a specified port for incoming requests, and hands them off to a pool of Request instances.
The Server class is a subclass of Xojo's ServerSocket class. As a result, ServerSocket's properties and methods are available.
Normally, a Server instance is instantiated in an app's Run event handler. For example:
Dim Server As New AloeExpress.Server(args) Server.Start
In this example, the app's command-line arguments are passed to the Server's constructor method. There are five command-line arguments that are supported: --port, --maxsockets, --minsockets, --loopback, and --Nothreads. When provided, the arguments are used to set the server's properties (described below). This makes it possible for you to configure the server's port and sockets at runtime.
You can also configure the server's properties explicitly. For example:
Dim Server As New AloeExpress.Server(args) Server.Port = 64000 Server.MaximumSockets = 100 Server.MinimumSockets = 50 Server.Loopback = True Server.Start
Starting in Aloe Express 2.0, the Server class provides full SSL / TLS support.
You can configure a server's SSL-related properties explicitly. For example:
Dim Server As New AloeExpress.Server(args) Server.Port = 443 Server.Secure = True Server.ConnectionType = SSLSocket.TLSv12 Server.CertificateFile = GetFolderItem("").Parent.Child("certificates").Child("certificatefile.crt") Server.Start
In addition, you can configure the SSL-related properties using command line arguments. For example:
--Secure --ConnectionType=5 --CertificateFile='/aloe/app/certificates/certificatefile.crt'
Use the start method to have the server begin listening for incoming requests.
Can be used to send a message to all active WebSockets.
A boolean value with a default of False. This property determines whether or not an instance of the AloeExpress.CacheEngine class is created and associated with the Server (via the CacheEngine property described below) when the server starts.
CacheEngine is an AloeExpress.CacheEngine instance, which is optionally created if the server is started with the CachingEnabled set to True.
If the server's caching is enabled (see "CachingEnabled" above), then this value is used to determine the frequency with which expired cache entries are removed. This is an Integer with a default value of 300
Use this FolderItem to specify the location of the server's SSL certificate. The default location is a "certificates" folder in the parent directory of the app's folder, and the default certificate name is: default-certificate.crt
The certificate's password, if applicable.
Indicates the type of connections that the SSLSockets should use. Refer to ConnectionType property of the Xojo SSLSocket class for the types of connections that are supported. The defaut is TLSv12 (5).
A dictionary that persists between requests, and is scoped in such a way that it acts very much like an App-level property. Can be used to store server-specific custom attributes.
Set the Loopback property to true if you want to force the app to bind to the loopback network interface. When enabled, only for requests originating from the same machine will be processed. By default, Loopback is set to False.
Specifies the maximum size of entities that will be accepted by the server. This is particularly helpful when you want to limit the size of file uploads. By default, this is set to 10Mb.
Specifies the maximum number of connections the Server's ServerSocket instance will allow to connect. The default value is 10.
Specifies the minimum number of sockets available in the Server's Request pool. The default value is 3.
The AloeExpress Server uses a multi-threaded model where each request is processed in its own thread. The Multithreading property can be used to disable this feature, so that requests are processed in the primary thread. This is a Boolean value, with True as the default. The property can be set directly, or via the command line using the "--Nothreads" argument.
Can be used to display an alternate name when the server launches. The default is "Aloe Express Server."
Specifies the port that the server will be bound to and will listen for connections on. The default value is 8080.
Indicates whether the server is running in secure mode using SSL connections. The default value is False.
A boolean value with a default of False. This property determines whether or not an instance of the AloeExpress.SessionEngine class is created and associated with the Server (via the SessionEngine property described below) when the server starts.
SessionEngine is an AloeExpress.SessionEngine instance, which is optionally created if the server is started with the SessionsEnabled set to True.
If the server's sessions are enabled (see "SessionsEnabled" above), then this value is used to determine the frequency with which expired sessions are removed. This is an Integer with a default value of 300
Can be used to suppress the display of the server info when the server launches. Defaults to False.
An array of AloeExpress.Request instances, which supports bulk WebSocket-related functions such as message broadcasting.
Can be used to specify the number of seconds of inactivity that can pass before a WebSocket will be considered to have timed out. The default is 1800 seconds (30 minutes). To disable WebSocket timeouts, set WSTimeout to zero.
Aloe Express-based apps can be designed to listen on multiple ports, in which case the app is actually running multiple instances of the Server class, each in its own thread. The Aloe Express "ServerThread" helps to make this possible.
The ServerThread class is a subclass of Xojo's Thread class. As a result, the Thread class's properties and methods are available.
In this example, the app is being configured to use three Server instances, each listening on its own port, and each assigned to its own thread.
Dim ServerThread1 As New AloeExpress.ServerThread ServerThread1.Server.Port = 64000 ServerThread1.Run Dim ServerThread2 As New AloeExpress.ServerThread ServerThread2.Server.Port = 64001 ServerThread2.Run Dim ServerThread3 As New AloeExpress.ServerThread ServerThread3.Server.Port = 64002 ServerThread3.Run While True app.DoEvents Wend
Refer to the Xojo Thread class for methods.
This is an instance of the Aloe Express Server class that has been created to run in the thread.
Refer to the Xojo Thread class for additional properties.
SessionEngine, a subclass of the Xojo Timer class, is used to manage session in Aloe Express-based Web apps and sites. It handles the creation and maintenance of sessions.
Given a Request instance, SessionGet returns a session to the caller. The session is implemented as a Dictionary, which gives you the ability to store a wide range of values and objects in the session. If the specified Request instance does not already have a session associated with it, SessionGet will create one.
Additionally, SessionGet takes a second optional parameter, AssignNewID, as a Boolean value (with a default value of True). When AssignNewID is True, SessionGet will assign a new SessionID value for the session, which helps prevent session fixation attacks.
Dim Session As Dictionary = App.SessionEngine.SessionGet(Request) If Session.Value("Authenticated") = False Then Request.Response.MetaRedirect("/login") Return End If
The session dictionary that is returned includes the following entries:
This method, which is called on a timer, removes any expired sessions. The frequency of the timer is based on SessionEngine's SweepIntervalSecs property. You do not need to call this method directly.
In some cases, you might want to terminate a sessions prior to it expiring. For example, when an authenticated user logs out of an application. In those cases, call SessionTerminate.
Dim Session As Dictionary = App.SessionEngine.SessionGet(Request) App.SessionEngine.SessionTerminate(Session)
SessionEngine maintains sessions via the Sessions property, which is a Dictionary. The keys used for the Sessions dictionary are SessionIDs, which the engine automatically generates as needed.
SessionEngine automatically handles session timeouts. This is the situation where a session hasn't been active for awhile, and it is assumed that the session is no longer active. The SessionsTimeOutSecs property, which is an Integer value with a default value of 600, is used to specify the number of seconds that can elapse between requests, after which a session will be terminated.
This property, an Integer value with a default value of 300, is used to specify the number of seconds between runs of the SessionsSweep method.
This is usually called via the app's Run event handler, where SessionEngine itself is a property of the app.
SessionEngine = New AloeExpress.SessionEngine
// Get a session. Session = App.SessionEngine.SessionGet(Request) // If the user has not been authenticated... If Session.Value("Authenticated") = False Then Request.Response.MetaRedirect("/login") Return End If
As of v3.0, the Template class has been moved to a Templates modules. The class is now named MustacheLite.
The Template class can be used to merge data with mustache-like logic-less templates to render documents.
XSProcessor is an internal Aloe Express class that is used by the Request class to process XojoScript blocks found within static content. The class is used by Request.MapToFile to parse XojoScript code blocks within files (if the Request.XojoScriptEnabled property is set to True). However, the class can also be used process ad-hoc XojoScript code, or code blocks that are generated or obtained outside of the MapToFile method.