Tag: example

What Makes Good Code? – Should Every Class Have An Interface? Pt 1

What Makes Good Code? - Should Every Class Have An Interface?

What’s An Interface?

I mentioned in the first post of this series that I’ll likely be referring to C# in most of these posts. I think the concept of an interface in C# extends to other languages–sometimes by a different name–so the discussion here may still be applicable. Some examples in C++, Javaand Python to get you going for comparisons.

From MSDN:

An interface contains definitions for a group of related functionalities that a class or a struct can implement.
By using interfaces, you can, for example, include behavior from multiple sources in a class. That capability is important in C# because the language doesn’t support multiple inheritance of classes. In addition, you must use an interface if you want to simulate inheritance for structs, because they can’t actually inherit from another struct or class.

It’s also important to note that an interface decouples the definition of something from its implementation. Decoupled code is, in general, something that programmers are always after. If we refer back to the points I defined for what makes good code (again, in my opinion), we can see how interfaces should help with that.

  • Extensibility: Referring to interfaces in code instead of concrete classes allows a developer to swap out the implementation easier (i.e. extend support for different data providers in your data layer). They provide a specification to be met should a developer want to extend the code base with new concrete implementations.
  • Maintainability: Interfaces make refactoring an easier job (when the interface signature doesn’t have to change). A developer can get the flexibility of modifying the implementation that already exists or creating a new one provided that it meets the interface.
  • Testability: Referring to interfaces in code instead of concrete classes allows mocking frameworks to leverage mocked objects so that true unit tests are easier to write.
  • Readability: I’m neutral on this. I don’t think interfaces are overly helpful for making code more readable, but I don’t think they inherently make code harder to read.

I’m only trying to focus on some of the pro’s here, and we’ll use this sub-series to explore if these hold true across the board. So… should every class have a backing interface?

An Example

Let’s walk through a little example. In this example, we’ll look at an object that “does stuff”, but it requires something that can do a string lookup to “do stuff” with. We’ll look at how using an interface can make this type of code extensible!

First, here is our interface that we’ll use for looking up strings:

public interface IStringLookup
{
    string GetString(string name);
}

And here is our first implementation of something that can lookup strings for us. It’ll just lookup an XML node and pull a value from it. (How it actually does this stuff isn’t really important for the example, which is why I’m glossing over it):

public sealed class XmlStringLookup : IStringLookup
{
    private readonly XmlDocument _xmlDocument;

    public XmlStringLookup(XmlDocument xmlDocument)
    {
        _xmlDocument = xmlDocument;
    }

    public string GetString(string name)
    {
        return _xmlDocument
            .GetElementsByTagName(name)
            .Cast<XmlElement>()
            .First()
            .Value;
    }
}

This will be used to plug into the rest of the code:

private static int Main(string[] args)
{
    var obj = CreateObj();
    var stringLookup = CreateStringLookup();
    
    obj.DoStuff(stringLookup);
 
    return 0;
}
 
private static IMyObject CreateObj()
{
    return new MyObject();
}
 
private static IStringLookup CreateStringLookup()
{
    return new XmlStringLookup(new XmlDocument());
}
 
public interface IMyObject
{
    void DoStuff(IStringLookup stringLookup);
}
 
public class MyObject : IMyObject
{
    public void DoStuff(IStringLookup stringLookup)
    {
        var theFancyString = stringLookup.GetString("FancyString");
        
        // TODO: do stuff with this string
    }
}

In the code snippet above, you’ll see our Main() method creating an instance of “MyObject” which is the thing that’s going to “DoStuff” with our XML string lookup. The important thing to note is that the DoStuff method takes in the interface IStringLookup that our XML class implements.

Now, XML string lookups are great, but let’s show why interfaces make this code extensible. Let’s swap out an XML lookup for an overly simplified CSV string lookup! Here’s the implementation:

public sealed class CsvStringLookup : IStringLookup
{
    private readonly StreamReader _reader;
 
    public CsvStringLookup(StreamReader reader)
    {
        _reader = reader;
    }
 
    public string GetString(string name)
    {
        string line;
        while ((line = _reader.ReadLine()) != null)
        {
            var split = line.Split(',');
            if (split[0] != name)
            {
                continue;
            }
 
            return split[1];
        }
 
        throw new InvalidOperationException("Not found.");
    }
}

Now to leverage this class, we only need to modify ONE line of code from the original posting! Just modify CreateStringLookup() to be:

private static IStringLookup CreateStringLookup()
{
    return new CsvStringLookup(new StreamReader(File.OpenRead(@"pathtosomefile.txt")));
}

And voila! We’ve been able to extend our code to use a COMPLETELY different implementation of a string lookup with relatively no code change. You could make the argument that if you needed to modify the implementation for a buggy class that as long as you were adhering to the interface, you wouldn’t need to modify much surrounding code (just like this example). This would be a point towards improved maintainability in code.

“But wait!” you shout, “I could have done the EXACT same thing with an abstract class instead of the IStringLookup interface you big dummy! Interfaces are garbage!”

And you wouldn’t be wrong about the abstract class part! It’s totally true that IStringLookup could instead have been an abstract class like StringLookupBase (or something…) and the benefits would still apply! That’s a really interesting point, so let’s keep that in mind as we continue on through out this whole series. The little lesson here? It’s not the interface that gives us this bonus, it’s the API boundary and level of abstraction we introduced (something that does string lookups). Both an interface and abstract class happen to help us a lot here.

Continue to Part 2


IronPython: A Quick WinForms Introduction

IronPython: A Quick WinForms Introduction

Background

A few months ago I wrote up an article on using PyTools, Visual Studio, and Python all together. I received some much appreciated positive feedback for it, but really for me it was about exploring. I had dabbled with Python a few years back and hadn’t really touched it much since. I spend the bulk of my programming time in Visual Studio, so it was a great opportunity to try and bridge that gap.

I had an individual contact me via the Dev Leader Facebook group that had come across my original article. However, he wanted a little bit more out of it. Since I had my initial exploring out of the way, I figured it was probably worth trying to come up with a semi-useful example. I could get two birds with one stone here–Help out at least one person, and get another blog post written up!

The request was really around taking the output from a Python script and being able to display it in a WinForm application. I took it one step further and created an application that either lets you choose a Python script from your file system or let you type in a basic script directly on the form. There isn’t any fancy editor tools on the form, but someone could easily take this application and extend it into a little Python editor if they wanted to.

Leveraging IronPython

In my original PyTools article, I mention how to get IronPython installed into your Visual Studio project. In Visual Studio 2012 (and likely a very similar approach for other versions of Visual Studio), the following steps should get you setup with IronPython in your project:

  • Open an existing project or start a new one.
  • Make sure your project is set to be at least .NET 4.0
    • Right click on the project within your solution explorer and select “Properties”
    • Switch to the “Application” tab.
    • Under “Target framework”, select  “.NET Framework 4.0”.
  • Right click on the project within your solution explorer and select “Manage NuGet Packages…”.
  • In the “Search Online” text field on the top right, search for “IronPython”.
  • Select “IronPython” from within the search results and press the “Install” button.
  • Follow the instructions, and you should be good to go!

Now that we have IronPython in a project, we’ll need to actually look at some code that gets us up and running with executing Python code from within C#. If you followed my original post, you’ll know that it’s pretty simple:


var py = Python.CreateEngine();
py.Execute("your python code here");

And there you have it. If it seems easy, that’s because it is. But what about the part about getting the output from Python? What if I wanted to print something to the console in Python and see what it spits out? After all, that’s the goal I was setting out to accomplish with this article. If you try the following code, you’ll notice you see a whole lot of nothing:


var py = Python.CreateEngine();
py.Execute("print('I wish I could see this in the console...')");

What gives? How are we supposed to see the output from IronPython? Well, it all has to do with setting the output Stream of the IronPython engine. It has a nice little method for letting you specify what stream to output to:


var py = Python.CreateEngine();
py.Runtime.IO.SetOutput(yourStreamInstanceHere);

In this example, I wanted to output the stream directly into my own TextBox. To accomplish this, I wrote up my own little stream wrapper that takes in a TextBox and appends the stream contents directly to the Text property of the TextBox. Here’s what my stream implementation looks like:


private class ScriptOutputStream : Stream
{
  #region Fields
  private readonly TextBox _control;
  #endregion

  #region Constructors
  public ScriptOutputStream(TextBox control)
  {
    _control = control;
  }
  #endregion

  #region Properties
  public override bool CanRead
  {
    get { return false; }
  }

  public override bool CanSeek
  {
    get { return false; }
  }

  public override bool CanWrite
  {
    get { return true; }
  }

  public override long Length
  {
    get { throw new NotImplementedException(); }
  }

  public override long Position
  {
    get { throw new NotImplementedException(); }
    set { throw new NotImplementedException(); }
  }
  #endregion

  #region Exposed Members
  public override void Flush()
  {
  }

  public override int Read(byte[] buffer, int offset, int count)
  {
    throw new NotImplementedException();
  }

  public override long Seek(long offset, SeekOrigin origin)
  {
    throw new NotImplementedException();
  }

  public override void SetLength(long value)
  {
    throw new NotImplementedException();
  }

