Out With the Old

In the previous post I described the rationale and the approach to building a custom fitness tracker for the desktop. The application was to be built using the Windows Presentation Foundation. As far as execution goes, I had a lot to learn about the correct way to use WPF. The first commit of the application followed so many WinForms paradigms that it made zero sense to involve the overhead of WPF.

FitNet Desktop screenshot

This is what the XAML that implements the above screen looked like.

<TabControl>
     <TabItem Header="Summary">
         <fit:Summary/>
     </TabItem>
     <TabItem Header="Reports">
         <Label>Reports View</Label>
     </TabItem>
     <TabItem Header="Tracking">
         <Label>Tracking View</Label>
     </TabItem>
</TabControl>

Perfectly readable, but it would quickly devolve either into a big ball of mud with XML nodes nested several layers deep in a single file, or turn into a pile of nested classes inheriting unrelated behaviour from a few common base classes. Either case was unacceptable. But I didn’t know that yet.

The second mistake was borrowing a data-access implementation from a previous project which was based on a primitive architecture. The template pattern that this layer implemented was fine for a small number of data objects. But it becomes tedious to build a separate reader and writer sub-class and its associated ancillary classes for every aggregate data type (and FitNet requires quite a few of those). I needed something that was easier to extend when it came to data access.

FitNet Desktop Solution View

The third major flaw was having monolithic namespaces out of ignorance of the WPF architectural style, and not using its paradigms to the best benefit. This resulted in the application turning into three projects – a Desktop project as the primary executable, a Desktop.Lib library project as a massive collection of view classes, and a Persistence project which implemented the aforementioned half-functioning data access layer.

I went through this path for several weeks before finally realising my folly, by which time I had actually built quite a bit of useful functionality in the application. But it was getting unwieldy to make any modifications or add new functionality. It seemed like I was constantly fighting against the framework in order to get things done.

I had finally had enough of this struggle when I had to implement a flyout for modifying the list of exercises in the database. Adding yet another node to the already crowded main window file and more inline click event handlers in the backing CS file were a clear indicator that I was doing this wrong. There was no way this could scale up elegantly.

This is where I decided to take a step back and try to understand what the heck was going on.

Fortunately I stumbled upon XPence, an expense tracking application built on WPF by Siddhartha S. and hosted with an in-depth development tutorial on Code Project.

Hang on for the next part where I finally begin to turn this ship around to a more meaningful course.

Introducing FitNet

The recent surge in fitness-related technology innovations bodes well for the future of many people. And though the Cheeto-munching, Red Bull-guzzling stereotype for the technologists behind this progress still sticks, the truth is that more people, including programmers, are gaining awareness of their physical health and nutrition and changing lifestyles to seek improvement.

Latching on to this bandwagon came a surge of fitness tracking apps. FitNotes, StrongLifts 5×5, the Starting Strength App by legendary strength-training coach Mark Rippetoe, Strong App for iOS, and many more, provide ample choice to the enthusiast as well as advanced lifter. These apps cover various aspects, from simple tracking, to full blown programme design with progressions and periodisation. Some applications work online. Your data is stored on their server, and requires an internet connection to access and update. Others are offline, or a hybrid of both modes. Many are free and use ad revenue to sustain operations. Some of the fancier ones are paid. They all have their pros and cons.

Having used a small subset of them in the past few years, I have identified certain shortcomings between them.

Incompatible Storage

This is especially annoying because most of these applications use the same database engine – SQLite. But it’s impossible to move from one application to another without a lot of manual re-entry of data.

Now this is an understandable shortcoming. Database design is an engineering activity. People approach the same problem differently based on their skill levels and priorities. Copying databases between applications will never work directly. But the problem can be mitigated to a great extent by the industry agreeing to a common minimum format that they all support, which can be used to send data out of the application. Customers do not like being locked in.

Changing Platforms

Mobile phones change often. I have found myself switching between Blackberry to Android to iOS in a few short years. Fitness journeys last a lifetime. Phones last a few years, at best.

This is to some extent, a manifestation of point 1 above. If the common minimum format were to come together, changing platforms would become much easier. However, there’s another more subtle point. The one unchanged platform over all these years has been the desktop and the Windows operating system. People usually have access to at least one Windows computer. Even though Android has become the most popular operating system, the Windows desktop remains firmly lodged into place at workplaces, schools and homes. It’s still a very stable and dependable platform to target.

Privacy

It is possible to cast all these troubles away and switch to a web-based application. However, people are not always comfortable with storing sensitive personal information on a server that is not in their control. Not to mention the risk of the company going belly-up and taking their precious PR logs along with it.

