Sharing Code – Static and Dynamic Libraries in ActionScript

When I was in school, practically nobody had access to the internet. As a result, every student would have two essential items in his toolkit – an encyclopedia and a membership to a library. Homework, projects and supplementary studies were highly dependent on both of them.

Encyclopedias ranged from simple one-book units that specialized in a single subject, to multi-volume tomes spanning practically every topic imaginable (or at least deemed allowably imaginable by its publishers) by a school student. In both cases, the research was already done by someone else. When we were assigned a project on the solar system, nobody expected us to discover the planets in it. The planets remained discovered. All we had to do was read about them and share the information when making a presentation to the class.

Code Libraries

It is heartening to know that somebody creating computer languages took this to heart and invented the concept of code libraries – units of code written by people who are really good in the domain, then shared with the also rans who just wanted to implement their business applications without knowing the mathematics of relational databases or the bit-juggling that network libraries perform.

Libraries are compiled separately from the application that ends up eventually using them. They are linked to the application through a process that maps function calls in the application code with function addresses in the library. This process, predictably, is called linking.

Code stored in statically linked libraries is copied into the application executable at compile time, resulting an individual copy being created for every application that uses the library. Static libraries become an integral part of the application that uses them and cannot be shared with other applications. If the library is modified in any manner, the application must be recompiled and relinked with the new version in order to utilize those changes.

Dynamic libraries are stored in a shared location, and are linked to the application at runtime by the operating system or other environment controller such as a virtual machine. The metaphor falls apart a bit when it comes to sharing dynamic libraries – in a physical library, only one member can borrow a book at a time, whereas any number of programs can concurrently use the code stored in a dynamic library.

With static linking, it is enough to include those parts of the library that are directly and indirectly referenced by the target executable (or target library). With dynamic libraries, the entire library is loaded, as it is not known in advance which functions will be invoked by applications. Whether this advantage is significant in practice depends on the structure of the library.

Other than the obvious benefit of being able to compile units of code separately, either type of libraries offer their own individual benefits also. Statically linked code guarantees that all required code units are present and compatible with the application. Dynamically linked libraries may be of a different version than what the application requires, or not be present at all. Either case either causes a runtime error, or requires defensive code and reduced functionality in the application. Static linking also simplifies product distribution by reducing the number of files to be shipped and installed.

All said and done, both types of libraries are popular and well-worn concepts in computer programming. Many modern languages support either method, usually both.

Code Libraries in the Flash Ecosystem

Adobe’s MXML compiler offers several parameters for programmers to employ libraries – both static and dynamic – in their code.

Static linking is almost identical to how it is used in conventional languages. Dynamic linking works slightly differently from Windows’ Dynamically Linked Libraries and Unix’s Shared Objects due to the browser-based operation of the Flash Player. But these differences are at an implementation level only. The concepts remain the same.

Static Linking

To statically link a library into an application, the compiler offers the library-path and include-libraries directives.

library-path

When a library is specified using the library-path directive, the compiler includes only those assets and classes that are referenced in the application. For example, if the Math library contains IntegerArithmetic and FloatArithmetic for performing arithmetic operations on two separate numeric data types, but the client application only uses integers, the FloatArithmetic class is excluded from the output. This reduces the file size of the application SWF.

mxmlc Main.mxml -output=Main.swf -library-path=math.swc
include-libraries

The include-libraries directive packages the entire library, irrespective of what the compiler thinks is used in the application. This comes in handy in a dynamic language like ActionScript because all method calls do not necessarily get tested for linkages by the compiler.

var classRef:Class = getDefinitionByName("com.notadesigner.math.FloatArithmetic") as Class;
var instance:Object = new classRef();
instance["add"](10.5, 2.5); // Linkage not tested by the compiler

The include-libraries directive is used like this.

mxmlc Main.mxml -output=Main.swf -include-libraries=math.swc
static-link-runtime-shared-libraries

This directive is a convenient shortcut to convert runtime shared libraries into static libraries without significant changes to the compiler configuration files. Simply setting its value to true causes the compiler to embed all RSLs into the application. This is a handy way to investigate library-related problems when debugging the application.

