CAUBLESTONE INK

.net development and other geeky stuff

Application Helpers: Protect your method calls

Posted on January 26th, 2009


First thing, refactor, refactor, refactor. Most ideas come from refactoring of your code. It’s amazing how much you do when you start refactoring things. The big benefit of course is less code. If you have a couple hundred thousand lines of code or even ten thousand lines of code, refactoring even a small thing can cut down your code base and improve readability. This article is geared towards refactoring.

In the course of working on multiple applications over the years you find you tend to do the same things over and over again. One of those things is constantly checking objects for null, data type compatibility, etc. How many times have you written the following lines of code.

if (object == null)
{
   throw new ArgumentNullException();
}

or

if (object.GetType() == typeof(sometype))

The amount of code there justs adds up. Not only that but you probably have lots of null checks maybe even in the same method. So what if we wrote something like this instead:

Protect.IsNotNull(obj, "The object you are checking is null");

So if you had multiple objects going into an object you would have something like this:

Protect.IsNotNull(obj1, "Object 1 is null");
Protect.IsNotNull(obj2, "Object 2 is null");

Now since we are talking about refactoring what if we even refactor that code to make use of the newer features of the framework. Since the Protect methods throw an exception if the object is null in this case what if we wanted to expand it to allow for multiple checks. We could do something like this:

Protect.Against(obj1 == null, "Object 1 is null");
Protect.Against(String.IsNullOrEmpty(stringData), "The string is emtpy.");

As you can see we can now handle multiple things at the same time. So let’s look at what is under the Protect method.

public static class Protect
{
  public static void Against(bool condition, string message) where T: Exception
  {
    if (condition)
      throw new (T)Activator.CreateInstance(typeof(T), message);
  }
}

As you can see not much but it makes your code easier to read and it adds a nice bit of conformity while reducing the total lines you need to maintain and worry about. The T parameter is the type of exception you want thrown based on your condition. As long as you have a boolean condition your good. Anything that evaluates to true will throw the exception. The message will be on the exception that is thrown. Based on this pattern we can also add things like Inheritance checks, Type checks, Enum, checks, etc. It’s really easy for it to morph into what you need as you need it. You can even extend it with delegates, Func<> methods, setup for linq style syntax, etc. the sky is the limit.

Here is what it would look like in use inside of a method:

public void DoSomething(List data, Dictionary other)
{
    Protect.Against(data == null, "Data is null");
    Protect.Against(other==null, "Other is null");

    foreach (int i in data)
    {
        Console.WriteLine(other[i]);
     }
}
kick it on DotNetKicks.com

Introduction to the Circuit Breaker pattern

Posted on March 6th, 2008


Download the code (14kb)

I was reading the book Release It! about a month ago and ran across this pattern for creating code that has the ability to essentially shut itself off.  It just so happens that I had a use for this type of process and it helped me to create my final design.  What I was working on was a component that used a third party webservice for batch processing.  In this batch we would send over anywhere from 50-1500 web request one right after the other.  As such if we had any problems on the service end we could have thrown 1500 or even more error messages depending on how it was coded.  Of course we did not want that as it could potentially cause even worse problems by letting our app continue to try and process our data even if the service was down.  So instead of needlessly killing each of our apps I took a queue from the book and implemented the circuit breaker pattern. 

Now you might ask what is the circuit breaker pattern?  Well lets take a look at a real world scenario that everybody is familiar with.  Every home today has a main power box that is the central point at which power enters the home.  Now depending on how old the home is you could either have circuit breakers, fuses, or even worse a piece of metal jammed between the connections (I’d hope not).  Now fuses and circuit breakers all work the same way and for the same reason, to regulate the amount of load that is allowed over the electrical wire.  This is important because if there were no limit then it would cause an electrical short somewhere and possibly a fire.  It happened a lot before the fuse was created.  So, the use of a fuse or circuit breaker is meant to make sure we don’t put too much of a load on the circuit or wire.  Once a threshold is met then the circuit is tripped or the fuse is blown.  Thus stopping the flow of power.  Now if we look at our code base we want the same thing to occur.  So if I were to start sending records to the service in question and they start constantly failing as long as we have setup a threshold for error counts or failures we can then trip our circuit so to say and stop the flow of data to this service. 