This is a no-brainer. Put the data on the user’s own computer, where they do not have to worry about losing their privacy. Include an automated backup feature that saves the encrypted data on their cloud-storage service. The data remains reasonably safe from loss as well as from prying eyes. Again, a common minimum format can prove to be very useful in the worst case scenario of 100% loss of the physical computer itself.

These were real and personal pain-points I experienced first-hand. And being a programmer gave me the ability to actually work on a solution that addresses these problems.

Introducing FitNet

The easiest replacement to these woes was a spreadsheet. Smack a new row for every workout, see real-time graph updates. It works as a log, but getting a report out of it is a chore. Besides, programming fancy reports into a spreadsheet eventually turns it into a prime feature for The Daily WTF. So that was out. Microsoft Access used to be a very good tool for this kind of tasks, but it still leaves out graphical reports. And the new monthly subscription model for Office 365 just isn’t for me.

Enter Windows Presentation Foundation.

I have been using Windows Forms since the longest time as the tool of choice for building desktop applications on Windows. It’s easy and it’s straightforward, and anybody who’s working with the previous Windows API feels perfectly at home with the new managed API that WinForms represents.

Windows Presentation Foundation is different. It is not just a wrapper around the Windows API. It’s a whole different framework which eschews the disparate development sub-frameworks from the Windows API in favour of a single well-integrated and extensible library. It also accounts for differing device capabilities in a more resilient fashion by abstracting away tasks like drawing objects relative to the device resolution and hardware accelerated graphics available out of the box without any extra effort. Finally, WPF brings a new type of resource – a XAML file – to be used as a declarative approach to building and programming user-interface elements rather than the procedural approach required by the Windows API.

This means that the following 50 lines of code –

WNDCLASSEX wc;
HWND hwnd;
MSG Msg;

// Registering the Window Class
wc.cbSize        = sizeof(WNDCLASSEX);
wc.style         = 0;
wc.lpfnWndProc   = WndProc;
wc.cbClsExtra    = 0;
wc.cbWndExtra    = 0;
wc.hInstance     = hInstance;
wc.hIcon         = LoadIcon(NULL, IDI_APPLICATION);
wc.hCursor       = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wc.lpszMenuName  = NULL;
wc.lpszClassName = g_szClassName;
wc.hIconSm       = LoadIcon(NULL, IDI_APPLICATION);

if (!RegisterClassEx(&wc))
{
  MessageBox(NULL, "Window Registration Failed!", "Error!",
MB_ICONEXCLAMATION | MB_OK);
return 0;
}

// Create the window
hwnd = CreateWindowEx(
  WS_EX_CLIENTEDGE,
  g_szClassName,
  "FitNet Desktop",
  WS_OVERLAPPEDWINDOW,
  CW_USEDEFAULT, CW_USEDEFAULT, 400, 300,
  NULL, NULL, hInstance, NULL);

if (NULL == hwnd)
{
  MessageBox(NULL, "Could not create application window.", "Error", MB_ICONEXCLAMATION | MB_OK);

  return 0;
}

ShowWindow(hwnd, nCmdShow);
UpdateWindow(hwnd);

// Message loop
while(GetMessage(&Msg, NULL, 0, 0) > 0)
{
  TranslateMessage(&Msg);
  DispatchMessage(&Msg);
}

return Msg.wParam;

– can be distilled down to –

<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="FitNet Desktop" Height="400" Width="300" />

Now it can be argued that the Windows Forms API also offers similar succinctness. But WPF takes this to a whole different level as I learned through the course of my project.

This series of articles is an ongoing log of my journey of building FitNet – a fitness tracker that meets my own needs.

Reifying Your Commands – Interprocess Communications by Example

In the first part of this series, I introduced readers to the work reify, which means to make something real. So far, we have seen how the ActionScript application converts a logging request into a command object, serialises it into a byte array, and sends it over a TCP socket connection into the waiting arms of a server. The server for its part must deserialise the byte array back into a command object and execute it.

This last part in the series explains how this is done.

The Story So Far

We have seen how the Puppeteer receives a message. In the receive callback method is a call to deserialise the message into an object.

byte[] message = new byte[messageLength];
Buffer.BlockCopy(buffer, 4, message, 0, messageLength);

ICommand command = Util.Deserialize(message);

The Deserialize utility method receives only the portion of the message that constitutes the actual data. The first 32 bits are discarded as they are not relevant to the deserialisation process. The Deserialize method is extremely simple.

public static ICommand Deserialize(byte[] message)
{
    Dictionary<byte, type=""> instructionClassMap = new Dictionary<byte, type="">() { { 0x02, typeof(Trace) } };

    Type commandType = null;
    ICommand command = null;
    if (instructionClassMap.TryGetValue(message[0], out commandType))
    {
        command = (ICommand)Activator.CreateInstance(commandType, new object[] { message });
    }

    return command;
}