mxml Main.mxml -output=Main.swf -static-link-runtime-shared-libraries=true

Dynamic Linking

A Runtime Shared Library (commonly abbreviated to RSL) is loaded by the application before it begins execution. Loading a RSL is a complicated task if done in plain ActionScript, but is taken care of automatically if the application builds on the Spark or MX Application class.

Adobe-provided framework libraries are the most obvious use case for using RSLs. All Flex-based applications depend upon these files. By caching them after the first time they are downloaded, future applications can be started much faster as they do not need to download the same code again. Custom libraries can also take advantage of the same technique.

Flash libraries are compiled using the compc utility, that ships as part of the Flex SDK. It generates a SWC file which is a compressed archive containing a SWF (named library.swf) and an XML (catalog.xml). To use this library, the developer must manually extract the SWF from the SWC using an archival utility (such as PKZip) and place it where the application can download it at runtime. As a good practice, the SWF is also usually renamed from library.swf to something more meaningful.

runtime-shared-library-path

This directive is used to specify the location of RSL files for the compiler. The compiler requires the names of both, the SWC as well as the extracted SWF, separated by a comma.

mxmlc -o=main.swf -runtime-shared-library-path=libs/math.swc,bin/math.swf Main.mxml

Related Directives

The Flex compiler provides two other directives to externalize the application’s assets and code fragments. The compiler tests linkages against these assets at compile-time, but leaves them out of the application binary. Libraries that contain these assets or classes are required at runtime, and the Flash Player throws a runtime error if they are not available.

These directives are useful when creating modules which are loaded dynamically into an application that they share code with. The application is linked to the requisite RSL, and the module does not need to fetch it again. However, the compiler still needs to test the linkages against the symbols – either against the original source code or a compiled binary. These directives assist in that task.

external-library-path

The compiler uses SWC files specified at these paths to test linkages with the application code, but does not compile the binaries into the application itself.

externs

This directive points to source files containing assets or classes which will be available at runtime. The compiler uses the source files for link testing, but does not compile them into the application binary.

A Spreadsheet of Posts for WordPress

When Microsoft was working on Excel during the early nineteen nineties, their research indicated that many people did not use spreadsheets for the mathematical tasks (such as financial planning, bookkeeping or simulations) which were the original goals of the spreadsheet genre. Instead, they were used for making lists – grocery shopping, planning parties for their kids, logging project tasks, so on. Microsoft took this research into account and reoriented the functional specifications to make list-making much easier than the competition and previous versions of their own product. Joel Spolsky, who was program manager for Microsoft Excel during this period, states the following.

When we were designing Excel 5.0, the first major release to use serious activity-based planning, we only had to watch about five customers using the product before we realized that an enormous number of people just use Excel to keep lists. They are not entering any formulas or doing any calculation at all! We hadn’t even considered this before. Keeping lists turned out to be far more popular than any other activity with Excel. And this led us to invent a whole slew of features that make it easier to keep lists: easier sorting, automatic data entry, the AutoFilter feature which helps you see a slice of your list, and multi-user features which let several people work on the same list at the same time while Excel automatically reconciles everything.

The Process of Designing a Product, Joel on Software

If you abstract away the specifics of the application, you can easily see that the spreadsheet grid is a one-table database. Having multiple tables can be much more efficient, but a single table is easier to understand for people who do not use databases regularly.

The simplicity of spreadsheets as databases goes beyond just reading.

Adding columns? A database engine needs, at the least, the column name and its data type. In a spreadsheet all you need to do is place the cursor over the first empty cell in the first row and type its name. Filtering is one of the simpler tasks in a database, but spreadsheets even make that easier by providing a dropdown of valid values to choose from. Even inserting new records is much easier in a spreadsheet as compared to a database engine. And more importantly, the grid is a good way of capturing an aggregate view of the entire database and making wholesale changes to groups of records quickly.

A spreadsheet application can be the subject of some really grimy IT horror stories that can involve file shares, multiple users and overwritten records. But if put into a proper data validation framework, the spreadsheet interface is robust and easy to use. Many database management clients use the it to represent their table interface, even for multiple relationships.

