Yesterday we saw the Strategy Pattern. Today I want to talk about the Observer Pattern.

I got a bit of a mixed feeling about this pattern, since in the .NET world, we got events and delegates making this pattern somewhat unneeded.

However, it's good to know how it works, since it's used behind the scenes in the .NET CLR when working with events. Besides, better know too much than too little, knowledge is power.

Also, I'm planning to write a separate post after this to go into the C# specific implementation anyway.

First, the definition again: "Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically."

Let's continue with our example from yesterday, were we made an object model to describe some game characters. The next requirement came in, and we need to display movement of our units on the screen.

Initially, we are given one screen, a big overview of a battle map, where all units are displayed on and move around on.

An easy quick approach would be to simply add some coordinates information to our GameUnit class and add in a Move() method which gets called whenever the unit moves.

This Move() method would then simply call our BattleMapDisplay class to inform it of its new location.

Quick Hacky Notification

That would work, for now... But what if we want to add in a different type of display?

Let's say we want to add in a OverviewDisplay as our main view. Then we have to go and change our GameUnit class to inform this screen as well. Bad. Let's fix this up a little.

If we look at it from a higher level again, all our displays are doing is observing our game units and acting upon any change in them. So, one display is actually an Observer of our GameUnit, the Subject. And there we have it, our displays have a one-to-many relation with a GameUnit and want to be notified when it changes it state, the Observer Pattern's exact definition. :)

Remember from last time? Program to an interface, not an implementation.

When we set up a system to let objects communicate state changes to each other, the only thing these objects should know about each other is a common communication interface. Let's create that one by adding two additional interfaces, IObserver and ISubject.

Notification Interfaces

Now that we have our new interfaces, we can change the GameUnit class to hold a collection of IObserver objects. Together with providing two methods for additional observers to subscribe themselves so they can get notifications when the GameUnit changes.

By implementing it this way, we can easily add new displays or other objects to our application, which can easily stay informed about our units as long as they implement the IObserver interface and subscribe themselves with the units.

The GameUnit doesn't care about which kind of object is on the receiving end of the notification, and so won't have to be changed whenever an new Observer is added. The Observer however will have to make checks in its Update() method to determine which ISubject is being returned.

Observer Pattern

Whenever a GameUnit moves right now, it informs all screens about this, passing itself along so the observers can get information out of the object.

And that's it really, the Observer Pattern isn't all that hard, it's a simple notification mechanism. In a next post I'll talk more about delegates and events to have a look on how the Observer Pattern is implemented in the CLR.

If you have any questions about this pattern, please leave them in the comments, something you want to know, something I overlooked or was unclear about, just ask, it's from having a dialog we learn the most.

As usual, I uploaded the solution I used for this post so you have a detailed look at the code used.

Some additional information on the Observer pattern:

 

The first pattern I want to talk about is the Strategy pattern, which always reminds me about the Command & Conquer games so I'll simply use it as an example :)

First of all, the definition: "Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it."

I'm bad at remembering definitions or trying to imagine what they really mean, so let's just go ahead and try to create something and learn as we go, eventually we'll end up implementing the Strategy pattern and you'll 'get it' for the rest of your life, without a definition.

A long time ago, we made a simple strategy game, having only 2 units, a soldier and a tank, both were able to shoot at each other which we implemented as follows:

Simple Class Model

The Shoot() logic is contained in the base GameUnit class, since it's identical for both units. Each unit takes care of drawing itself.

After a while, we receive a request to add in an Engineer, which is a unit used to take over buildings and more importantly, he can't shoot.

If we just added an Engineer class similar to the Soldier one, he would be able to shoot as well, which we don't want. We could for this once just override the Shoot() method for the Engineer and make it empty.

Hiding methods - Maintenance Hell

Can you already see where this is going to end up? Maintenance Nightmare!

Eventually we end up with lots of useless code being repeated for every class which has a different shooting logic, where you have to open up every class to figure out all the available implementations. Let's not implement it like this!

What if we were to get rid of the Shoot() logic in the GameUnit class and make an IShootable interface for the units that can actually shoot?

Interface - Code Duplication