  public override void Write(byte[] buffer, int offset, int count)
  {
    _control.Text += Encoding.GetEncoding(1252).GetString(buffer, offset, count);
  }
  #endregion
}

Now while this isn’t pretty, it serves one purpose: Use the stream API to allow binary data to be appended to a TextBox. The magic is happening inside of the Write() method where I take the binary data that IronPython will be providing to us, convert it to a string via code page 1252 encoding, and then append that directly to the control’s Text property. In order to use this, we just need to set it up on our IronPython engine:


var py = Python.CreateEngine();
py.Runtime.IO.SetOutput(new ScriptOutputStream(txtYourTextBoxInstance), Encoding.GetEncoding(1252));

Now, any time you output to the console in IronPython you’ll get your console output directly in your TextBox! The ScriptOutputStream implementation and calling SetOutput() are really the key points in getting output from IronPython.

The Application at a Glance

I wanted to take this example a little bit further than the initial request. I didn’t just want to show that I could take the IronPython output and put it in a form control, I wanted to demonstrate being able to pick the Python code to run too!

Firstly, you’re able to browse for Python scripts using the default radio button. Just type in the path to your script or use the browse button:

IronPython - Run script from file

Enter a path or browse for your script. Press “Run Script” to see the output of your script in the bottom TextBox.

Next, press “Run Script”, and you’re off! This simply uses a StreamReader to get the contents of the file and then once in the contents are stored in a string, they are passed into the IronPython engine’s Execute() method. As you might have guessed, my “helloworld.py” script just contains a single line that prints out “Hello, World!”. Nothing too fancy in there!

Let’s try running a script that we type into the input TextBox instead. There’s some basic error handling so if your script doesn’t execute, I’ll print out the exception and the stack trace to go along with it. In this case, I tried executing a Python script that was just “asd”. Clearly, this is invalid and shouldn’t run:

python_error_asd

Python interpreted the input we provided but, as expected, could not find a definition for “asd”.

That should be along the lines of what we expected–The script isn’t valid, and IronPython tells us why. What other errors can we see? Well, the IronPython engine will also let you know if you have bad syntax:

python_error_bad_syntax

Python interpreted the script, but found a syntax error in our silly input.

Finally, if we want to see some working Python we can do some console printing. Let’s try a little HelloWorld-esque script:

python_pass_hello_world

Python interpreted our simple Hello World script.

Summary

This sample was pretty short but that just demonstrates how easy it is! Passing in a script from C# into the IronPython is straight forward, but getting the output from IronPython is a bit trickier. If you’re not familiar with the different parts of the IronPython engine, it can be difficult to find the things you need to get this working. With a simple custom stream implementation we’re able to get the output from IronPython easily. All we had to do was create our own stream implementation and pass it into the SetOutput() method that’s available via the IronPython engine class. Now we can easily hook the output of our Python scripts!

As always, all of the source for you to try this out is available online:

Some next steps might include:

  • Creating your own Python IDE. Figure out some nice text-editing features and you can run Python scripts right from your application.
  • Creating a test script dashboard. Do you write test scripts for other applications in Python? Why not have a dashboard that can report on the results of these scripts?
  • Add in some game scripting! Sure, you could have done this with IronPython alone, but maybe now you can skip the WinForms part of this and just make your own stream wrapper for getting script output. Cook up some simple scripts in a scripting engine and voila! You can easily pass information into Python and get the results back out.

Let me know in the comments if you come up with some other cool ideas for how you can leverage this!


Lambdas: An Example in Refactoring Code

Lambdas: An Example in Refactoring Code

Background: Lambdas and Why This Example is Important

Based on your experience in C# or other programming languages, you may or may not be familiar with what a lambda is. If the word “Lambda” is new and scary to you, don’t worry. Hopefully after reading this you’ll have a better idea of how you can use them. My definition of a lambda expression is a function that you can define in local scope to pass as an argument provided it meets the delegate signature. It’s probably pretty obvious to you that you can pass in object references and value types into all kinds of functions… But what about passing in a whole function as an argument? And what if you just want to declare a simple anonymous method right when you want to provide it to a function? Lambdas.

So now you at least have a basic idea of what a Lambda is. What’s this article all about? I wanted to discuss a real-world coding experience that helped demonstrate the value of lambdas to me. In my honest opinion, I think having real world programming topics to learn from is more beneficial than many of the “ideal” scenario examples/tutorials you end up reading on the Internet. We can argue and debate that certain things are better or worse in an ideal sense, but when you have a real practical example, it really helps to drive the point home.

So for me, I love working with events. I’m very comfortable with the concept of delegation in C#. I can have one object that may notify anyone that’s interested that something is happening, and the other objects that do care are able to handle the event. Thus, actions can get delegated to those objects that care to be notified. One of my weaknesses at this point in my development experience is leveraging the concept of delegation outside of the realm of events. Delegation is powerful, but it’s certainly not limited to hooking onto events with event handlers.

The particular example I want to illustrate is a parallel of a real coding scenario. I was refactoring some code that was leveraging close to zero OOP practices. I wanted to create a nice extensible framework and class hierarchy to replace it. Once I was done, a few colleagues of mine at Magnet Forensics picked up on a bit of a code smell. We all agreed the new framework and class hierarchy was better, but there seemed to be a lot of boiler plate code going on. We got into the discussion of how lambdas could reduce a lot of the light-weight classes I had introduced. After taking their thoughts and refactoring my changes just a little bit more, the benefits of the lambdas were obvious to me.

So obvious, I had to write about it to share with all of you! Feel free to skip ahead to the downloads section to get the code and follow along with it. There are plenty of options for downloading.

The Scenario

I mentioned that this was a real world scenario. I’ve contrived a parallel example that hopefully demonstrates some of the real world issues while illustrating how lambdas are useful. Let’s imagine we have some big chunk of logic that does data processing. In my real-world scenario, this may have existed as one monolithic function. I would have one big function that, based on all the parameters I provide, can figure out how to process the data I feed it.

Problems:

  • Hard to test (You need to test the whole function even if you’re really just wanting to target a small part of it)
  • Error prone (Any small change to one part can potentially break an entire other part of the function as it grows in complexity)
  • Not extensible (As soon as you need to deviate a little bit from the structure that’s existed, suddenly things get really complicated)

By switching to more of an OOP approach, I can start to address all of the above problems. So in this example, I’ll illustrate what my initial refactoring would have looked like by introducing classes. Afterward, I’ll show what my second refactor may have looked like after taking lambdas into account. In order to stay true to some of the real world problems you might encounter when performing a big refactor like this, I’ve opted to include some fictitious dependency. I refer to this at the “mandatory argument” or “important reference”. You’ll notice in the code that I don’t really use it to do any work, but it’s demonstrating having to pass down some other critical information to my classes that the original function may have had easy access to.

Pre-Refactor: No Lambdas Here!

Let’s start with our new OOP layout. I want to have a factory that can create data processor instances for me. So let’s define what those look like.

First, we have the interface for our data processors:

using System;
using System.Collections.Generic;
using System.Text;

namespace LambdaRefactor.Processing
{
  public interface IProcessor
  {
    bool TryProcess(object input);
  }
}

And then a simple interface for a factory that can create the data processor instances for us:

using System;
using System.Collections.Generic;
using System.Text;

namespace LambdaRefactor.Processing
{
  public interface IProcessorFactory
  {
    IProcessor Create(ProcessorType type, object mandatoryArgument, object value);
  }
}

As you may have noticed, the factory interface I’ve provided above takes a ProcessorType enumeration. You may or may not agree that using an enumeration as an argument for the factory is good practice, but I’m using it to make my example simple. Here’s what our enumeration will look like:

using System;
using System.Collections.Generic;
using System.Text;

namespace LambdaRefactor.Processing
{
  public enum ProcessorType
  {
    GreaterThan,
    LessThan,
    NumericEqual,
    StringEqual,
    StringNotEqual,
    /* we could add countless more types of processors here. realistically,
     * an enum may not be the best option to accomplish this, but for
     * demonstration purposes it'll make things much easier.
     */
  }
}

And now we have a definition for all of the basic building blocks defined. These will also be used later when we refactor, so I wanted to get them out of the way right in the beginning.

Right. So, let’s create an extensible IProcessor implementation. We can address some of our basic requirements (like our artificial dependency) and create something that can easily be built on top of. All of our child classes will just have to handle validating their constructor input and overriding a single method. Easy!

using System;
using System.Collections.Generic;
using System.Text;

namespace LambdaRefactor.Processing.PreRefactor
{
  public abstract class Processor : IProcessor
  {
    private readonly object _importantReference;

    public Processor(object mandatoryArgument)
    {
      if (mandatoryArgument == null)
      {
        throw new ArgumentNullException("mandatoryArgument");
      }

      _importantReference = mandatoryArgument;
    }

    public bool TryProcess(object input)
    {
      if (input == null)
      {
        return false;
      }

      return Process(_importantReference, input);
    }

    protected abstract bool Process(object importantReference, object input);
  }
}

And now let’s provide the factory that’s going to be making all of these instances for us. Please not that the factory is left incomplete on purpose. I’ll only be providing two actual processor implementations and I’ll leave it up to you to try and fill out the rest!

using System;
using System.Collections.Generic;
using System.Text;