Extending to multiple dimensions comes at the cost of some loss of elegance when representing one-to-many relationships. While this UI works, it likely marks the limits of a spreadsheet interface. Nested relationships quickly become difficult to understand. And each nested level can represent only one relationship. It comes as no surprise then that so many database-oriented applications (not the management clients themselves) eschew the spreadsheet interface in favour of a form-driven approach.

But I still think that the spreadsheet interface is vastly underused on the web. As I have mentioned above, it does work for simpler collections of records, such as articles in a content management system or user lists.

Spreadsheet of Posts is a WordPress plugin that aggregates all posts into a spreadsheet interface. While WordPress is a fairly simple to use product for even laypersons, the Post creation process leaves a bit to be desired. The sheer amount of shuffling back and forth between the All Posts and the Edit Posts screen takes away a lot of time. This is similar to the REP loop that interpreted languages provide. The visual difference between two screens is bad enough. To that, the delay caused by network activity, fetching the same data repeatedly from the database, regenerating almost identical markup each time and then rendering it again on the client side increases the effort of getting into the flow. Any boredom while performing such a task is justified.

Spreadsheet of Posts attempts to address these shortcomings by putting all the posts into a grid. Edits are made in-place on the grid itself. New records are inserted by filling in a blank row. Records are deleted by selecting any cell and hitting delete. The record that corresponds to the selected row is deleted. The plugin uses standard page-based navigation to cycle through records that do not fit into a single page. It also provides an alternative to display all the records in a single page. Cell heights can be varied to fit the content, or be set to a fixed constant.

The underlying grid is the Hands on Table jQuery grid editor. While there are more functionally complete alternatives, the interactions and appearance of Hands on Table come closest to replicating Excel. Even the bare bones demo on their home page evokes a lot of familiarity to Microsoft’s product. This is a big necessity to make users more comfortable with Spreadsheet of Posts. The rest of the back end of the plugin uses the standard WordPress framework.

Spreadsheet of Posts is still work in development. A current version can be downloaded from here.

Objective-C Primer for C# Developers

A Different C with Classes

Objective-C is a different take at an object oriented implementation of C, and a rather elegant one at that. The language supports all the principles of the paradigm – inheritance, encapsulation and polymorphism. It is a strict superset of C, which is a fancy way of saying that all C code is already valid Objective-C code, and C code can be freely interspersed within an Objective-C program (and yes, you also have to deal with pointers). Objective-C compilers can compile code from both languages without trouble. While the language is staple among developers using OS X and iOS, it is perfectly suited for general purpose programming as well. However, thinking in Objective-C requires getting used to its unique syntax and an eclectic model of programming that infuses Smalltalk-style messaging, C-style statements and modern OO constructs such as protocols, understanding the role of the language runtime, and getting your head around slightly different terminology.

And since large Objective-C applications are typically written for Apple’s ecosystem, being able to converse in Cocoa is not half bad a thought. This primer assumes you already know terminology such as classes, objects and methods. With that in mind, we move on to introducing the Objective-C syntax for writing class-based code.

Classes and Instances

A class is split into two files – a header and an implementation. Let’s begin with a Shape class that we will flesh out and use through the rest of this document.

// Shape.h
@interface Shape

@end

This file declares the public interface of the Shape class. The language loves its ‘@’ symbols, so get used to them. You’ll be using them more often than you think (just one of the eccentricities of the language). The implementation is stored in Shape.m and is written as follows.

// Shape.m
#import "Shape.h"

@implementation Shape

@end

This is very similar to how one might structure files in C.

You need to instantiate an object in order to do anything with it. However, the language does not have traditional constructors like in C#. Instead, the base NSObject class implements two separate methods for object allocation and initialization – alloc and init.

Shape *s = [[Shape alloc] init];

Note: Separating the interface from the implementation might seem like a lot of effort, but it is one of the traits that Objective-C inherits from C. The advantages and disadvantages of this approach have been debated in many texts and discussion forums, which I encourage you to read. They are interesting in their own right and provide a valuable background to getting under the skin of the language.

This statement allocates memory for an instance of the Shape class and initializes the object. It can also be simplified into a single message.

Shape *s = [Shape new];