It reads the first byte from the message which contains the instruction to be executed. The instruction is then used as key to look for the type in the instruction map. The Activator.CreateInstance() API is used to instantiate the type into a variable. The instance is then returned from the function.

The receive callback then dispatches a CommandReceived event. The application implements the plumbing from that point onward to handle the event notification and act upon it.

At this point, we need to take a step back and observe the command object instantiation in detail. Each command type has its own implementation detail which interprets and utilises the message. The Trace class, for example, reads the level, category and message values from the message. Its constructor is listed below.

public Trace(byte[] message)
{
    int unixTimeStamp = message[1] << 24 | message[2] << 16 | message[3] << 8 | message[4];
    TimeStamp = Util.UnixTimeStampToDateTime((double)unixTimeStamp);
    int paramCount = message[5] << 24 | message[6] << 16 | message[7] << 8 | message[8];
    parameters = new string[paramCount];
    int index = 9;
    
    for (int i = 0; i << paramCount; i++)
    {
        int length = message[index] << 8 | message[index + 1];
        parameters[i] = Encoding.UTF8.GetString(message, index + 2, length);

        index += (2 + length);
    }

    Level = parameters[0];
    Category = parameters[1];
    Parameters = parameters;
}

The first byte contains the instruction. This is ignored since we already know that the instruction is Trace (0x02).

The next four bytes contain the timestamp of the message as a 32-bit integer. The value is converted into DateTime object through a utility method.

The next four bytes contain the number of parameters that are passed into the Trace command. The command uses this number to determine the number of string objects to retrieve from the message. Remember that each string object is prefixed by a 16-bit integer that contains the number of characters that make up the string. That’s where the index + 2 comes from, which offsets the current position in the array by another 2 bytes. Once the parameters are loaded into an array, they are assigned to public accessors of the Trace class.

The application uses the public members to display the Trace command on screen and store them into a database for persistence.

Socket Talk – Interprocess Communications by Example

In the previous article in this series, I explained the logging framework that the Flex SDK provides, limitations of the Flash Player at providing effective run-time logging, and how they can be circumvented by using the Socket API. I also described a custom message data structure that encodes the information to be sent out of the Flash Player. This part of the article explores the implementation of the socket server that receives the message, and how it decodes it into meaningful instructions and information.

Introducing…Puppeteer!

Puppeteer is a desktop application that runs on Windows which can be used to manipulate one or more client applications. The application works by opening up a TCP port for client applications to connect to, then exchanging messages over the connection to send or receive instructions back and forth. Messages are binary-encoded and follow a simple format which was described in the previous article. Instructions are 8-bit integers, and therefore, have an upper limit of 255 possible values. The message may contain an additional payload along with the instruction. There is no limit to the length of the message.

Client applications require to integrate the ability to dispatch, receive and parse messages to Puppeteer. It cannot connect to any application on its own without the application explicitly requesting the connection, and having the ability to dispatch or react to messages from the server. Client applications can be written on any platform that supports TCP sockets.

On startup, Puppeteer begins listening for incoming connections from client applications on a well-known port number. It also accommodates certain idiosyncrasies specific to the Flash Player. Applications written in other languages can ignore these aspects, as they are most likely not relevant to their own ability to function correctly.

“Hello!”

One of the restrictions applied on the Flash Player is that every TCP socket connection must be explicitly authorised by the owner of that server. To quote Peleus Uhley from the Adobe website –

One of these features is the ability to create TCP sockets in order to exchange data with servers. From a network administrator’s point of view, the idea that content from the Internet could make socket connections to internal hosts is scary. This is why Flash Player requires permission from the target host before it will allow content to make the network connection.

The policy file is requested automatically by the Flash Player the first time the content playing in makes the connect() API call. The process followed is described below.

  1. The content (.swf file playing the the Flash Player) requests a connection to the server through the Socket API.
  2. The Flash Player checks its whitelist if the server has already allowed access to the content.
  3. If it does not already have a policy file for the server in memory, it pauses the connection request from the content and instead tries to connect on port number 843. If a connection is established on this port number, it sends a message containing the string “”.
  4. If the server does not respond on port number 843 unti timeout, the Flash Player attempts to connect again on the same port number that is requested by the content.
  5. The server must respond by sending back the contents of the policy file as soon as the connection is accepted. Any other response from the server will be considered invalid and the Flash Player will disconnect from the server.
  6. Once the policy file is served, the Flash Player parses it for correctness and checks if it authorises the content to connect to the server. If the policy file allows the connection, the content is notified about it and is now able to communicate freely with the server.