That looks a bit cleaner, but wait! We simply shifted the nightmare, because now the Soldier and Tank have identically the same code in their Shoot() method. This isn't the solution either, let's take a look at what our higher level goal actually is.

We can see the part that changes is how a unit shoots. If we take a closer look at shooting and implementing future classes, it is very possible we'll end up with a class that has a very different shooting algorithm or has upgradeable parts, changing the way it shoots. You could say the way a unit shoots is a behaviour of a unit.

Remember the definition of the Strategy pattern? The shooting behaviour we have just defined is actually an algorithm, while the requirement of units being able to get upgraded implies the behaviours have to be changed at run time, making them interchangeable.

Making things interchangeable usually means having less things hard-coded in your application, which reminds of a great saying: Program to an 'interface', not an 'implementation'.

Let's separate all our shooting logic from our units and create a totally new set of classes defining all possible shooting behaviours.

Behaviour Set - Family of Algorithms

Now it's only a matter of letting our GameUnit use these behaviours. We'll do this by programming against the IShootingBehaviour interface instead of against an implementation. This way we can dynamically replace the behaviour at run time, and have a very flexible programming model towards the future.

Adding a new way of shooting is simply a matter of adding a new class implementing the IShootingBehaviour interface after which all our units could use it.

Strategy Pattern

And that's it! We've implemented the Strategy pattern. We defined a family of algorithms (IShootingBehaviour), we encapsulated each one (NormalShot, CantShoot, ThrowKnifes) and made them interchangeable (ShootingBehaviour property).

Each client can define his algorithm as we currently did in the constructor, by setting the property to the desired implementation. In a future pattern we'll see how to set this different, since it's not that pretty doing it in the constructor.

Note that even though we are setting a shooting implementation via the constructor, it is possible to change the way a unit shoots at runtime by setting the ShootingBehaviour property.

I've uploaded the sample project I have used while learning this pattern so you can have a look at the code representing the above diagrams yourself.

Some additional information on the Strategy pattern:

 

It's been a while again, real life issues managed to take over all time... But, I'm regaining ground and winning back some of it ;)

For the first time in years, I've managed to get around reading a real book again. Last week I picked up a copy of Head First Design Patterns and started on it yesterday. As far as I can tell, only read the first chapter so far, it's a great book!

It's not like a usual learning book, which tend to be pretty dull when it comes to formatting or the type of language used. This book reads like a great story, filled with images to clarify and explain concepts. The images aren't even optional, when you really want to learn, you have to read them to get the full picture.

As a form of learning, I plan to write a blog post about each pattern I finish, explaining it in my own words, so it 'sticks' a lot better for myself as well, helping others at the same time. Stay tuned!

 

In a previous article I have demonstrated how easy it is to decompile and reverse engineer .NET assemblies using Reflector and Reflexil. I've also shown that applying a strong name to your assembly does not protect your code from reverse engineering. So, what else is left?

A technique called obfuscating goes a long way in keeping your source code safe. An obfuscator will mangle your code, without changing the actual result, to make it increasingly harder for someone to decompile your code and actually understand it.

Keep in mind however that this is 'security through obscurity', and as such it does not provide solid security, it's just another layer. The more layers, the more walls there are around your assembly to demotivate others into breaking it, but never enough to demotivate 100% of the people. A similar tactic can be found in CD protection schemes, which stops a percentage of users from copying a disk, but not everyone.

There are several possibilities to obfuscate an assembly:

  • Renaming Classes, methods, parameters, namespaces, fields, ... are renamed to short names, making it much harder to deduct the working of a program from descriptive naming. Unicode characters can be used, making it even harder to understand.

    When there is a lot of code, an obfuscator can also rename different methods to the same name, due to taking advantage of overloading.

    For example, if you have a method GetCustomers without any parameters and GetCustomer(int customerNr), an obfuscator can rename them both to 'a', letting the .NET framework pick the correct one thanks to using overloads.

  • Control Flow Alternation

    An obfuscator can turn nicely structured code using if, while, for statements into a big spaghetti mess, by utilizing lots of goto statements. The more code you have, the more difficult it will be to understand the generated spaghetti end result.

  • String Encryption

    When code has been turned in to a complex obfuscated mess, it is still possible to find interesting parts due to the readability of strings used, limiting the attack vector to a smaller piece of obfuscated to be understood.

    Obfuscators provide the ability to encrypt strings and decrypt them at run time, making them unreadable in the source code.

  • Assembly Linking

    Calls made to .NET Framework methods will still be readable, because of this some obfuscators allow you to link in the .NET Framework assemblies being used, and obfuscating these as well, making it impossible to find anything 'normal' in the IL.