In both the above examples, alloc and new are class methods (also known as static methods). The init method is also implemented by the base class, but it is an instance method. Classes can override or implement their own versions of initializers.

A look into the past

The history of this two-step construction can be traced back to the days of NeXTSTEP, when the language was still in its infancy. The tight memory constraints of the hardware at that time often necessitated memory pooling. By separating allocation from initialization, programmers were able to reuse preinstantiated objects after reinitializing them. The practice continues today because it leaves programmers free to create custom initializers for their classes while gaining the benefits of a pre-written, generic and performant allocation method.

New allocation methods are seldom created because the existing methods meet almost every need. However, one or more new initializers are created for almost every class. Due to the separation of allocation and initialization stages, initializer implementations only have to deal with the variables of new instances and can completely ignore the issues surrounding allocation.The separation simplifies the process of writing initializers. – Erik M. Buck and Donald A. Yacktman, Cocoa Design Patterns

Messages

Procedural code gets information then makes decisions. Object-oriented code tells objects to do things. – Alec Sharp

Sending messages to objects imbibes the philosophy of tell, don’t ask as championed by Sharp. A message in Objective-C is identified by the enclosing brackets ([ and ]) around the message name and the receiver. Messages are sent by clients to instances or classes. Objects contain methods to handle those messages. Messages have a method type – either instance or class (denoted by the – and + symbols, respectively). Message signatures must declare a return type (or void if they return nothing), and the types of all parameters.

The syntax of a method declaration

All messages are declared in the class interface. The definitions are stored in the implementation.

// Shape.h
@interface Shape

- (void)scaleX:(double)x Y:(double)y;

- (void)rotate:(double)radians;

- (void)translateX:(double)x Y:(double)y;

@end
// Shape.m
#import "Shape.h"

@implementation Shape

- (void)scaleX(double)x Y:(double)y {
    // Scale this object
}

- (void)rotate:(double)radians {
    // Rotate this object
}

- (double)translateX:(double)x Y:(double)y {
  // Translate this object
}

@end

Finally, the object is instantiated and called upon by a client class.

#import "Shape.h"

...
Shape *rect = [[Shape alloc] init];
[rect translateX:20 Y:30];
...

Messages are invoked upon an object instance through the unique double square-bracketed syntax of the language. The first token is the name of the object, the second the name of the message being passed. Each subsequent token is separated by a colon and denotes a parameter to be passed to the message.

Dissecting Messages

Dynamic messaging is one of the primary enhancements of Objective-C over plain C. Rather than being bound statically at compile time, messages are resolved at runtime by the language runtime. The message itself is identified by a selector, which is a null-terminated string that contains the name of the method. The selector points to a C function pointer that implements the method. An Objective-C call…

[rect translateX:20 Y:30];

is compiled into…

objc_msgSend(rect, @selector(translateX:Y:), 20, 30);

While the internals of how a message is sent are not essential, some overview is useful when writing and debugging code.

In the example above, a Shape instance is initialized and its reference stored in the variable ‘rect’. It is then sent a message to move it 20 pixels on the X axis and 30 pixels on the Y axis. The message selector to effect the move is the string “translateX:Y:”. When the language runtime attempts to send the message to the object, it uses the entire string as the selector.

It is understandably easy to misinterpret the selector name to be a method name along with its named parameters. But it becomes clear once you read the objc_msgSend function call that Objective-C does not work this way.

A programmer can dispatch any message to an object. While the compiler will identify and warn of a potentially unsupported message, the program itself will compile. While this does seem error-prone, there is a method (heh heh) behind the madness.

Methods can be added or replaced on instances at runtime. The compiler cannot possibly identify which messages are going to be supported by an object when the program executes, due to which it allows sending messages which are not defined in the scope of the class interface.

When the program is executed, the runtime introspects the object to see if it can handle the message or not. If the object receives a message it cannot handle, the system will generate a runtime exception and your program will stop.

Declared Properties

Declared properties correspond to auto-implemented properties in C#. Unless explicitly overridden, the public interface to properties is automatically generated by the compiler.

// Shape.h
...
@interface Shape : NSObject
@property double width;
@property double height;
...
@end