using LambdaRefactor.Processing.PreRefactor.Numeric;
using LambdaRefactor.Processing.PreRefactor.String;

namespace LambdaRefactor.Processing.PreRefactor
{
  public class ProcessorFactory : IProcessorFactory
  {
    public IProcessor Create(ProcessorType type, object mandatoryArgument, object value)
    {
      switch (type)
      {
        case ProcessorType.GreaterThan:
          return new GreaterProcessor(mandatoryArgument, value);
        case ProcessorType.StringEqual:
          return new StringEqualsProcessor(mandatoryArgument, value);
        /*
         * we still have to go implement all the other classes!
         */
        default:
          throw new NotImplementedException("The processor type '" + type + "' has not been implemented in this factory.");
      }
    }
  }
}

And now that we have a factory that can easily create our processors for us, let’s actually define some of our processor implementations.

We’ll start off with a simple processor for checking if some input is greater than a defined value. It should really only work with numeric values, but one of the challenges we need to work with is that our data is only provided to us as an object. As a result, we’ll have to do some type checking on our own.

using System;
using System.Collections.Generic;
using System.Text;
using System.Globalization;

namespace LambdaRefactor.Processing.PreRefactor.Numeric
{
  public class GreaterProcessor : Processor
  {
    private readonly decimal _value;

    public GreaterProcessor(object mandatoryArgument, object value)
      : base(mandatoryArgument)
    {
      if (value == null)
      {
        throw new ArgumentNullException("value");
      }

      _value = Convert.ToDecimal(value, CultureInfo.InvariantCulture); // will throw exception on mismatch
    }

    protected override bool Process(object importantReference, object input)
    {
      decimal numericInput;
      try
      {
        numericInput = Convert.ToDecimal(input, CultureInfo.InvariantCulture);
      }
      catch (Exception)
      {
        return false;
      }

      return numericInput > _value;
    }
  }
}

And to put a spin on things, let’s implement a processor that operates on string values only. We’ll implement the processor that checks if strings are equal. Like the GreaterProcessor, we’re forced to get object references passed in. We’ll need to convert these to strings to work with them.

using System;
using System.Collections.Generic;
using System.Text;

namespace LambdaRefactor.Processing.PreRefactor.String
{
  public class StringEqualsProcessor : Processor
  {
    private readonly string _value;

    public StringEqualsProcessor(object mandatoryArgument, object value)
      : base(mandatoryArgument)
    {
      if (value == null)
      {
        throw new ArgumentNullException("value");
      }

      _value = (string)value; // will throw exception on mismatch
    }

    protected override bool Process(object importantReference, object input)
    {
      return Convert.ToString(input, System.Globalization.CultureInfo.InvariantCulture).Equals(_value);
    }
  }
}

Where can we go from here?

  • We can make simple inverse processors by overriding others and inverting the return value on the Process() function. Want a StringDoesNotEqual processor? It’s just as easy as  inheriting from the StringEqualsProcessor and then modifying the return of Process(). Then we add this to our factory.
  • Adding other various types of processors is easy. We just have to extend our base class and add a couple of lines to our factory.
  • This code is much easier to test than one monolithic function that does all types of processing. We can now put a nice testing framework around this, and test each method on each class individually.

Post-Refactor: All of the Lambdas!

So… Why don’t we stop here? Because we can do better.

I mentioned that to make a simple inverse processor, all I had to do was override a class and invert the return value of Process(). That’s pretty easy to do… Except I need an entire new class to do it. If I want to make more types of numeric processing, I need to provide similar type checking and conversion. This code gets duplicated every time I go to add another simple class.

I also have my factory class responsible for creating my processor instances. They’re relatively coupled already, but I want developers to have to use my factory to construct instances of processor interface and not worry about the specific implementations. So what if my factory had a bit more say in the construction if the processors? I could use lambdas to pass in the logic that’s unique to each type of processor, and keep each type of processor pretty bare bones. This would move more logic into the factory, but reduce the number of processor implementations I have to make.

So let’s do better!

Let’s start with our new IProcessor implementation. We’ll provide a delegate signature that will be the basis for the lambda expressions we pass in:

using System;
using System.Collections.Generic;
using System.Text;

namespace LambdaRefactor.Processing.PostRefactor
{
  public abstract class Processor : IProcessor
  {
    private readonly object _importantReference;

    public Processor(object mandatoryArgument)
    {
      if (mandatoryArgument == null)
      {
        throw new ArgumentNullException("mandatoryArgument");
      }

      _importantReference = mandatoryArgument;
    }

    public delegate bool ProcessDelegate<T>(object importantReference, T processorValue, T input);

    public bool TryProcess(object input)
    {
      if (input == null)
      {
        return false;
      }

      return Process(_importantReference, input);
    }

    protected abstract bool Process(object importantReference, object input);
  }
}

From here, we can come up with some child classes that that are generic enough for us to work with using lambas that still provide enough functionality for them to exist on their own. We can break our processors up based on the type of data they’ll be working with. That is, we can have a processor for numeric values and a processor for string values. This will cover a lot of the duplicated functionality that exists in the current state of our refactor if we wanted to keep creating new IProcessor implementations.

Let’s start with our NumericProcessor:

using System;
using System.Collections.Generic;
using System.Text;
using System.Globalization;

namespace LambdaRefactor.Processing.PostRefactor.Numeric
{
  public class NumericProcessor : Processor
  {
    private readonly decimal _value;
    private readonly ProcessDelegate<decimal> _processDelegate;

    public NumericProcessor(object mandatoryArgument, object value, ProcessDelegate<decimal> processDelegate)
      : base(mandatoryArgument)
    {
      if (value == null)
      {
        throw new ArgumentNullException("value");
      }

      if (processDelegate == null)
      {
        throw new ArgumentNullException("processDelegate");
      }

      _value = Convert.ToDecimal(value, CultureInfo.InvariantCulture); // will throw exception on mismatch
      _processDelegate = processDelegate;
    }

    protected override bool Process(object importantReference, object input)
    {
      decimal numericInput;
      try
      {
        numericInput = Convert.ToDecimal(input, CultureInfo.InvariantCulture);
      }
      catch (Exception)
      {
        return false;
      }

      return _processDelegate(importantReference, _value, numericInput);
    }
  }
}

And similarly, a StringProcessor:

using System;
using System.Collections.Generic;
using System.Text;

namespace LambdaRefactor.Processing.PostRefactor.String
{
  public class StringProcessor : Processor
  {
    private readonly string _value;
    private readonly ProcessDelegate<string> _processDelegate;

    public StringProcessor(object mandatoryArgument, object value, ProcessDelegate<string> processDelegate)
      : base(mandatoryArgument)
    {
      if (value == null)
      {
        throw new ArgumentNullException("value");
      }

      if (processDelegate == null)
      {
        throw new ArgumentNullException("processDelegate");
      }

      _value = (string)value; // will throw exception on mismatch
      _processDelegate = processDelegate;
    }

    protected override bool Process(object importantReference, object input)
    {
      return _processDelegate(importantReference, _value, Convert.ToString(input, System.Globalization.CultureInfo.InvariantCulture));
    }
  }
}

With these two basic child classes built upon our new IProcessor implementation, we can restructure a new IProcessorFactory implementation. As I mentioned, we can leverage lambdas to move some logic back into the factory class and keep the processor implementations relatively basic.

Here’s the new factory:

using System;
using System.Collections.Generic;
using System.Text;

using LambdaRefactor.Processing.PostRefactor.Numeric;
using LambdaRefactor.Processing.PostRefactor.String;

namespace LambdaRefactor.Processing.PostRefactor
{
  public class ProcessorFactory : IProcessorFactory
  {
    public IProcessor Create(ProcessorType type, object mandatoryArgument, object value)
    {
      switch (type)
      {
        case ProcessorType.GreaterThan:
          return new NumericProcessor(mandatoryArgument, value, (_, x, y) => x <; y);
        case ProcessorType.StringEqual:
          return new StringProcessor(mandatoryArgument, value, (_, x, y) => x == y);
        /*
         * Look how easy it is to add new processors! Exercise for you:
         * implement the remaining processors in the enum!
         */
        default:
          throw new NotImplementedException("The processor type '" + type + "' has not been implemented in this factory.");
      }
    }
  }
}

As you can see, our new factory is simple like our first implementation. The major difference? We’re passing very simple lambdas that would have otherwise been functionality defined in a very light-weight child class. This allows us to move away from having many potentially very bare-bones classes and minimizes the amount of boilerplate duplication.

Summary

I didn’t post it here, but the original implementation that this example paralleled  in real life was a pain to deal with. It was hard to test, brittle to modify/extend, and just downright unwieldly. It was obvious to me that switching to a refactored object-oriented implementation was going to make this style of code easy to extend and easy to test.

The initial refactor posted in this example was a great step in the right direction. The code became easy to build upon by relying on simple OOP principals, and granular parts of the functionality became really easy to test. If I just wanted to test certain types of numeric processing, I didn’t have set up a test for my entire massive “process” function. All I’d have to do is make an instance of the processor I want to test, and call the methods I’d like to cover. Incredibly easy.