So the first requirement for Puppeteer is to be able to listen for a client request for a socket policy file and serve it up. The application does not listen for incoming policy file requests on port 843. Instead, it responds with the policy file when the client attempts to connect on the public incoming request port number (1337 by default). The response is an XML document encoded as a null-terminated string. The null at the end is necessary. The XML response will be treated invalid without it (many hours were wasted in learning this seemingly insignificant detail).

A Mirrored Standard for Commands

Puppeteer works in tandem with the command pattern implemented by its corresponding client library. Each message is serialised into a byte array, which contains the instruction number of the command being invoked, and the payload that accompanies the instruction. It must, therefore, be able to parse and interpret the message, which is done by mirroring the ICommand interface and its implementation classes in .NET.

public interface ICommand
{
    event ExecutionCompletedHandler ExecutionCompleted;

    DateTime TimeStamp
    {
        get;
    }

    void Execute();
}

The ICommand interface declares the Execute() method, same as the one contained within the ActionScript code. It also declares a public property called TimeStamp and an ExecutionComplete event. A CommandBase class implements this interface and provides the basic common set of methods which are required to fulfill this contract.

public abstract class CommandBase : ICommand
{
    …
}

Finally, separate classes are written for each command that Puppeteer must be able to interpret and understand.

public class Trace : CommandBase
{
    …
}

Insert Plug Here

The previous article talked about sockets very briefly. So let me explain that topic before proceeding.

Sockets are a software construct that operating systems use to communicate over the network. They are handles to resources over a network interface, same as files are handles to resources on the hard disk. They come in various different types, of which datagram and stream sockets are most commonly heard of. They are often referred to by the protocol they typically use – UDP for datagram sockets, and TCP for stream sockets. Puppeteer is built on stream sockets. The .NET framework ships with a managed implementation of the socket API in the System.Net.Sockets namespace. The Socket class is the primary actor in this namespace.

On startup, the application begins with instantiating the Socket class, binding it to a local end point and setting it to listen for incoming connection requests.

listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
endPoint = new IPEndPoint(0x0100007F, 1337);
listener.Bind(endPoint);
listener.Listen(0);
listener.BeginAccept(BUFFER_SIZE, new AsyncCallback(AcceptConnection), listener);

In this example, a stream socket is initialised to use the IPv4 addressing scheme and TCP protocol. In order to begin listening, the socket must be bound to an end point, which is a combination of an IP address and a port number. Every TCP connection can be uniquely identified by its two end points – one on the host, and the other on the client. The IPEndPoint class represents an end point on one end of the connection. The IP address of the end point is represented as a hexadecimal-encoded, big-endian 64-bit integer.

Note: The IP address of the computer is hard-coded to 127.0.0.1 in this example. There are more sophisticated techniques to identify the IP address of the computer that the application runs on at run-time which are excluded here for brevity.

Listen is a non-blocking API call. The thread continues to run while the socket is listening for incoming connections. For single-threaded applications, the programmer must put the application into a loop while calling BeginAccept() periodically, in order to prevent it from exiting. Since Puppeteer is a Windows Forms application, this is not necessary.

The buffer size parameter of the BeginAccept API specifies the number of bytes that the server has to read from the message sent by the client. The AsyncCallback is a reference to a callback that is fired when an incoming connection request is received. The last parameter is a state object which can be used to pass around the state of the connection. In this case, the Socket instance itself is used as the state object.

The callback contains code to handover the connection from the listener to another Socket instance dedicated to communicating with the client. This is required so that the listener can be freed to continue to listen for incoming requests on from other clients. The EndAccept() API automatically creates a new Socket instance to communicate with the client.

private void AcceptConnection(IAsyncResult result)
{
    Socket listener = (Socket)result.AsyncState;
    Socket clientSocket = listener.EndAccept(result);

    byte[] response = Encoding.ASCII.GetBytes(SocketPolicy);
    clientSocket.BeginSend(response, 0, response.Length, SocketFlags.None, new AsyncCallback(SendData), clientSocket);
    listener.BeginAccept(new AsyncCallback(AcceptConnection), listener);
}

Once the connection has been established on the new socket, the server must first publish the string containing the socket policy file required by the Flash Player. It does this with the BeginSend method on the new socket. Finally, the original socket instance which is bound to a well-known port number is set back to accept incoming connection requests.

The .NET framework triggers an AsyncCallback when the data has been sent over the new socket instance. This callback signals the socket to end the sending operation, clears the incoming buffer and sets the socket to begin receiving data when the client sends it.

private void SendData(IAsyncResult result)
{
    Socket clientSocket = (Socket)result.AsyncState;
    clientSocket.EndSend(result);
    Array.Clear(buffer, 0, BUFFER_SIZE);
    clientSocket.BeginReceive(buffer, 0, BUFFER_SIZE, SocketFlags.None, new AsyncCallback(ReceiveData), clientSocket);
}