This is the bare minimum that you need to write in order to implement properties in your class instance. The compiler automatically generates accessors and mutators for you. An accessor has the same name as the property name (width and height in this case) and the mutator is the property name capitalized and prefixed with the word ‘set’ (setWidth and setHeight).

// Shape.m
@implementation Shape
@synthesize width;
@synthesize height;
...
@end

To access the properties, clients can use the following syntax.

// Client.m
...
NSLog("width: %d, height: %d", [rect width], [rect height]);
[rect setWidth:30];
[rect setHeight: 22];
...

Properties can also be accessed through an alternative dot syntax.

// Client.m
...
rect.width = 20;
NSLog("height: %d", rect.height);
...

Property Attributes

Property declarations can be embellished in the interface with attributes in order to control how they work. There is no change required in the implementation.

// Shape.h
...
@property (readonly) double width;
...

The readonly attribute makes the property only viewable. The compiler flags any attempts to call setWidth as errors and stops the compilation process. While property attributes have many subtleties that must be thoroughly understood in order to master the feature, beginners can go with the most general guidelines.

Storage
  • Use assign for scalar properties (native numeric types, structs, enums).
  • Use retain for object types (NSString, NSNumber, etc.). Creates a new reference to the object instance and releases the old one.
  • Use copy for object types. Creates a new instance based on the properties of the old one. Releases the old instance.
  • Use strong for object types that increment reference counts. This is the recommended technique for objects at the top of a hierarchy to reference their child objects. This ensures that the child objects will not be cleared as long as the parent object exists.
  • Use the weak attribute for references to parent objects from child objects. If the parent object is destroyed, its reference in the child object is automatically cleared off and prevents memory leaks.
Mutability
  • The readonly attribute makes a property immutable. Outside classes cannot modify its value. The class itself also cannot make any changes through the property mutator (since there isn’t one), but can change the value of the underlying field directly.
  • The readwrite attribute makes a property mutable by outside classes by auto-generating the mutator and accessor methods.
Concurrency
  • Non-threadsafe code can get away with using nonatomic properties.
  • Use atomic for properties that must work in a multithreaded environment.
API
  • The getter attribute explicitly declares the name of the accessor method. Use this to override the default name of the accessor.
  • The setter attribute works similarly to declare the name of the mutator method.

Instance Variables

A field in C# corresponds to instance variables (or ivars) in Objective-C. An instance variable exists throughout the lifetime of the object and is accessible within the scope of the objects methods – public and private. Outside classes cannot access an ivar directly.

// Shape.h
@interface Shape : NSObject {
  int _width;
  int _height;
}
...
@end

The compiler can automatically synthesize ivars for properties. The auto-generated variable has the same name as the property, prefixed by an underscore (_). This can be overridden in the implementation file using the @synthesize statement to link them to explicitly declared variables.

// Shape.m
#import "Shape.h"

@implementation Shape @synthesize width = myWidth; ... @end

Protocols

Protocols correspond to interfaces in C#. They are header files which declare a list of method signatures. Developers can declare that a class implements those methods in the header file. The compiler checks this and flags any classes that do not implement those methods.

Classes that implement all methods declared in a protocol fully are said to conform to it.

// FilledShape.h
@protocol FilledShape

- (void)setFill(Fill *)fill;

- (void)clearFill;

@end

The Shape class can declare that it conforms to the FilledShape protocol by following its class name with the name of the protocol.

// Shape.h
#import "FilledShape.h"

@interface Shape : NSObject <FilledShape> ... @end

Classes can implement as many protocols as required. Each protocol name should be separated by a comma within the two angled brackets (<>).

// Shape.h
#import "FilledShape.h"
#import "OutlinedShape.h"

@interface Shape : NSObject <FilledShape, OutlinedShape>
...
@end

Objective-C protocols offer the option of declaring required and optional methods. This makes it possible to write classes that implement only some, but not all methods of a certain interface. While this again does seem like a code smell to many programmers, it does come in handy given the dynamic nature of Objective-C.

All methods declared in a protocol are public. Protocols cannot define private methods.

In Closing

Like many other languages, the syntax and many features of Objective-C are fairly easy to grasp. Apple’s excellent implementation of the Foundation Framework, UIKit and Cocoa frameworks make it easy even for novices to write significant applications without much effort. But like everything else, true mastery comes only with practice and an understanding of the underlying runtime that powers the language.