Lambdas took this to the next level though. By leveraging lambads, I could refactor even more common code into a base class. This meant that  in order to use my processors properly, the final factory class implementation definitely became required to use. It caused a paradigm shift where instead of making lots of light-weight child classes for additional processor implementations, I’d only need to implement some logic in the factory. All of my existing processors could be refactored into a handful of generic processor classes, and the factory would be responsible for passing in the necessary lambdas.

Lambdas let you accomplish some pretty powerful things, and this refactoring example was one case where they made code much easier to manage. Hopefully you can find a good use for lamba expressions in your next up-coming programming task!

Code Downloads


Fragments: Creating a Tabbed Android User Interface

Fragments: Creating a Tabbed Android User Interface

Fragments: A Little Background

Update: The actual application is available on the Google Play store.

Once upon a time, Android developers used only two things called activities and views in order to create their user interfaces. If you’re like me and you come from a desktop programming environment, an Activity is sort of like a form or a window. Except it’s more like a controller for one of these classes. With that analogy in place, a view is then similar to a control. It’s the visual part you’re interacting with as a user. I remember the learning curve being pretty steep for me being so stuck in my desktop (C# and WPF) development, but once I came up with these analogies on my own, it seemed pretty obvious. So to make an Android application, one would simply put some views together and chain some activities to show these views. Pretty simple.

Something changed along the way though. It was apparent that the Activity/View paradigm was a bit lacking so something new was added to the mix: The Fragment. Fragments were introduced in Android 3.0 (which is API level 11). Fragments added the flexibility to be able to swap out parts of an activity without having to completely redefine the whole view. This means that having an application on a mobile phone with a small screen can appear differently than when it’s on a large tablet, and as a developer you don’t have to redesign the whole bloody thing. Awesome stuff!

So, to clarify, a fragment is just a part of the activity. By breaking up activities into fragments, you get the modular flexibility of being able to swap in and out components at will. If you’re like me and you took a break from Android when fragments were introduced, then you may have another little learning curve. The goal of this article is to create a tabbed Android user interface using fragments.

For what it’s worth, when I first tried putting together a tabbed UI with fragments, it was a complete mess. I was surfing the net for examples, but I couldn’t find anything that really hit it home for me. Once I had it working, I decided I should redo it and document the process. That’s how this article came to be! Another side note… I’m a C# developer by trade and I haven’t developed with Android/Java within a team. If you don’t like my coding conventions then please try to look past that to get the meat of the article!

As per usual, you can follow along by downloading all of the code ahead of time. Please check out the section at the end of the article and pick whichever option you’d like to get the source!

Setting Up: Getting Your Project Together

I’m going to make a few assumptions here. You should have Eclipse installed with the latest Android Development Tools. There are plenty of examples out there for how to get your environment put together, but I’m not going to cover that here.

You’re going to want to start by making a new Android Application in eclipse. By going to the “File” menu, then the “New” sub menu, then the “Other” sub menu, you should get a dialog letting you pick Android application. You’ll get a wizard that looks like the following (where I’ve filled in the information with what I’ll be using for this entire example):

Tab Fragment Tutorial - New Android Application

The first part of the wizard is setting up your Android project.

The wizard gives you some options for what you want to have it generate for you. In this case, I opted out of having a custom icon (since that’s not really important for this tutorial) and I chose to have it create an activity for me.

Tab Fragment Tutorial - Create Activity

The second step in the wizard lets you choose what to create. I wanted just the activity made.

Our activity is actually going to be pretty light-weight. The bulk of what we’re going to be doing is going to be inside of our fragments. Because of this, we should be totally fine just making our main activity a simple blank activity.

Tab Fragment Tutorial - Create Blank Activity

We won’t have much code in our main activity. Let’s just opt for the blank activity.

The final step in the wizard just wants you to confirm the naming for your generated code.

Tab Fragment Tutorial - Activity Naming

Let’s create our “MainActivity” activity with a layout called “activity_main”. Pretty straight forward.

At this point, we actually have an Android application that we can deploy to a phone or a virtual device. If you’re new to Android programming, I suggest you try it out. It’s pretty exciting to get your first little application running.

The Layouts

The layout XML files in Android provide the hierarchies of views that will get shown in the UI. If you haven’t modified the one that was created by default, it will probably look like this:

Tab Fragment Tutorial - Initial Main Activity Layout XML

The default Main Activity XML will look like this. It’s really just a text view that says “Hello World”.

What does that give us? Well, we get a RelativeLayout view that acts as a container for a TextView. The TextView says “Hello World”. Amazing, right?

Let’s switch up our main activity’s layout a bit. Instead of a RelativeLayout, let’s drop in a linear layout that has a vertical orientation. We’ll blow away the TextView too, and drop in a Fragment. Our fragment will need to point to our custom fragment class (which we haven’t created yet). For now, make the class “com.devleader.tab_fragment_tutorial.TabsFragment”. Later in the example, we’ll create the TabsFragment class and put it within this package. When the application runs, it will load up our custom fragment (specified by the full class name) and place it within our LinearLayout.

The layout XML for the main activity looks like the following:


<LinearLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent">

 <fragment
 class="com.devleader.tab_fragment_tutorial.TabsFragment"
 android:id="@+id/tabs_fragment"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent" />
</LinearLayout>

We’re going to need a layout for our tabs fragment. This is going to be the view portion of the UI that gets dropped in to our main activity. It’s going to be responsible for showing the tabs at the top of the UI and then providing container views for the contents that each tab will want to show.

In order to create this layout, right click on your “layout” folder nested within the “res” folder in the Eclipse IDE. Go to “new”, and then click on the “Other” child menu. Pick “Android XML Layout File” from your list of options. Select “TabHost” as the layout’s root element. Let’s call this file “fragment_tabs.xml”.

The top level component in this layout will be a TabHost. We’ll put our TabWidget in next, which is going to contain the actual tab views, and then a FrameLayout with two nested FrameLayouts inside of it for holding the contents that we want to show for each tab. To clarify, the user will be clicking on views within the TabWidget to pick the tab, and the contents within the tab1 and tab2 FrameLayouts will show the corresponding user interface for each tab.

The layout XML for the tabs fragment looks like the following:


<TabHost
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@android:id/tabhost"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:background="#EFEFEF">

 <LinearLayout
 android:orientation="vertical"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent">

 <TabWidget
 android:id="@android:id/tabs"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content" />

 <FrameLayout
 android:id="@android:id/tabcontent"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent">

 <FrameLayout
 android:id="@+id/tab1"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:background="#FFFF00" />

 <FrameLayout
 android:id="@+id/tab2"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:background="#FF00FF" />

 </FrameLayout>
 </LinearLayout>
</TabHost>

You may have noticed I used some pretty aggressive hard-coded colors in the layout file. I highly advise you switch these to be whatever you want for your application, but when I’m debugging UI layouts I like to use really high contrasting colors. This helps me know exactly where things are (as opposed to having 10 views all with the same background). Maybe I’m a bit crazy, but I find it really helpful.

Now that we have the main activity done and the tab fragment all set up, the last thing we need is to create some sort of layout for our individual tab views. This will be the view that is placed inside of the TabWidget on our tabs fragment layout. These views will have the title of the tab and they’ll be what the user actually interacts with in order to switch tabs.

The layout XML for our simple tab view looks like the following:


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:orientation="vertical" >

<TextView
 android:id="@+id/tabTitle"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

And that’s it for layouts! Just these three simple files. Now, we need to fill out our classes!

The Classes

If we start from the beginning with the classes, the first (and only) class that gets generated for you is the MainActivity class. If you left it untouched (hopefully you did since there was no indication to change it yet!) then you should have a class that looks like:

Tab Fragment Tutorial - Initial Main Activity Class

The default MainActivity class that gets generated after we complete the steps in the wizard.

In order to make this example work, we barely even need to modify this class at all. You’ll notice our MainActivity extends the Activity class. Because we’re going to be using fragments in our application, we need to modify this class to extend the FragmentActivity. In this entire example, I opted to use the Android v4 Support Library. Thus, in order to make this example work, please ensure you’re using FragmentActivity from the package “android.support.v4.app.FragmentActivity“.

Once you’ve made this replacement (“Activity” for “FragmentActivity”) we’re all done in this class. Great stuff, right? Let’s move on.

We’re going to want to make a class that defines what a tab is. In order to make some nice re-usable code that you can extend, I decided to make a base class that defines minimum tab functionality (at least in my opinion). Feel free to extend upon this class later should your needs exceed what I’m offering in this tutorial.

The base TabDefinition class will:

  • Take in the ID of the view where the tab’s content will be put. In our example, this will be the ID for tab1 or tab2’s FrameLayout.
  • Provide a unique identifier to look up the tab.
  • Be required to provide the Fragment instance that will be used when the tab is activated.
  • Be required to create the tab view that the user will interact with in order to activate the tab.

Let’s add a new class called “TabDefinition” to the package “com.devleader.tab_fragment_tutorial”, just like where our MainActivity class is. The code for the TabDefinition class is as follows:


package com.devleader.tab_fragment_tutorial;

import java.util.UUID;

import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * A class that defines a UI tab.
 */
public abstract class TabDefinition {
 //
 // Fields
 //
 private final int _tabContentViewId;
 private final String _tabUuid;

 //
 // Constructors
 //
 /**
 * The constructor for {@link TabDefinition}.
 * @param tabContentViewId The layout ID of the contents to use when the tab is active.
 */
 public TabDefinition(int tabContentViewId) {
   _tabContentViewId = tabContentViewId;
   _tabUuid = UUID.randomUUID().toString();
 }

 //
 // Exposed Members
 //
 /**
 * Gets the ID of the tab's content {@link View}.
 * @return The ID of the tab's content {@link View}.
 */
 public int getTabContentViewId() {
   return _tabContentViewId;
 }

 /**
 * Gets the unique identifier for the tab.
 * @return The unique identifier for the tab.
 */
 public String getId() {
   return _tabUuid;
 }

 /**
 * Gets the {@link Fragment} to use for the tab.
 * @return The {@link Fragment} to use for the tab.
 */
 public abstract Fragment getFragment();

 /**
 * Called when creating the {@link View} for the tab control.
 * @param inflater The {@link LayoutInflater} used to create {@link View}s.
 * @param tabsView The {@link View} that holds the tab {@link View}s.
 * @return The tab {@link View} that will be placed into the tabs {@link ViewGroup}.
 */
 public abstract View createTabView(LayoutInflater inflater, ViewGroup tabsView);
}

Now that we have the bare-minimum definition of what a tab in our UI looks like, let’s make it even easier to work with. In my example, I just want to have my tabs have a TextView to display a title–They’re really simple. I figured I’d make a child class of TabDefinition called SimpleTabDefinition. The goal of SimpleTabDefinition is really just to provide a class that takes the minimum amount of information to get a title put onto a custom view.

Please keep in mind that there are many ways to accomplish what I’m trying to illustrate here, but I personally felt having a base class with a more specific child class would help illustrate my point. You could even put in a second type of child class that would make a graphical tab that shows a graphical resource instead of a string resource. Tons of options!

Let’s add another new class called “SimpleTabDefinition” to the package “com.devleader.tab_fragment_tutorial”. The code for SimpleTabDefinition is as follows:


package com.devleader.tab_fragment_tutorial;

import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;

/**
 * A class that defines a simple tab.
 */
public class SimpleTabDefinition extends TabDefinition {
  //
  // Fields
  //
  private final int _tabTitleResourceId;
  private final int _tabTitleViewId;
  private final int _tabLayoutId;
  private final Fragment _fragment;

  //
  // Constructors
  //
  /**
  * The constructor for {@link SimpleTabDefinition}.
  * @param tabContentViewId The layout ID of the contents to use when the tab is active.
  * @param tabLayoutId The ID of the layout to use when inflating the tab {@link View}.
  * @param tabTitleResourceId The string resource ID for the title of the tab.
  * @param tabTitleViewId The layout ID for the title of the tab.
  * @param fragment The {@link Fragment} used when the tab is active.
  */
  public SimpleTabDefinition(int tabContentViewId, int tabLayoutId, int tabTitleResourceId, int tabTitleViewId, Fragment fragment) {
    super(tabContentViewId);

    _tabLayoutId = tabLayoutId;
    _tabTitleResourceId = tabTitleResourceId;
    _tabTitleViewId = tabTitleViewId;
    _fragment = fragment;
  }

  //
  // Exposed Members
  //
  @Override
  public Fragment getFragment() {
    return _fragment;
  }

  @Override
  public View createTabView(LayoutInflater inflater, ViewGroup tabsView) {
    // we need to inflate the view based on the layout id specified when
    // this instance was created.
    View indicator = inflater.inflate(
      _tabLayoutId,
      tabsView,
      false);

    // set up the title of the tab. this will populate the text with the
    // string defined by the resource passed in when this instance was
    // created. the text will also be centered within the title control.
    TextView titleView = (TextView)indicator.findViewById(_tabTitleViewId);
    titleView.setText(_tabTitleResourceId);
    titleView.setGravity(Gravity.CENTER);

    // ensure the control we're inflating is layed out properly. this will
    // cause our tab titles to be placed evenly weighted across the top.
    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
      LayoutParams.WRAP_CONTENT,
      LayoutParams.WRAP_CONTENT);
    layoutParams.weight = 1;
    indicator.setLayoutParams(layoutParams);

    return indicator;
  }
}