The last stage in this cycle is to receive and process the data, and either respond to the data if required, or set the client socket back into the receiving state as shown here. This is where the meat of the operation occurs. The basic structure of the ReceiveData() method is shown below.

private void ReceiveData(IAsyncResult result)
{
    Socket clientSocket = (Socket)result.AsyncState;

    if (clientSocket.Connected)
    {
        Array.Clear(buffer, 0, BUFFER_SIZE);
        clientSocket.BeginReceive(buffer, 0, BUFFER_SIZE, SocketFlags.None, new AsyncCallback(ReceiveData), clientSocket);
    }
}

Some basic processing is also performed in this method. The application is aware of the message structure that was described in the previous article in this series. The ReceiveData method receives the entire message, but only processes the first four bytes which contain the total length of the message. The rest of the bytes from the message are read from the buffer into a byte array and passed on to a deserialisation utility class, which converts it into an ICommand instance.

private void ReceiveData(IAsyncResult result)
{
    Socket clientSocket = (Socket)result.AsyncState;

    // Extract the length of the message from the first 4 bytes
    int messageLength = buffer[0] << 24 | buffer[1] << 16 | buffer[2] << 8 | buffer[3];

    // Extract the bytes containing the message and deserialize it into an ICommand object
    byte[] message = new byte[messageLength];
    Buffer.BlockCopy(buffer, 4, message, 0, messageLength);

    ICommand command = Util.Deserialize(message);

    if (clientSocket.Connected)
    {
        Array.Clear(buffer, 0, BUFFER_SIZE);
        clientSocket.BeginReceive(buffer, 0, BUFFER_SIZE, SocketFlags.None, new AsyncCallback(ReceiveData), clientSocket);
    }
}

Finally, the method triggers a CommandReceived event which other classes in the application subscribe to in order to act upon the command.

private void ReceiveData(IAsyncResult result)
{
    Socket clientSocket = (Socket)result.AsyncState;

    // Extract the length of the message from the first 4 bytes
    int messageLength = buffer[0] << 24 | buffer[1] << 16 | buffer[2] << 8 | buffer[3];

    // Extract the bytes containing the message and deserialize it into an ICommand object
    byte[] message = new byte[messageLength];
    Buffer.BlockCopy(buffer, 4, message, 0, messageLength);

    ICommand command = Util.Deserialize(message);

    if (null == CommandReceived)
    {
        return;
    }

    CommandReceivedEventArgs e = new CommandReceivedEventArgs(command);
    CommandReceived(this, e);

    if (clientSocket.Connected)
    {
        Array.Clear(buffer, 0, BUFFER_SIZE);
        clientSocket.BeginReceive(buffer, 0, BUFFER_SIZE, SocketFlags.None, new AsyncCallback(ReceiveData), clientSocket);
    }
}

In the next part in this series, I will explain how the command is deserialised and executed by the Puppeteer.

A Message in a Socket – Interprocess Communications by Example

Introduction

I couldn’t help but feel like a luddite as I sat down to write down this article. Who works on Flash applications in 2016 any more? Aren’t we all done with it now?

The Flash Player might have its own set of problems, which is a topic for another discussion. The ActionScript language, however, is fun to work with. It is syntactically similar to Java, has a class-based inheritance model, a choice between static or dynamic typing, or both, within the same code base, namespaces, and a host of easy to use and powerful APIs for 2D and 3D graphics, network operations, animation, audio processing, XML and text processing, and more. Frameworks like the open source Flex SDK make it possible to do even more interesting things on top of this.

But, more importantly, we are heavily invested into the Flash ecosystem for the VMX platform at Vertika. We have 9 years of effort and 40,000 lines of code written in ActionScript and MXML, which would be very expensive to port over to a new platform without a very compelling business reason. So here we are today.

Unfortunately, the Flash Platform also comes with its idiosyncrasies, one of which is addressed in this article.

For those losing interest at the mention of Flash, the good thing about this client architecture is that it can easily be ported over to literally any other platform with little change and still work. And the server-side stuff is written in C#. Collectively, this solution covers a plethora of different concepts such as socket programming, data structure design, a custom-built lightweight ORM framework and design patterns.

Raison D’être

The Great Catsby is a rather upset feline. He is fond of company and loves nothing more than to kick back with a saucerful of heavy cream milk and a stack of Calvin & Hobbes comics with his human pals. But they just won’t let him out of his cage. Catsby, you see, is a 300 kilogram Bengal Tiger at the zoo. And no matter how much he pleads, they are not going to let him out and explore the city.

It’s a rather bleak state of affairs for the poor cat.