Additionally, while OOP is great for increasing productivity, developers must also take time out to grasp the C underpinnings that form the foundation of Objective-C. This knowledge not only makes for a well-rounded education of the language, but also opens up the ability to harness the raw power of C when necessary, which is an important benefit of Objective-C.

WPF Game of Life

I was introduced to cellular automatons a good decade ago through books written by Peter Small. Back then, we were using Adobe (then Macromedia) Director as our primary development platform, where object-oriented programming was still a bit of a novelty. Small’s writings explained OOP using artificial life forms such as cellular automatons, with Conway’s Game of Life being an oft used concrete example. I was hooked and would spend hours running patterns on a simple implementation of the game that shipped with Windows Entertainment Pack.

But I never got around to implementing the application myself until now. The game has a fairly simple model that does not take much effort to build. This is handy when learning a new platform or language, leaves the programmer free to explore the features of the framework instead of spending cycles trying to nail down the business logic correctly using an unfamiliar language syntax.

Background

There are plenty of resources available online that describe, implement and demonstrate this game. The basic essence of the game is a two-dimensional array of cells and an endless loop that iterates over these cells to update their state depending upon some simple rules.

  1. Any live cell with fewer than two live neighbours dies, as if caused by under-population.
  2. Any live cell with two or three live neighbours lives on to the next generation.
  3. Any live cell with more than three live neighbours dies, as if by overcrowding.
  4. Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.

This implementation of the game also consists of the following features for convenience.

  1. Clicking on a cell toggles its state between being alive or dead.
  2. A Randomize button initializes the board by randomly setting the state of all cells to either alive or dead.
  3. A Stop button lets the user stop the cell update iterations in order to observe the arrangement of the board at any given time. This is useful for times when an interesting pattern appears on the screen that seeks further observation.
  4. A Next button complements the Stop button to let the user iterate to progressive generations of the board, one step at a time.

Implementation

This implementation is made up of the following classes.

MainWindow.xaml and MainWindow.xaml.cs

The application window is a XAML class called MainWindow.xaml, which defines the layout of the application. The layout is built around a DockPanel that divides the screen into two – a controller toolbar and the board view.

<DockPanel Name="layout">
    <ToolBar DockPanel.Dock="Top">
        <Button Content="Start" Name="btnStart" Height="23" Width="75" Margin="5" Click="toggleStart_Click" />
        <Button Content="Next" Name="btnNext" Height="23" Width="75" Margin="5" Click="nextIteration_Click" />
        <Button Content="Clear" Name="btnClear" Height="23" Width="75" Margin="5" Click="clear_Click" />
        <Button Content="Randomize" Name="btnRandomize" Height="23" Width="75" Margin="5" Click="randomize_Click" />
    </ToolBar>
    <ScrollViewer HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
        <life:BoardView x:Name="view" DockPanel.Dock="Top" Margin="10" Click="view_Click"></life:BoardView>
    </ScrollViewer>
</DockPanel>

The MainWindow class stores a reference to an instance of BoardModel as a private field. Buttons in the toolbar are wired to trigger event handlers in the MainWindow class, which in turn trigger public methods exposed by the model and view instances.

BoardModel.cs

The model class is where the business logic behind the application is implemented. It contains two arrays of bytes of identical length, which store the state of the board in the current iteration and the next iteration. It also initializes a timer that is used to iterate over the board state automatically. In addition, it exposes public methods to control the state of the board – Next(), Start(), Stop(), Clear() and Randomize().

The model instance dispatches an Update event every time the board changes. The window class listens for this event and passes on the contents of the new board cells to the Update() method of the view instance.

BoardView.cs

The view class inherits from System.Windows.FrameworkElement in order to take advantage of its built-in layout functionality. The board is drawn using low-level Visual elements. While it is easier to implement the cell drawing by using Drawings or Shapes, it also adds a lot of overhead for unnecessary features such as styles, data binding, automatic layout and input events. DrawingVisuals provide a much more performant way of drawing large numbers of objects on the screen.