Awesome stuff. Now we can define tabs easily in our application. We just have one more class left, I promise! In the following section, I’ll re-iterate over everything, so if you’re feeling a bit lost… Just hang in there.

The one part we’re actually missing is the fragment that will manage all of our tabs. We created the layout for it already, which has a TabHost, a TabWidget (to contain the clickable tab views), and some FrameLayouts (that contain the content we show when we press a tab). Now we just need to actually attach some code to it!

The TabsFragment class that we’re going to want to add to the package “com.devleader.tab_fragment_tutorial” is responsible for a few things. First, we’re going to be defining our tabs in here. This class will be responsible for taking those tab definitions and creating tabs that get activated via the TabHost. As a result, this fragment class is going to have to implement the OnTabChangedListener interface. This will add a method where we handle switching the fragment shown to match the fragment for the contents of the tab that was pressed.

The code for our TabsFragment class looks like the following:

package com.devleader.tab_fragment_tutorial;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;

/**
 * A {@link Fragment} used to switch between tabs.
 */
public class TabsFragment extends Fragment implements OnTabChangeListener {
  //
  // Constants
  //
  private final TabDefinition[] TAB_DEFINITIONS = new TabDefinition[] {
    new SimpleTabDefinition(R.id.tab1, R.layout.simple_tab, R.string.tab_title_1, R.id.tabTitle, new Fragment()),
    new SimpleTabDefinition(R.id.tab2, R.layout.simple_tab, R.string.tab_title_2, R.id.tabTitle, new Fragment()),
   };

  //
  // Fields
  //
  private View _viewRoot;
  private TabHost _tabHost;

  //
  // Exposed Members
  //
  @Override
  public void onTabChanged(String tabId) {
    for (TabDefinition tab : TAB_DEFINITIONS) {
      if (tabId != tab.getId()) {
        continue;
      }

      updateTab(tabId, tab.getFragment(), tab.getTabContentViewId());
      return;
    }

    throw new IllegalArgumentException("The specified tab id '" + tabId + "' does not exist.");
  }

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    _viewRoot = inflater.inflate(R.layout.fragment_tabs, null);

    _tabHost = (TabHost)_viewRoot.findViewById(android.R.id.tabhost);
    _tabHost.setup();

    for (TabDefinition tab : TAB_DEFINITIONS) {
      _tabHost.addTab(createTab(inflater, _tabHost, _viewRoot, tab));
    }

    return _viewRoot;
  }

  @Override
  public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    setRetainInstance(true);

    _tabHost.setOnTabChangedListener(this);

    if (TAB_DEFINITIONS.length > 0) {
      onTabChanged(TAB_DEFINITIONS[0].getId());
    }
  }

  //
  // Internal Members
  //
  /**
  * Creates a {@link TabSpec} based on the specified parameters.
  * @param inflater The {@link LayoutInflater} responsible for creating {@link View}s.
  * @param tabHost The {@link TabHost} used to create new {@link TabSpec}s.
  * @param root The root {@link View} for the {@link Fragment}.
  * @param tabDefinition The {@link TabDefinition} that defines what the tab will look and act like.
  * @return A new {@link TabSpec} instance.
  */
  private TabSpec createTab(LayoutInflater inflater, TabHost tabHost, View root, TabDefinition tabDefinition) {
    ViewGroup tabsView = (ViewGroup)root.findViewById(android.R.id.tabs);
    View tabView = tabDefinition.createTabView(inflater, tabsView);

    TabSpec tabSpec = tabHost.newTabSpec(tabDefinition.getId());
    tabSpec.setIndicator(tabView);
    tabSpec.setContent(tabDefinition.getTabContentViewId());
    return tabSpec;
  }

  /**
  * Called when switching between tabs.
  * @param tabId The unique identifier for the tab.
  * @param fragment The {@link Fragment} to swap in for the tab.
  * @param containerId The layout ID for the {@link View} that houses the tab's content.
  */
  private void updateTab(String tabId, Fragment fragment, int containerId) {
    final FragmentManager manager = getFragmentManager();
    if (manager.findFragmentByTag(tabId) == null) {
      manager.beginTransaction()
        .replace(containerId, fragment, tabId)
        .commit();
    }
  }
}

And that’s it! Just four classes in total, and one of them (MainActivity) was almost a freebee!

Putting It All Together

Let’s recap on all of the various pieces that we’ve seen in this example. First, we started with the various layouts that we’d need. Our one and only activity is pretty bare bones. It’s going to contain our tabs fragment view. The tabs fragment view is responsible for containing the individual tabs a user clicks on as well as the content that gets displayed for each tab. We also added a layout for really simplistic tab views that only really contain a TextView that shows the tab’s title.

From there, we were able to look at the classes that would back up the views. To use our fragment implementation, we only had to modify our parent class of our only activity. I opted to create some classes that define tab functionality to make extending the UI a bit easier, and adding additional child classes that fit in this pattern is simple. The TabsFragment class was the most complicated part of our implementation, and truth be told, that’s where most of the logic resides. This class was responsible for defining the tabs we wanted to show, and what fragments we would swap in when each tab was clicked.