The guys at Adobe (then Macromedia) had the same ideas when they designed the Flash Player, which was designed primarily as a browser plug-in to play specially authored content served off websites. And as every competent security-minded person knows, it can be a very bad idea to allow strange websites to gain unrestricted access to your computer. Even if every ActionScript programmer pinky-swore not abuse their users’ trust, the guys at Macromedia were not going allow them free rein over the computers running the Flash Player. Hence, Flash content runs in a sandbox with several restrictions, one of them being no direct access the file system.

This is a tough situation for many programmers who need any kind of runtime application logging. No file system access means there is no persistent data storage on the client.

It is not that there’s no logging at all. The Flash Player Debugger exposes a very limited, plain-text log file access that is disabled by default, and requires a configuration flag in a specific plain-text file in order to be activated. The state of this flag cannot be queried or controlled from within the Flash Player. Extracting the file is a task and a half because it’s buried deep within the file system hierarchy. The log file is shared among all Flash Player applications which are executed on that computer. While there is no possibility of data conflicts, filtering and extraction of the data that is relevant to your application becomes a challenge. Finally, since this is a plain-text file, there is no structured information storage facility available here other than what can be achieved with plain text files (such as comma-separated values).

Did I mention that even this facility is only available on a special Debugger edition of the Flash Player that most people don’t use?

In effect, it’s impossible to have any kind of reliable, persistent runtime logging on a production computer. A third-party intervention is essential. And this is the challenge that is addressed in this article – a logging framework that allows Flash content to delegate the task of persistent storage to another process, which runs at a higher privilege level and has access to the file system. The persistence process can be running locally on the same computer, or on another computer. The mechanism works identically as long as the two computers are able to establish a connection with each other over standard sockets.

Hi! It’s me, your brother!

Parents are like the operating system of the family. They spawn child processes, manage resources and schedule time for tasks. A well-organised family is like Unix. Every child gets their own space, and nobody gets into each other’s way. When they have to communicate, they send messages to pre-designated points. These could be a cell phone, a sticky note on the fridge or a whiteboard in the hallway. They could also speak across the dinner table, but nobody does that in 2016. So that’s out.

Speaking over the cell phone is more versatile because it works whether the person is at home or away at work, out running an errand, or at a party. A message on a sticky note is only delivered when the person returns back home and checks the fridge.

Operating systems also offer similar means to communicate between processes. You could send a message to the recipient over a socket, or write to a file that the recipient checks periodically. Since we have already discussed earlier that writing to files is out, that leaves us with socket communications.

Fortunately, the Flash Player has an API to communicate over TCP sockets. It works identically when communicating with a different device or another process on the same computer where the Flash application is being run. The Flash Player Socket API can only make client-side calls. It cannot listen for connections from another process. Therefore, the external application must play the role of a server and begin listening for connection requests from the Flash Player on a known port number. Once the connection is established, the two processes can send messages back and forth.

This mechanism can be utilised to create an external logging tool that listens for messages from a Flash Player client, and logs them to a persistent storage such as hard disk. Since the socket API works locally as well as remotely, the logging server can be situated at an offsite location, and as long as the two computers can communicate with each other, log messages will be successfully delivered and logged.

Flex Logging API

A lot of work that is needed to establish a robust logging API has already been implemented as part of the Flex SDK in form of the Logging API, which is loosely modelled on its Java framework equivalent. This API provides a convenient way to create structured log messages with severity levels and named categories. A log message is triggered by simple API calls, and is printed to a destination by a target object. Targets can be programmed to listen for messages at a certain severity level (and above), as well as certain categories only. For example, low-latency logging such as an in-memory temporary store can be used for diagnostic messages which are triggered more often, while infrequent but critical errors can be dispatched to remote persistent storage.

The SDK ships with two in-built logging targets – LineFormattedTarget and TraceTarget – which provide basic logging facilities to the application. TraceTarget prints the message to the Flash Builder or fdb console and extends LineFormattedTarget.

The Flex Logging API is documented elsewhere in sufficient detail. However, I’ll cover it briefly in this article to provide context to the reader for how it is used.

The API is centred around four types.

  1. mx.logging.Log
  2. mx.logging.ILogger
  3. mx.logging.LogEvent
  4. mx.logging.ILoggingTarget

The SDK ships with a mx.logging.AbstractTarget class that implements the ILoggingTarget interface. Developers can extend this class to build their own custom logging target implementations.

How the Flex Logging API Works

The ILogger interface provides methods to send messages to one or more targets. The developer doesn’t create the logger instance directly. Rather, they call upon the getLogger static method of the Log class to retrieve an ILogger implementation instance. The getLogger method takes a string parameter called category, which can be used to filter log messages down to a particular sub-system within an application.