Besides protection features some obfuscator packages out there also provide nice diagram generators to analyze your assembly.

Assembly Information

After applying an obfuscator on my previous CrackMe program, this is how it looks when opened with Reflector:

Reflector viewing obfuscated assembly

As you can see, Reflector is already unable to generate valid C# code for it. With some obfuscators it is even possible to make Reflector totally unable to output anything, besides IL. Trying to view in C# for example, made Reflector throw an exception.

Reflector bug report trying to open obfuscated assembly

Testing this on my SuperSecretApplication application, the obfuscator applied several methods on the IL of the assembly:

  • Method renaming, using Unicode characters which couldn't get displayed.
  • Parameter renaming, using a simply naming scheme.
  • Altered control flow, using several jump conditions, as displayed by the arrows in Reflexil.
  • String encryption, making it harder to find interesting sections.
 
.method private hidebysig static void รก(string[] A_0) cil managed
{
    .entrypoint
    .maxstack 3
    .locals init (
        [0] string str,
        [1] int32 num,
        [2] int32 num2)
    L_0000: ldc.i4 14
    L_0005: stloc num2
    L_0009: br.s L_0024
    L_000b: ldloc num
    L_000f: switch (L_00b7, L_0050, L_0071, L_0094)
    L_0024: ldstr "\ud382\ue484\uf486\ufa88\ufc8a\ue28c\ufd8e\uf590\ua992\ub594"
    L_0029: ldloc num2
    L_002d: call string <module>::a(string, int32)
    L_0032: call void [mscorlib]System.Console::Write(string)
    L_0037: call string [mscorlib]System.Console::ReadLine()
    L_003c: stloc.0
    L_003d: ldc.i4.1
    L_003e: br.s L_0043
    L_0040: ldc.i4.0
    L_0041: br.s L_0043
    L_0043: brfalse.s L_0045
    L_0045: ldc.i4 1
    L_004a: stloc num
    L_004e: br.s L_000b
    L_0050: ldloc.0
    L_0051: ldstr "\ue182\ue984\ue886\uee88\ua58a\uee8c\ufa8e\ufc90\ue392\ue694\ub996\ufb98\ufe9a"
    L_0056: ldloc num2
    L_005a: call string <module>::a(string, int32)
    L_005f: call bool [mscorlib]System.String::op_Equality(string, string)
    L_0064: brfalse.s L_0073
    L_0066: ldc.i4 2
    L_006b: stloc num
    L_006f: br.s L_000b
    L_0071: br.s L_0096
    L_0073: ldstr "\ucd82\uea84\ua686\ua988\uc58a\ue28c\uae8e"
    L_0078: ldloc num2
    L_007c: call string <module>::a(string, int32)
    L_0081: call void [mscorlib]System.Console::WriteLine(string)
    L_0086: ldc.i4 3
    L_008b: stloc num
    L_008f: br L_000b
    L_0094: br.s L_00b9
    L_0096: ldstr "\uda82\uea84\uf286\ua988\ue68a\uec8c\ue18e\uf090\uf492\uf094\uf396\ub998\uef9a\uf29c\ubf9e\uc4a0\ucda2\ud1a4\uc2a6\udba8\u8baa\ud9ac\uc7ae\ud4b0\u93b2\uc6b4\ud2b6\udab8\uc9ba\ud8bc\ucbbe\ue1c0\ua2c2\ub5c4\ub7c6\ua5c8\ua2ca\uaecc\uaece\ua5d0\ubad2\ubad4\ub9d6\uf8d8"
    L_009b: ldloc num2
    L_009f: call string <module>::a(string, int32)
    L_00a4: call void [mscorlib]System.Console::WriteLine(string)
    L_00a9: ldc.i4 0
    L_00ae: stloc num
    L_00b2: br L_000b
    L_00b7: br.s L_00b9
    L_00b9: ldstr "\ud382\uf784\ue286\ufa88\uf88a\uad8c\uee8e\uff90\uea92\ub594\ufc96\ufc98\ue29a\ubd9c\ueb9e\ucea0\u83a2\uc6a4\uc8a6\uc7a8\udfaa\uc4ac\uc1ae\uc4b0\ud6b2\u95b4\u99b6\u99b8\u95ba\u9dbc\u91be"
    L_00be: ldloc num2
    L_00c2: call string <module>::a(string, int32)
    L_00c7: call void [mscorlib]System.Console::Write(string)
    L_00cc: ldc.i4.1
    L_00cd: call valuetype [mscorlib]System.ConsoleKeyInfo [mscorlib]System.Console::ReadKey(bool)
    L_00d2: pop
    L_00d3: ret
}