In order to extend this even more, the things you’ll want to consider are:

  • Defining your own type of tab definition classes. Maybe you want to look at graphical tabs, or something more complicated than just a title.
  • Implementing your own fragment classes that you display when your tabs are clicked. In the example, the contents of the tabs are empty! This is definitely something you’ll want to extend upon.
  • Adding more tabs! Maybe you need three or four tabs instead of two.

Summary

Fragments in Android really aren’t all that complicated. As a new Android developer or transitioning from the pre-API level 11 days, they might seem a bit odd. Hopefully after you try out this example they’re a lot more clear. Hopefully by following along with this tutorial you found that you were easily able to set up a tabbed user interface in Android and get a basic understanding for how fragments work.

Source and Downloads

I like being able to provide the source in as many formats as possible… so here we go:

Update: The actual application is available on the Google Play store.


Lead by Example and Emulate Ideal

Lead by Example and Emulate Ideal (Image by http://www.sxc.hu/)

Background

Leadership has become a big focus for me as I start to grow more into my role at Magnet Forensics. As a developer, I feel like it’s easy to gain basic knowledge and experience with unfamiliar programming territory just by surfing The Internet. With leadership, that’s certainly not the case for me.

What’s my most recent realization? Lead by example if you expect anyone to take you seriously. As a young leader (and with little professional experience in a leadership role), I think this becomes especially important. When you lead by example, you’re showing others that you’re really behind what you’re preaching.

Lead by Example: A Simple How-to

Maybe it’s obvious, but I really don’t think I’m over simplifying my message when I say it. To lead by example, you just do what you expect other people to do. Obvious, right? If you’ve been working for long enough, you’ve probably had a boss that you thought was doing a poor job. There’s many reasons for this, and I don’t want to turn this into a negative-dwelling-unhappy-rant party, but one such reason is it felt like they were just passing down orders to you.

What’s more disengaging than having someone that’s locked up in a room come out every couple of hours to assign you a new task? This boss of yours was doing a poor job of demonstrating meaning to you. Why was doing what he or she was telling you to do was the right thing-the thing that’s going to help get the company to the next step? He or she was not using what I would now call leadership rule #1: lead by example.

Okay. So you’ve envisioned the times when it sucked. We’re off to a good start, because hopefully things can only look up from here. What would you have done differently if you were in your old boss’s shoes and you wanted to inspire an alternate-universe-you to do a good job? There’s probably a handful of things you can think of (and for certain people with certain bosses, maybe that handful is multiple gorilla-sized handfuls).

What if your boss, your manager, or your leader had actually sat down with you and guided you through their expectations? What if the first time through a particular task you sat together and worked through it as a team? What if there was nothing left unclear and you could truly get behind what you were being told? I’m sure you wouldn’t feel resentful of the almighty boss throwing down orders like lightning bolts from the heavens if that was the case.

But why? Here are a few reasons:

  • The clarity of expectations becomes established. There’s a lot less guessing work. Being able to establish clear expectations at work is key to building trust and having successful teams.
  • You buy in. When someone can lead by example, they’re proving to you why they value something. It’s a lot easier to get behind them compared to someone else who has never proved their knowledge, skills, or experience to you.
  • It becomes more like a peer relationship when receiving work. Initially, you feel like you’re shadowing someone that you can more easily relate to. When it comes time to take the reins, you don’t feel like you’re pulling your manager in a carriage behind you.

Emulate Ideal

As a leader, you’d be shocked if you realized just how much of an effect you have on other people. You don’t have to be the CEO or manage 100 teams of 100 people to have the influence either. The even more surprising part? A lot of your influence is actually not a conscious effort on your part. Boom.

The reason I’m suggesting that as a leader you should be emulating ideal is because people will pick up on it. People see how you act, whether good or bad, and will learn to emulate your own behavior. If you’re a hard worker who gets things done, your teammates will learn that that’s what drives the team’s success. If you’re always putting down people’s work, then it will be the norm for nobody to really have an appreciation for the work of others. If you’re watching YouTube and surfing the net all day, that’s now acceptable behavior for everyone else. Repeatedly show up late for or flake out on meetings? Don’t be surprised if meetings become less effective. Constantly encouraging people and acknowledging their successes? You’ll start to see others praising each other. These might be generalizations of course, but if everything else is aligned I’m sure you’ll see these kinds of trends.

This truly is often overlooked. Once you’ve gained respect from people and you have their attention, your actions will have a big impact. So now instead of expecting your team members to act in accordance of what you think is ideal, why not live it out yourself? They’ll automatically start making the transition, especially if you’ve clearly communicated your expectations to them.

Summary

You get the most buy in from others when you lead by example, and you’ll become much more effective as a manager or leader. You have your own expectations of what ideal is, so it’s important to communicate them with your team (Side note: expectations go both ways. Make sure your team’s expectations of an ideal leader are properly communicated to you). One of the best ways you can communicate your expectations through leading by example regularly, and you drive the point home by emulating your definition of ideal.

Extras

If you’re looking for a bit more on how and why to lead by example, consider these links:


Dynamic Programming with Python and C#

Dynamic Coding with C# and Python

Dynamic Code: Background

Previously, I was expressing how excited I was when I discovered Python, C#, and Visual Studio integration. I wanted to save a couple examples regarding dynamic code for a follow up article… and here it is! (And yes… there is code you can copy and paste or download).

What does it mean to be dynamic? As with most things, wikipedia provides a great start. Essentially, much of the work done for type checking and signatures is performed at runtime for a dynamic language. This could mean that you can write code that calls a non-existent method and you wont get any compilation errors. However, once execution hits that line of code, you might get an exception thrown. This Stack Overflow post’s top answer does a great job of explaining it as well, so I’d recommend checking that out if you need a bit more clarification. So we have statically bound and dynamic languages. Great stuff!

So does that mean Python is dynamic? What about C#?

Well Python is certainly dynamic. The code is interpreted and functions and types are verified at run time. You won’t know about type exceptions or missing method exceptions until you go to execute the code. For what it’s worth, this isn’t to be confused with a loosely typed language. Ol’ faithful Stack Overflow has another great answer about this. The type of the variable is determined at runtime, but the variable type doesn’t magically change. If you set a variable to be an integer, it will be an integer. If you set it immediately after to be a string, it will be a string. (Dynamic, but strongly typed!)

As for C#, in C# 4 the dynamic keyword was introduced. By using the dynamic keyword, you can essentially get similar behaviour to Python. If you declare a variable of type dynamic, it will take on the type of whatever you assign to it. If I assign a string value to my dynamic variable, it will be a string. I can’t perform operations like pre/post increment (++) on the variable when it’s been assigned a string value without getting an exception. If I assign an integer value immediately after having assigned a string value, my variable will take on the integer type and my numeric operators become available.

Where does this get us with C# and Python working together then?

Example 1: A Simple Class

After trying to get some functions to execute between C# and Python, I thought I needed to take it to the next level. I know I can declare classes in Python, but how does that look when I want to access it from C#? Am I limited to only calling functions from Python with no concept of classes?

The answer to the last question is no. Most definitely not. You can do some pretty awesome things with IronPython. In this example, I wanted to show how I can instantiate an instance of a class defined within a Python script from C#. This script doesn’t have to be created in code (you can use an external file), so if you need more clarification on this check out my last Python/C# posting, but I chose to do it this way to have all the code in one spot. I figured it might be easier to show for an example.

We’ll be defining a class in Python called “MyClass” (I know, I’m not very creative, am I?). It’s going to have a single method on it called “go” that will take one input parameter and print it to the console. It’s also going to return the input string so that we can consume it in C# and use it to validate that things are actually going as planned. Here’s the code:

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Scripting.Hosting;

using IronPython.Hosting;

namespace DynamicScript
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            Console.WriteLine("Enter the text you would like the script to print!");
            var input = Console.ReadLine();

            var script =
                "class MyClass:\r\n" +
                "    def __init__(self):\r\n" +
                "        pass\r\n" +
                "    def go(self, input):\r\n" +
                "        print('From dynamic python: ' + input)\r\n" +
                "        return input";

            try
            {
                var engine = Python.CreateEngine();
                var scope = engine.CreateScope();
                var ops = engine.Operations;

                engine.Execute(script, scope);
                var pythonType = scope.GetVariable("MyClass");
                dynamic instance = ops.CreateInstance(pythonType);
                var value = instance.go(input);

                if (!input.Equals(value))
                {
                    throw new InvalidOperationException("Odd... The return value wasn't the same as what we input!");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Oops! There was an exception while running the script: " + ex.Message);
            }

            Console.WriteLine("Press enter to exit...");
            Console.ReadLine();
        }
    }
}

Not too bad, right? The first block of code just takes some user input. It’s what we’re going to have our Python script output to the console. The next chunk of code is our Python script declaration. As I said, this script can be loaded from an external file and doesn’t necessarily have to exist entirely within our C# code files.

Within our try block, we’re going to setup our Python engine and “execute” our script. From there, we can ask Python for the type definition of “MyClass” and then ask the engine to create a new instance of it. Here’s where the magic happens though! How can we declare our variable type in C# if Python actually has the variable declaration? Well, we don’t have to worry about it! If we make it the dynamic type, then our variable will take on whatever type is assigned to it. In this case, it will be of type “MyClass”.