The category is conventionally set to the fully-qualified name of the class that calls the ILogger API.

The ILogger interface also exposes methods to perform log operations at five different severity levels, and a generic log method that takes the severity level as a parameter.

The severity levels in increasing order are DEBUG, INFO, WARN, ERROR and FATAL.

var logger:ILogger = Log.getLogger("com.notadesigner.ExpletiveGenerator");
logger.info("Sonofagun!");
logger.log(LogEventLevel.FATAL, "Crumbs!");

A logging target receives the log message and prints it to the destination medium. The logging target has a property called level, which determines the severity of messages that it will receive.

var target:ILoggingTarget = new TraceTarget();
target.level = LogEventLevel.INFO;

The target receives all messages of its assigned severity level and below. For example, the target instance in the example above would be able to receive DEBUG and INFO messages.

A logging target instance also has a filters property of type array that contains the categories which this instance should listen for.

target.filters = [ "com.notadesigner.ExpletiveGenerator" ]; // Category name must match

This snippet enables the target to receive all log messages whose category is set to “com.notadesigner.Example”. The filters array can contain more than one category.

target.filters.push("com.notadesigner.GreetingsGenerator");

The target is actually of greatest interest in this article, because it is this class that performs the message printing. In order to send the message to an external process, we need to build a custom logging target that is able to dispatch messages over a socket.

com.notadesigner.sockPuppet.SocketTarget

The SocketTarget class extends AbstractTarget rather than LineFormattedTarget, because the latter merges all the message fields into a single string, which we don’t want. By keeping them as separate fields of their native types, we get maximum control over the structure of the message, as well as the least amount of memory usage.

We begin by instantiating the class.

var target:SocketTarget = new SocketTarget("localhost", 1337);

The constructor takes two parameters for the host name and the port number on which the socket server is already ready and running. We will gloss over the details of performing the connection and maintaining it.

When a message is received, the logging framework triggers the logEvent method of the SocketTarget instance. This is defined as an empty method in the AbstractTarget class that takes a parameter of type LogEvent. By overriding this method, the SocketTarget instance can then dispatch the message to the server.

Making It Real

Before Daryl got into the programming business, he used to wait at the local deli. His job was to take orders from diners and pass them on to the kitchen, and serve the completed order after it was prepared by the kitchen staff. Daryl’s task was simple. He would jot down a list of orders from the table and pass it on to the chef. The chef would then prepare whatever items came up in the queue, and ring up the waiting staff once it was ready. The staff picked the completed order and served it fresh and hot to their patrons.

You want a burger and fries? Sure! Footlong with everything? On its way, sir. Need coffee with extra cream? Here it comes.

The food was good and footfalls were high. The entire team loved their job and did their best to stick to the process because it was so efficient. It abstracted away the underlying complexity of preparing a meal with all its customisations into a simple, mechanical task, while still retaining all necessary details that the kitchen staff would need to build an order.

In the years that followed, Daryl was on his way to become an accomplished software developer of some fame. It was during this period that he learned about design patterns in software engineering and came across the command pattern. In his mind, he could relate immediately.

A command is a reified method call. – Bob Nystrom, Game Programming Patterns

I find Bob‘s explanation to be much more relatable than the longer definition defined in the GOF book. There’s a beauty in its terseness. To understand it, of course you need to understand what reified means. To borrow another quote from Bob‘s book

“Reify” comes from the Latin “res”, for “thing”, with the English suffix “–fy”. So it basically means “thingify”, which, honestly, would be a more fun word to use.

So there we are. The command pattern converts an abstract item like a deli order into a real, fresh, piping hot meal. I‘m sure even reading about this makes you hungry. Maybe you would like to repeat the experience right about now, and issue a command to your local delivery joint for a large pizza with Coke. Go ahead. I‘ll wait.

Are you back? Let‘s continue.

Returning to the task at hand, we are now at a stage in the logging operation where the message is to be dispatched to the socket server process. The Flex framework already provides all the necessary structured information in an event handler – the logEvent method – that is overridden by the SocketTarget class. It is a matter of sending this information to the external process, so that it can be logged to disk. Reify the log, if you please. We need some infrastructure in order to implement this mechanism.

A Standard for Commands

The invention of the assembly line provided a massive boost to human progress during the industrial revolution. It was a break from the previous practice of having few master-craftsmen assembling a product from start to finish. By delegating each part of the assembly to a single individual, the human skill required was greatly diminished and productivity soared. Rather than having one exceptionally good worker build a single sword in a day, factories were able to assemble dozens by assigning several average-skilled workers, each handling only one aspect of the assembly process. All workers just followed one instruction – assemble the product. But what each did in response to this instruction was different. Somewhat akin to what we do with the ICommand interface.