Well you might ask how can we do this?  In our code bases is really not all that difficult to implement once you get the concept down.  So let’s look at some code to create a small example application.  Now you don’t have to create an interface but I wanted to really show what you need to do to add this functionality to your existing code.

public interface ICircuitBreaker
{
    void BreakCircuit();
    void ResetCircuit();
    bool CircuitBroken { get; set; }
    int Threshold { get; set; }
}

Next I’m going to embed an entire class with the interface implemented.  To show how this works I have created a class that writes to a file.  If there is a problem writing to the file for a specified number of tries then it will fail gracefully vs throwing an exception.

public class FileWriterWithCB : ICircuitBreaker
  {
    private bool _circuitBroken;
    private int _threshold;
    private string _fileName;
    private int _batchSize;

    public FileWriterWithCB()
    {
      this._circuitBroken = false;
      this._threshold = 5;
      this._fileName = "CBTest.txt";
      this._batchSize = 50;
    }

    public string FileName
    {
      get { return this._fileName; }
    }

    public int BatchSize
    {
      get { return this._batchSize; }
      set { this._batchSize = value; }
    }

    public void WriteToFile()
    {
      FileStream fs = new FileStream(this._fileName, FileMode.Open, FileAccess.ReadWrite);

      StreamWriter sw = new StreamWriter(fs);

      string data = "This is a test file write";

      sw.Write(data);

      sw.Flush();
      sw.Close();
      fs.Flush();
      fs.Close();

      sw = null;
      fs = null;
    }

    public void RunBatchWithCircuitBreaker()
    {
      int failureCount = 1;

      for (int x = 0; x &lt;= this._batchSize; x++)
      {
        if (failureCount &gt; this._threshold)
        {
          Console.WriteLine("Threshold reached breaking circuit.");
          this.BreakCircuit();
        }
        if (this.CircuitBroken)
        {
          Console.WriteLine("Circuit is Broken exiting code loop.");
          return;
        }

        try
        {
          // This should throw a FileNotFound Exception
          this.WriteToFile();
        }
        catch (Exception ex)
        {
          failureCount++;
          // Just write to the console to show that it is throwing the errors.
          Console.WriteLine(ex.Message);
        }

      }

    }

    #region ICircuitBreaker Members

    public void BreakCircuit()
    {
      Console.WriteLine("Circuit is being broken.");
      this._circuitBroken = true;
    }

    public void ResetCircuit()
    {
      Console.WriteLine("Circuit is being reset.");
      this._circuitBroken = false;
    }

    public bool CircuitBroken
    {
      get
      {
        return this._circuitBroken;
      }
      set
      {
        this._circuitBroken = value;
      }
    }

    public int Threshold
    {
      get
      {
        return this._threshold;
      }
      set
      {
        this._threshold = value;
      }
    }

    #endregion
  }

Ok, so let’s look at what this is doing.  First the class is used to write to a file.  There are two methods to write to the file.  One is a single write only the other is a batch writer for us to show the use of the circuit breaker pattern.  By default we set the system to perform 50 writes and the threshold is 5 errors, at which point we would expect the circuit to be proverbial broken.  In the attached code you will find a unit test that you can run to see the results for yourself. Needless to say when you run the codebase you should see that there are five errors thrown at which point the codebase effectively shuts down.  Try playing with the threshold.

Overall the pattern shown here can be very effective in integration scenarios but it’s especially effective in batch processes.  In the integration scenario you could have your app try to connect to say an external service and if it fails you want it to return a specified value vs crashing or throwing an exception.  This can be easily accomplished by adjusting how you use the circuit breaker.  All you would need to do is set your boolean variable if your external service is down.

kick it on DotNetKicks.com

Join the Darkside…

Posted on January 19th, 2008


Not that long ago I saw a post on one of the blogs out there about joining the DarkSide for Visual Studio.  I’m proud to say that I’ve been a Dark Sider now for over 10 years…  Yeah I know that’s before Visual Studio.net.  Prior to that I did a lot of VB and VBA work and I used a dark color scheme there as well.  Listed below is a screenshot of my dark scheme.  Which you can also get here for VS2005.  The font I am using here is the BitStream Vera Sans Mono which you can get here.