Afterwards, I use the return value from calling “go” so that we can verify the variable we passed in is the same as what we got back out… and it definitely is! Our C# string was passed into a Python function on a custom Python class and spat back out to C# just as it went in. How cool is that?

Some food for thought:

  • What happens if we change the C# code to call “go1” instead of “go”? Do we expect it to work? If it’s not supposed to work, will it fail at compile time or runtime?
  • Notice how our Python method “go” doesn’t have any type parameters specified for the argument “input”? How and why does all of this work then?!

Example 2: Dynamically Adding Properties

I was pretty excited after getting the first example working. This meant I’d be able to create my own types in Python and then leverage them directly in C#. Pretty fancy stuff. I didn’t want to stop there though. The dynamic keyword is still new to me, and so is integrating Python and C#. What more could I do?

Well, I remembered something from my earlier Python days about dynamically modifying types at run-time. To give you an example, in C# if I declare a class with method X and property Y, instances of this class are always going to have method X and property Y. In Python, I have the ability to dynamically add a property to my class. This means that if I create a Python class that has method X but is missing property Y, at runtime I can go right ahead and add property Y. That’s some pretty powerful stuff right there. Now I don’t know of any situations off the top of my head where this would be really beneficial, but the fact that it’s doable had me really interested.

So if Python lets me modify methods and properties available to instances of my type at runtime, how does C# handle this? Does the dynamic keyword support this kind of stuff?

You bet. Here’s the code for my sample application:

using System;
using System.Collections.Generic;
using System.Text;

using Microsoft.CSharp.RuntimeBinder;

using IronPython.Hosting;

namespace DynamicClass
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            Console.WriteLine("Press enter to read the value of 'MyProperty' from a Python object before we actually add the dynamic property.");
            Console.ReadLine();

            // this script was taken from this blog post:
            // http://znasibov.info/blog/html/2010/03/10/python-classes-dynamic-properties.html
            var script =
                "class Properties(object):\r\n" +
                "    def add_property(self, name, value):\r\n" +
                "        # create local fget and fset functions\r\n" +
                "        fget = lambda self: self._get_property(name)\r\n" +
                "        fset = lambda self, value: self._set_property(name, value)\r\n" +
                "\r\n" +
                "        # add property to self\r\n" +
                "        setattr(self.__class__, name, property(fget, fset))\r\n" +
                "        # add corresponding local variable\r\n" +
                "        setattr(self, '_' + name, value)\r\n" +
                "\r\n" +
                "    def _set_property(self, name, value):\r\n" +
                "        setattr(self, '_' + name, value)\r\n" +
                "\r\n" +
                "    def _get_property(self, name):\r\n" +
                "        return getattr(self, '_' + name)\r\n";

            try
            {
                var engine = Python.CreateEngine();
                var scope = engine.CreateScope();
                var ops = engine.Operations;

                engine.Execute(script, scope);
                var pythonType = scope.GetVariable("Properties");
                dynamic instance = ops.CreateInstance(pythonType);

                try
                {
                    Console.WriteLine(instance.MyProperty);
                    throw new InvalidOperationException("This class doesn't have the property we want, so this should be impossible!");
                }
                catch (RuntimeBinderException)
                {
                    Console.WriteLine("We got the exception as expected!");
                }

                Console.WriteLine();
                Console.WriteLine("Press enter to add the property 'MyProperty' to our Python object and then try to read the value.");
                Console.ReadLine();

                instance.add_property("MyProperty", "Expected value of MyProperty!");
                Console.WriteLine(instance.MyProperty);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Oops! There was an exception while running the script: " + ex.Message);
            }

            Console.WriteLine("Press enter to exit...");
            Console.ReadLine();
        }
    }
}

Let’s start by comparing this to the first example, because some parts of the code are similar. We start off my telling  the user what’s going to happen and wait for them to press enter. Nothing special here. Next, we declare our Python script (again, you can have this as an external file) which I pulled form this blog. It was one of the first hits when searching for dynamically adding properties to classes in Python, and despite having limited Python knowledge, it worked exactly as I had hoped. So thank you, Zaur Nasibov.

Inside our try block, we have the Python engine creation just like our first example. We execute our script right after too and create an instance of our type defined in Python. Again, this is all just like the first example so far. At this point, we have a reference in C# to a type declared in Python called “Properties”. I then try to print to the console the value stored inside my instances property called “MyProperty”. If you were paying attention to what’s written in the code, you’ll notice we don’t have a property called “MyProperty”! Doh! Obviously that’s going to throw an exception, so I show that in the code as well.

So where does that leave us then? Well, let’s add the property “MyProperty” ourselves! Once we add it, we should be able to ask our C# instance for the value of “MyProperty”. And… voila!

Some food for thought:

  • When we added our property in Python, we never specified a type. What would happen if we tried to increment “MyProperty” after we added it? What would happen if we tried to assign an integer value of 4 to “MyProperty”?
  • When might it be useful to have types in C# dynamically get new methods or properties?

Summary

With this post, we’re still just scratching the surface of what’s doable when integrating Python and C#. Historically, these languages have been viewed as very different where C# is statically bound and Python is a dynamic language. However, it’s pretty clear with a bit of IronPython magic that we can quite easily marry the two languages together. Using the “dynamic” keyword within C# really lets us get away with a lot!

Source code for these projects is available at the following locations:


Events: Demystifying Common Memory Leaks

Events: Demystifying Common Memory Leaks

Background

If you’ve poked through my previous postings, you’ll probably notice that I love using events when I program. If I can find a reason to use an event, I probably will. I think they’re a great tool that can really help you with designing your architectures, but there are certainly some common problems people run into when they use events. The one I want to address today has to do with memory leaks. That’s right. I said it. Memory leaks in your .NET application. Just because it’s a managed language doesn’t mean your code can’t be leaking memory! And now that I’ve got your attention, let’s see how events might be causing some leakage in your application.

(There is source that you can download and run. Check the summary section at the end!)

Instance-Scope Event Handlers

One of the most common ways to set up an EventHandler in C# is by having them defined for the entire scope of the instance. Consider for a moment the form designer in Visual Studio. When you double click on controls you get some handler created for the default event on that control. See how the EventHandler was declared though? You get a method declared that has a sender and some type of EventArgs. Pretty standard stuff here and there’s nothing ground-breaking about it. So what’s the problem with this method?

Well, there’s nothing wrong with it as long as you know how to clean up after yourself. Consider the following two classes:


private class ObjectWithEvent
{
    ~ObjectWithEvent()
    {
        Console.WriteLine(this + " is being finalized.");
    }

    public event EventHandler<EventArgs> Event;

    public void UnhookAll()
    {
        Event = null;
    }
}

private class ObjectThatHooksEvent
{
    public ObjectThatHooksEvent(ObjectWithEvent objectWithEvent)
    {
        objectWithEvent.Event += ObjectWithEvent_Event;
    }

    ~ObjectThatHooksEvent()
    {
        Console.WriteLine(this + " is being finalized.");
    }

    private void ObjectWithEvent_Event(object sender, EventArgs e)
    {
        // some fancy event
    }
}

The first class has an event that our second class can hook onto. You’ll notice in the second class that I’ve defined an instance-scope handler that we can hook up. This is the exact same syntax for declaring an event handler that you’d get from the form designer if you’re doing GUI programming.

The danger with this setup is that until you unhook the event, the object that hooks onto the event will not be freed. “Well, no problem!” is what you might be thinking. You know how to solve that. You can just unhook the event in the second class’s finalizer/deconstructor.

…Except that won’t work. The finalizer will not get called on the instance of the second class until the event has been unhooked! It’s a bit of a chicken-or-the-egg problem, but it makes sense. A finalizer will only be called when the reference is being cleaned up, but the instance can’t be marked for cleaning because something is still using its event handler. See why this can get a bit dangerous?

Anonymous Delegate (No Parent Reference)

So this is an example of hooking events where you won’t get a leak. Why am I showing it? Well, in the next section I’ll make a small tweak to it which will make it behave just like the first scenario I described.

Let’s assume we have two classes again. I’ll use the first class from my first example (the object with the event) and this new class here that we’ll use to hook onto the event:

private class HookWithAnonymousDelegate
{
    public HookWithAnonymousDelegate(ObjectWithEvent objectWithEvent)
    {
        objectWithEvent.Event += (sender, args) =>
        {
            // handle your event
            // (this one is special because it doesn't use anything related to the instance)
            Console.WriteLine("Event being called!");
        };
    }

    ~HookWithAnonymousDelegate()
    {
        Console.WriteLine(this + " is being finalized.");
    }
}

Notice the difference from the first example? I’ve hooked up an anonymous method (using a lambda expression) to our event instead of declaring an instance-scope event handler. It’s a small change, and for the most part, I might argue that this is just a stylistic thing. If you don’t ever plan on unhooking the event then it’s not such a big deal to go with anonymous methods, but if your method body grows pretty big the code can definitely get unsightly.

Anyway… sweet! We just hooked up to our event and we don’t have the scary leak situation that we did in the first scenario. How cool is that? Well…

Anonymous Delegate (With Parent Reference)