private void DrawCells()
{
    if (null == this.values)
    {
        return;
    }

    using (DrawingContext dc = this.cells.RenderOpen())
    {
        int x = 0;
        int y = 0;
        Rect rect = new Rect(OUTLINE_WIDTH, OUTLINE_WIDTH, Constants.CELL_SIZE - OUTLINE_WIDTH, Constants.CELL_SIZE - OUTLINE_WIDTH);

        for (int i = 0; i &amp;lt; values.Length; i++)
        {
            x = (i % Constants.CELLS_X);
            y = (i / Constants.CELLS_X);
            rect.Location = new Point((x * Constants.CELL_SIZE) + OUTLINE_WIDTH, (y * Constants.CELL_SIZE) + OUTLINE_WIDTH);

            if (1 == values[i])
            {
                dc.DrawRectangle(Brushes.Red, null, rect);
            }
        }
    }
}

One must fetch a reference to a DrawingContext in order to draw content onto a DrawingVisual. This is done through the RenderOpen() method of the DrawingVisual. Since we are only drawing basic rectangles, we can use the in-built DrawRectangle() method of the DrawingContext class to draw this shape for us. Internally, this method still uses a GeometryDrawing and a subclass of the Geometry class, but abstracts away those details for convenience.

The drawing is displayed on the screen by adding the Visual instances to the visual tree of the BoardView class, which is done in its constructor.

public BoardView()
    : base()
{
    this.AddVisualChild(this.grid);
    this.AddLogicalChild(this.grid);

    this.AddVisualChild(this.cells);
    this.AddLogicalChild(this.cells);

    this.visuals = new DrawingVisual[] { this.grid, this.cells };

    this.drawGrid();
    this.drawCells();
}

Additionally, the BoardView class also overrides the VisualChildrenCount, GetVisualChild and MeasureOverride members of the FrameworkElement class.

protected override int VisualChildrenCount
{
    get
    {
        return this.visuals.Length;
    }
}

protected override Visual GetVisualChild(int index)
{
    if (index < 0 || index > this.visuals.Length)
    {
        throw new ArgumentOutOfRangeException("index");
    }

    return this.visuals[index];
}

protected override Size MeasureOverride(Size availableSize)
{
    return new Size(Constants.CELLS_X * Constants.CELL_SIZE, Constants.CELLS_Y * Constants.CELL_SIZE);
}

The BoardView class instance also dispatches an event when the user clicks on a cell on the board. This is in turn passed over to the model instance via the window, causing the model to toggle the state of the cell that was clicked.

ClickEventArgs.cs

An instance of this class is passed as a parameter along with the Click event is dispatched from the BoardView class. It exposes two parameters to identify the X and Y coordinates of the cell which was clicked upon, relative to the board.

The Visual Studio solution for this project can be downloaded from here as a ZIP archive.

Storing Values with Bit Packing and Unpacking

Bit packing and unpacking is a handy way of consolidating multiple data values into a single variable, thus compressing the amount of data being stored or transmitted. The number of values that can be stored depends upon the width of the data to be stored as well as the type of the value that it is packed into. A simple byte can store up to 8 bits of data. Larger types such as ints can store up to 16, 32 or 64 bits. This is an especially efficient technique for storing several small-width values, often smaller than the smallest width supported by a platform (such as byte or boolean flags) into a single large value such as a 32-bit integer.

Bit flags are commonly used for implementing low-level features, such as storing file access-permissions or packing values into a single value before transmitting across a bus. However, they can be applied with equal ease to higher level tasks such as storing user preferences or choosing which widgets to display from an enumerated list. We will see here how to use bit flags to store font formatting preferences, and apply them later to a label.

Bitwise Operators

There are a couple of operators we need to understand before we can move on to the implementation. Bitwise operators, by definition, work on individual bits inside a value. Since they are implemented directly by the processor itself, they are much faster than arithmetic operators such as division and multiplication. We will use bitwise AND (&), bitwise OR (|) and left shifts (<<) in this exercise.

A bitwise AND operation takes the binary representations of two values and performs a logical AND operation on each bit. The result is 1 in every position where both the bits are 1, and 0 if either or both bits are 0.

    001010