As you can see, given enough time, it is possible to figure out the above code and still break it. The more code you have however, the harder it becomes due to the increasing complexity of the obfuscated code, added with the fact that obfuscators will be able to apply even more advanced methods.

Obfuscators also have some disadvantages though. When writing advanced code involving reflection, obfuscating an assembly might break your code, possibly due to class and namespaces being renamed. Debugging also becomes harder because the stacktrace will contain renamed method signatures.

A good obfuscator will offer features to work around these advantages though, by allowing you to mark sections which should be skipped for obfuscation and also providing tools to translate an obfuscated stack trace to the original methods, using a mapping file.

You can find a comparison between several obfuscators on How To Select Guides, including links to individual websites and details about which features they support.

This post is the third in a series on protecting intellectual property.

 

Ever heard of the very popular game for the PlayStation 2, called Guitar Hero? Until recently, I only vaguely picked it up here and there, but not being a big PlayStation gamer, I never payed much attention. That is, until today. A friend of mine gave me a link to Frets On Fire, which claims to be the PC variant of Guitar Hero. Seeing it was free, I downloaded it and gave it a try, and I have to admit, it's addictive!

Allow me to give you a small introduction on this game.

First of all, start by downloading Frets On Fire and installing it on your computer.

Let's get started and begin the fun by selecting one of the available songs, there only three out of the box, but you can download additional songs.

The selected song will load and you'll notice five frets above the snares. These frets can be selected using the F1 to F5 buttons, but there are also instructions available on using your guitar hero controller. After a while, you'll notice various notes coming towards you, the goal is to pick the correct snare when the note is around the same position of the frets. You can pick a snare by pressing the ENTER key while holding a fret.

Some notes will be very short, while others have a long trail behind them, simply hold the fret down long enough to play the entire note. An example of this can be seen in the video I recorded of Anthrax - Caught In A Mosh on the left side which has some very long notes in the beginning followed by lots of short ones towards the end.

The better you play, the higher your score will be. A counter will be ticking up in the upper left corner, keeping track of the amount of successful notes played in succession, while in the upper right corner you'll see the bonus meter build up per note. This meter will tick up per 10 correct notes played and give you up to a 4x multiplier for your score, an incorrect note will reset it back to 1.

To make your ears like the song, you'd better play as many correct notes as possible, because missing a note will be audible due to the guitar suddenly falling silent. It's also possible to make a wrong note stand out very clearly. There are various degrees of difficulty, making you hit multiple notes together and shorter after each other in increasing difficulty. Since I'm still quite bad at it, the video I recorded was played on the easiest difficulty.

Don't feel sorry to play on the lowest difficulty though, the most valuable feature of the game is being the fact that it's a great party game! The laughs and hours of fun you can have with this game are amazing, especially since it's free!

Another nice addition is the possibility to change the look and feel through the use of mods, and even introduce multi-player functionality.

Frets On Fire managed to make me love this genre of games, where the simplicity makes it so addictive you'd play it all day long.

If you'll excuse me now, I have to prepare for my big rock concert! :)