The second method I described works great… until you go to put it into practice. It’s clearly not an impossible situation, but it’s pretty unlikely that you’ll write event handlers within an object that don’t use any of that object’s state (or even other methods on the object). Again, not impossible but just not the common use case. And since it’s not the common use case, you need to be concerned with the potentially problematic common use case 🙂

Let’s consider two classes (yes, again, two classes). We’ll use the first class I described above in both examples that has an event that we can hook onto, and a second class that looks similar to the class I introduced in the second example:

private class HookWithAnonymousDelegate2
{
    public HookWithAnonymousDelegate2(ObjectWithEvent objectWithEvent)
    {
        objectWithEvent.Event += (sender, args) =>
        {
            // handle your event and use something that's part of this instance
            SomeInnocentLittleMethod();
        };
    }

    ~HookWithAnonymousDelegate2()
    {
        Console.WriteLine(this + " is being finalized.");
    }

    private void SomeInnocentLittleMethod()
    {
        Console.WriteLine("... Not so innocent after all!");
    }
}

See the difference compared to example 2? The event handler in this class calls an instance method. This would be a pretty common thing to do (unless you like to duplicate all of your code and not use methods ever :P) and it doesn’t look like it should cause problems. And really, it won’t if you understand the implications of hooking an event handler up to an event. So once you’re done handling your events, make sure you clean up and remove your handlers!

In my opinion, the really interesting part of this example is that the event handler is only calling an instance method. It’s not even using any variables or properties of the instance. Still, the .NET framework is going to hold onto this second instance until we unhook.

Summary

Well, hopefully I haven’t scared you away from using events. The take-away point here is that you need to be mindful of hooking up your events and when/where you unhook them. Personally, unless you always plan to have two objects exist for the same lifetime, I wouldn’t hook up events in the constructors like I’ve done in my examples. Some closing tips:

  • Try only hooking onto events when you need to. If you don’t need to hook up all your events when initializing something, then don’t!
  • Be mindful of how you’re going to clean up your event hooking. Whenever you add an event handler, try to think of where you’ll be cleaning it up.
  • Hooking events onto singletons or global instances can make this problem a lot worse. Since your singleton will be around for the lifetime of your application, if you forget to unhook from your event then you’ll start accumulating a lot of garbage.

I’ve written up a little sample application that uses the example classes and walks you through the three examples I’ve outlined. All of them involve instantiating the classes, hooking up the events, and then how they behave differently when you try to clean them up. You can grab the source code from:

Hope you enjoyed! Remember to follow Dev Leader:


Simple Way To Structure Threads For Control

Background

I’ve previously discussed the differences between the BackgroundWorker and Thread classes, but I figured it would be useful to touch on some code. I’d like to share the pattern I commonly use when creating threads in C# and discuss some of the highlights.

The Single Thread

I like to use this design when I have a single thread I need to run and in the context of my object responsible for running the thread, I do mean having a single thread. Of course, you could have your object in control of multiple threads as long as you repeat this design pattern for each of them.

Here’s the interface that I’ll be using for all of the examples:

    internal interface IThreadRunner
    {
        #region Exposed Members

        void Start();

        void Stop();

        #endregion 
    }

Behold!

    internal class SingleThreadRunner : IThreadRunner
    {
        #region Fields

        private readonly object _threadLock;
        private readonly AutoResetEvent _trigger;
        private Thread _theOneThread;

        #endregion

        #region Constructors

        /// 
        /// Prevents a default instance of the class from being created.
        /// 
        private SingleThreadRunner()
        {
            _threadLock = new object();
            _trigger = new AutoResetEvent(false);
        }

        #endregion

        #region Exposed Members

        public static IThreadRunner Create()
        {
            return new SingleThreadRunner();
        }

        public void Start()
        {
            lock (_threadLock)
            {
                // check if already running
                if (_theOneThread != null)
                {
                    return;
                }

                _theOneThread = new Thread(DoWork);
                _theOneThread.Name = "The One Thread";
                _theOneThread.Start(_trigger);
            }
        }

        public void Stop()
        {
            lock (_threadLock)
            {
                // check if not running
                if (_theOneThread == null)
                {
                    return;
                }

                _theOneThread = null;
                _trigger.Set();
            }
        }

        #endregion

        #region Internal Members

        private void DoWork(object parameter)
        {
            var currentThread = Thread.CurrentThread;

            // this was the trigger that we passed in. elesewhere in the 
            // instance, we can use this object to wake up the thread.
            var trigger = (AutoResetEvent)parameter;

            try
            {
                // keep running while we're expected to be running
                while (currentThread == _theOneThread)
                {
                    // DO ALL SORTS OF AWESOME WORK HERE.
                    Console.WriteLine("Awesome work being done.");

                    // put this thread to sleep, but remember it can be woken 
                    // up from other places in this instance.
                    trigger.WaitOne(1000);
                }
            }
            finally
            {
                lock (_threadLock)
                {
                    // if we were still expected to be running, change the 
                    // state to suggest that we're not
                    if (_theOneThread == currentThread)
                    {
                        _theOneThread = null;
                    }
                }
            }
        }

        #endregion
    }

This design was taken from some Java programming I had done in a previous life. Essentially, I have a thread that is responsible for doing some work in a loop. It could be anything… Periodically polling for some data, a work dequeing thread, a random-cursor-moving thread… Anything! The point is, you only want one of these suckers hanging around. How is this accomplished?

Leveraging the instance variable that marks the one expected running thread is key here. Whenever this thread checks if it should still be running, if the current thread doesn’t match what’s assigned to the instance variable then it needs to stop! This means you could potentially spawn off two of these threads, and if you set the instance variable to one of the two, then the other one should kill itself off! Pretty neat.

By using the reset event, we can actually interrupt this thread if it’s sleeping. This is great if we have a thread that periodically wakes up to do some work but we want to stop it and have it stop fast. We simple set our instance variable for the thread to be null and then set this thread’s reset event to ensure it get’s woken up. Presto! It wakes up, checks the condition, and realizes it needs to exit the loop.

Simple.

The Handful of Threads

This design is almost identical to the single thread design above. I use it primarily when I want to have an object responsible for a bunch of threads that are turned on/off under the same conditions. The major difference between the two designs? In the single thread scenario, we check that our current thread is still set to be the one instance. In this design, we need all of our threads to be checking against the same state object which is not going to be a single thread instance.

Let’s have a peek:

    internal class GroupThreadRunner : IThreadRunner
    {
        #region Fields

        private readonly object _threadLock;
        private readonly Dictionary<Thread, AutoResetEvent> _triggers;

        private bool _running;

        #endregion

        #region Constructors

        /// 
        /// Prevents a default instance of the class from being created.
        /// 
        private GroupThreadRunner()
        {
            _threadLock = new object();
            _triggers = new Dictionary<Thread, AutoResetEvent>();
        }

        #endregion

        #region Exposed Members

        public static IThreadRunner Create()
        {
            return new GroupThreadRunner();
        }

        public void Start()
        {
            lock (_threadLock)
            {
                // check if any are already running
                if (_triggers.Count > 0)
                {
                    return;
                }

                _running = true;

                const int NUMBER_OF_THREADS = 4;
                for (int i = 0; i < NUMBER_OF_THREADS; ++i)
                {
                    var thread = new Thread(DoWork);
                    thread.Name = "Thread " + i;

                    var trigger = new AutoResetEvent(false);
                    _triggers[thread] = trigger;

                    thread.Start(trigger);
                }
            }
        }

        public void Stop()
        {
            lock (_threadLock)
            {
                // check if not running
                if (_triggers.Count <= 0)
                {
                    return;
                }

                _running = false;
                foreach (var trigger in _triggers.Values)
                {
                    trigger.Set();
                }
            }
        }

        #endregion

        #region Internal Members

        private void DoWork(object parameter)
        {
            var currentThread = Thread.CurrentThread;

            // this was the trigger that we passed in. elesewhere in the 
            // instance, we can use this object to wake up the thread.
            var trigger = (AutoResetEvent)parameter;

            try
            {
                // keep running while we're expected to be running
                while (_running)
                {
                    // DO ALL SORTS OF AWESOME WORK HERE.
                    Console.WriteLine("Awesome work being done by " + currentThread.Name);

                    // put this thread to sleep, but remember it can be woken 
                    // up from other places in this instance.
                    trigger.WaitOne(1000);
                }
            }
            finally
            {
                lock (_threadLock)
                {
                    _triggers.Remove(currentThread);

                    // if we were still expected to be running, change the 
                    // state to suggest that we're not
                    if (_running && _triggers.Count <= 0)
                    {
                        _running = false;
                    }
                }
            }
        }

        #endregion
    }

Summary

The above patterns I discussed cover my common usage for threads: Instances that have reoccurring work over long periods of time. Both patterns are very similar and only have slight modifications to make them support one instance or many thread instances running. If you have one unique thread or many threads… there’s a pattern for you!

Check out a full working example of this code over here.


  • Nick Cosentino

    Nick Cosentino

    I work as a team lead of software engineering at Magnet Forensics (http://www.magnetforensics.com). I'm into powerlifting, bodybuilding, and blogging about leadership/development topics over at http://www.devleader.ca.

    Verified Services

    View Full Profile →

  • Copyright © 1996-2010 Dev Leader. All rights reserved.
    Jarrah theme by Templates Next | Powered by WordPress