This interface unifies all commands so that they can be guaranteed to have a single method for execution. The ActionScript implementation looks like this.

public interface ICommand
{
    function execute():ByteArray;
}

The obvious follow up is why have a command interface at all when the only operation we need is to trace messages. However, it’s a small leap from where we are now (sending plain-text messages for printing) into communicating more elaborate commands such as enabling and disabling logging, force-flushing the log to disk, clearing the log or sending other structured diagnostic information such as internal data structures. It becomes easier to swap out one command for another, much like the assembly line, if they all must adhere to a common interface. All these commands can be triggered from the Flash application by instantiating an appropriate command class instance, serialising it, and dispatching the result over the connection.

The details of the execution of the command are specific to the command. The common operation is serialisation of the message from a Flash object to something that the server can read. For this, we use a byte-array because it is compact and efficient to send over a socket.

Trace generates a certain kind of layout in the byte array, which contains the string to be traced in the message log. Another possible message might be to toggle the state of the logging operation itself. In this case, the byte array could only require a Boolean value to indicate the toggle state. A more complex diagnostic message might send across complete object instances after serialisation, along with information on how they are to be deserialised again.

While message specifics are different, they all share a common structure called the message header. The header in the current version of this API requires the following elements.

  1. Message length (32-bit integer) – The total length of the message in bytes (including the header and all parameters).
  2. Instruction (byte) – An 8-bit integer value that contains the instruction code. Each command has a unique instruction number associated with it. This makes the message more compact than sending the human-readable command name as a string.
  3. Message timestamp in UTC (32-bit integer) – The date and time that the message was created in the Flash Player, encoded as seconds since the UNIX epoch. The time is calculated relative to UTC and must be converted into local time as an additional step by the receiver of the message, if needed.
  4. Number of parameters (32-bit integer) – A count of the number of parameters attached to the message.

The instruction for the Trace command is assigned the value 0├ù02. The byte array needed to trace the string “Hello” at severity level INFO is shown in the table below. Each cell represents 1 byte.

Message Length (4 bytes)
0×000×000×000×20 
Instruction (1 byte)
0×02 
Timestamp (4 bytes)
0×570×CD0×AC0×31 
Parameter Count (4 bytes)
0×000×000×000×03 
String Length (2 bytes)
0×000×04 
Severity Level (“INFO”, variable-length string)
0×490×4e0×460×4f 
String Length (2 bytes)
0×000×04 
Category (“Main”, variable-length string)
0×4d0×610×690×6e 
String Length (2 bytes)
0×000×05 
Message (“Hello”, variable-length string)
0×480×650×6c0×6c0×6f

The first 4 bytes contain the message length. The next 1 byte contains the instruction code (0×02). Four bytes are allocated to sending the timestamp in seconds (1,473,096,753 seconds since 1 January 1970). The next 4 bytes contain the number of parameters attached to this message (3). The contents of the rest of the message are specific to the Trace command. It is made up of 3 data fragments that encode a string prefixed by its length as a 16-bit integer. A string is an array of characters. C-style strings mark the end of the array by placing a null character in the last position of the array. When a piece of code needs to perform any string operation, it walks the length of the array until it arrives at the null terminating character. Alternative to this are length-prefixed strings, or Pascal strings, which prefix the length of the character array at the beginning. Pascal strings do not require a null terminating character as the length of the string is already known beforehand.

This kind of data structure has an advantage of speed over null-terminated strings. Any operation that requires the length of the string can peek into the beginning of the sequence, making it a constant time operation. Finding the length of null terminated strings, on the other hand, is a linear operation because it requires walking the entire byte array to locate the null terminator. Longer strings take more time, shorter strings take less.

The writeUTF method of the ActionScript ByteArray class uses Pascal strings. Programmers do not have a choice in this matter. Therefore, all commands, present as well as new ones in the future, use this same structure to encode strings.

A Pregnant Pause

Once the message has been serialised into a byte array, the send method of the Socket class is used to dispatch the message over the network.

At this point, the message is out of the realm of the Flash Player and is crossing boundaries into the .NET runtime. If the server at the other end receives the message in full (which is more or less guaranteed due to the TCP stack), it can be parsed, deserialised and acted upon by the server. If the message fails for any reason, the Socket class raises an error event within the Flash Player for the programmer to handle. For brevity, we ignore that aspect and proceed with the assumption that the message has been received successfully and in full. Transparent to the ActionScript programmer, the server dispatches an ACK response to acknowledge receipt of the message. There is nothing more that the Flash Player has to after this point and it can return back to its steady state.

Keep watching this space for part two of this article that explores receiving the message on the server, interpreting it into its component parts, then acting upon the instruction contained in it.