So come on over to the darkside and give us a try. :)

kick it on DotNetKicks.com

Book Review: Release It!: Design and Deploy Production-Ready Software

Posted on January 17th, 2008


After reading on several blogs that this was a book worth getting I decided to get myself a copy. I will say that this is a great book and that it should be on every programmer’s bookshelf. This is right up there with Code Complete. If you have not already gotten a copy you should do so.

When it comes to technical books I like to only purchase books that I will continue to use over the years vs ones that are very targeted and will go out of date. Thus architectural books are a prime candidate for purchase. However knowing which to buy can be daunting. After all who wants to plop down $50 or more for a book that might only have 1 or 2 good chapters in it or is a rehash of books you already have. That’s where these reviews come in. I picked up this book based on reviews on other blogs and I was not disappointed. While the information in the book is presented by an obvious Java programmer it in no ways is tied to Java programming. It provides insight into several projects from the real world and things that they learned from them. As such it is more of a best practices book vs a code book. From Anti-Patterns to Patterns it walks you through various scenarios and things to watch out for when developing release ready software.

After reading the book myself I was able to make changes to the way I was coding my components to take advantage of these patterns. By making use of this pattern I was able to take a service interface layer and change it such that the application using it would not crash from this component as it had done in the past. I was able to accomplish this by using the circuit breaker pattern that he describes in his book. Basically what it does is very much what you would expect. Just like in a home if you plug too many items into your outlet and it overloads the circuit it throws the breaker so you don’t burn your house down. So in code what this does it allows you to implement your code such that if you run into problems it can shut down the interface or process without taking down your application with it. After all who wants to crash their application or website because an integration point is down or broken.

There are quite a few other patterns some of which I have already taken advantage of like the Fail Fast pattern. I can honestly say that after reading this book almost any developer should be able to walk away a better programmer and will most likely start to use some of the patterns presented in this book. I know I have.

All in all this was an excellent book and it was written very well and not all that expensive. If you would like to see a more in-depth review see this blog post, Ayende’s Blog.
This book should be on every developer’s bookshelf. Get it now. You can get it here: Release It

kick it on DotNetKicks.com

Tip: Open a .Net Command Prompt Here

Posted on December 21st, 2006


Download (1k)

If you find you want to open a command prompt on a certain folder and have access to all the underlying Visual Studio.Net <your version here> options this is for you.

This is based on similar updates to your windows system in which you can add a new option to your right-click context menu inside of your explorer windows. What this particular tip does is shows you how to add a item to your menu that will open a VS.Net 2003 command prompt on the specified folder, however you follow the same procedure for all versions of visual studio.

Note: This involves updating the registry. You should always backup your registry before making manual changes as your changes could make your system unstable. If you are not comfortable with doing these types of changes you should pass on this tip.

Following the steps below:

1. Open regedit.exe
  Start->Run->regedit.exe
2. Navigate to the following location:
HKEY_CLASSES_ROOT/Directory/shell
3. Add a new key
  VS2003CMD
4. In this key create another key called:
  command
5. Click on the key created in step 3. On the right double-click the Default value and type in the following: (this will be displayed in the context menu).
  Open &VS2003 Command Prompt
6. Click OK
7. Click on the command subkey and then double-click on the default value on the right. Enter the following: (this is the command that will be run).

cmd.exe /k “cd %L && “c:/Program Files/Microsoft Visual Studio .NET 2003/Common7/Tools/vsvars32.bat” && ver”

Make sure you entered the quotes. This also assumes that you have installed VS.Net 2003 in the default folder. If you did not then adjust accordingly.

That should do it. Now if you go into windows explorer you should see a new menu item when you right-click.

To make this easier we have also included a download of the reg file that you can just apply to your system. As with anything to do with the registry you should always double check files you download that update the registry to make sure nothing malicious exists.

Enjoy.

kick it on DotNetKicks.com
Page 3 of 41234