AND 011011
    ------
    001010

Bitwise OR on the other hand, compares two bits in corresponding positions, and sets the result to 1 if either of them is 1, or to 0 if both of them are 0.

    001010
OR  011011
    ------
    011011

Bitwise left shift operator moves individual bits within a single value by the number of places specified in the second operand. The value is padded with 0s on the right, and the left-most bits are dropped off.

    001010 << 1 = 010100

Implementation

We set up a simple Windows Forms project and draw three checkboxes and one label on the form. The aim is to have the checkboxes control three font properties of the label – weight, style and underlining. All checkboxes are given appropriate labels and configured to execute the _changeFormatting method of the form every time the CheckStateChanged event is fired. The code for this method is shown below.

private void ChangeFormatting(object sender, EventArgs e)
{
    byte flags = 0;

    flags = (byte)(
        Convert.ToByte(this.chkUnderline.Checked) << 2 |
        Convert.ToByte(this.chkItalic.Checked) << 1 |
        Convert.ToByte(this.chkBold.Checked)
        );

    Font f = new Font(this.label1.Font.FontFamily, this.label1.Font.Size, (FontStyle)(
        (flags & (byte)FontStyle.Underline) |
        (flags & (byte)FontStyle.Italic) |
        (flags & (byte)FontStyle.Bold)
        ));

    this.label1.Font = f;
}

Packing

In the first statement, the flags variable is populated with the values of each checkbox. We want to store the three flags in the last three bits of a single byte.

PositionSetting
7Unused
6Unused
5Unused
4Unused
3Unused
2Underline
1Italic
0Bold

In order to do so, we take the value of each boolean (either true or false), convert it into a byte, then shift it by an appropriate number of positions. The value of the underline flag is to be stored in the 2nd bit (starting from 0). So we left-shift its value by 2. Similarly, the italic flag is stored in the 1st position, so its boolean value is shifted by 1. The value of the bold flag does not need to be shifted at all.

    00000001 << 2 = 00000100 // Underline
    00000001 << 1 = 00000010 // Italic
    00000001                 // Bold (no shifting required)

A consolidated value can be generated by ORing the three values together.

    00000100
 OR 00000010
 OR 00000001
    --------
    00000111 // Decimal value 7
    00000000
 OR 00000010
 OR 00000001
    --------
    00000011 // Decimal value 3
    00000100
 OR 00000000
 OR 00000001
    --------
    00000101 // Decimal value 5

The decimal value can then be stored in a database or other persistent storage system as an integer or byte. This is better than having to store three boolean fields. This information can transmitted across systems too as a packed unit, to be unpacked later only when the preferences have to be applied to a display element.

In our example, we are unpacking and applying the values immediately for brevity. But a more practical situation would probably involve serializing the value somewhere, then deserializing and applying the font properties later at another location.

Unpacking

In order to apply the font styles on a display element, the individual values of each style parameter must be extracted from the packed value and then applied. The .NET framework defines enumerations for each of these style parameters in the System.Drawing.FontStyle enum. The values for each style parameter are listed below.

SettingDecimal ValueBinary Value
Regular000000000
Bold100000001
Italic200000010
Underline400000100

You will notice that each enumeration is double the value of its predecessor, hence moving the digit 1 by one position leftwards with every increase. This is a key feature of bit flags. Each element differs from the others only in the position of the 1 bit. Thus, the value of a given flag can be extracted from the packed value by ANDing the packed value with the value of the enumeration.

     00000111 // Packed value decimal 7
AND  00000100 // Underline enum decimal 4
     --------
     00000100 // Result - show underlines

This operations shows that the value of the underline flag is true. If the packed value was the decimal 3 instead of 7, then the operation would play out as shown below, resulting in the value 0 for the underline flag.

     00000011 // Packed value
AND  00000100 // Underline enum
     --------
     00000010 // Result - hide underlines

All that is needed then is to convert the result byte into a boolean and apply it wherever required. In our example above, the constructor of the Font class requires the values packed together any way as a FontStyle enum. To do this, each bit is ANDed with its corresponding enum, then all of them are combined together again using an OR operation. The resultant byte is cast into a FontStyle before being passed to the constructor.