Using StyleCop With Visual Studio Express

StyleCop is a tool that enforces specific formatting guidelines on C# source code. Originally written by Microsoft for internal use, it has now been given to the programming community to maintain. StyleCop is not designed to find bugs in your software like FxCop (which will be covered in a later post). However, it will tend to force your code to be more readable, which makes it easier for you to find bugs and maintain your code. This is especially true when sharing your code with other programmers. Everybody tends to have different code formatting styles and they can each argue the merits of their own style. StyleCop is a set of standards that, when used, keep everybody on the same page.

Installation and Setup

The following instruction have been tested on Visual Studio 2010 and 2012 Express Editions but should work on all editions of Visual Studio 2008 and up.

1)  Download the latest version of StyleCop from

2)  Install StyleCop with the default settings.

3)  Navigate to any existing project that you wish to run StyleCop on or create a new Visual Studio project.

4)  Find the .csproj file (usually located at <Solution Name>\<Project Name>\<Project Name>.csproj) and open it in a text editor.

5)  Locate the existing <Import Project="..." ... > tags and add the following line after the <Import> tags:
<Import Project="$(ProgramFiles)\MSBuild\StyleCop\v4.7\StyleCop.targets" />

6)  Save the .csproj file and open the project in Visual Studio.

Unfortunately, steps 4-6 will need to be repeated on each project that will use StyleCop.


Compiling the project will now run StyleCop and show the results in the output window. Just like compilation errors and warnings, each StyleCop infraction can be double-clicked to take you to the offending code. There are also error codes (e.g. SA1600) that can be used to find more information online.

8 Common C# Mistakes

I came across a great article listing 8 common mistakes that C# programmers make. I was aware of a few of these and even wrote a short article about the proper way to rethrow exceptions. However, the first mistake in that article deals with string concatenation, and is something that I have been doing wrong.

Check out the article for yourself:

UI Responsiveness With Async in C# 5.0

It's time to revise one of my earlier posts based on a new feature of C# 5.0.  In UI Responsiveness, I had shown how to use threading and delegates to keep the UI responsive while the program was busy running a CPU-bound method in the background.  C# 5.0 has introduced the new async and await keywords that will allow us to accomplish the same goal in a much simpler way.

Note: This example now requires Visual Studio 2012.


Async is used as a method modifier that marks the method as being able to run asynchronously.  Adding this modifier to the method declaration is a required step and indicates to the compiler that the method is async-ready.  Next, we'll append Async to the end of the method's name to indicate to ourselves, and anyone using our code, that this is an async method.  This change of the method's name is not required but is considered a best practice.  In general, you would also have to change the return type to either Task, or Task<T>.  However, in our example, we will be using async with an event handler, and in these cases the return type must remain void.
private async void StartButtonClick(object sender, RoutedEventArgs e)
    // event handler code


Await is used to indicate two things: where the calling method should wait, and what the program should be doing while the calling method is waiting.  The program will run synchronously until it gets to the await command within the async method.  At this point, it will run asynchronously.  It starts the method indicated by the await command and also returns control to the async method's caller (in our case, this caller would be the UI).  The async method will wait here until the await command finishes.  The calling function will run until it encounters an await command itself.  Once the current async method completes the await command and the calling function has hit its next await command, the async method becomes synnchronous again.
double result = await Task.Run(() => this.ProcessStuff(maxCount));


Using this new feature, the length and complexity of our sample from the UI Responsiveness post has been greatly reduced.  We no longer need any delegates nor do we need to explicitly handle creating or starting any threads.

Final Code

This code below will work with the XAML file defined in the UI Responsiveness post with one change: the method name for the startButton's Click handler has been changed from StartButtonClick to StartButtonClickAsync.
namespace WpfApplication1
    using System;
    using System.Threading.Tasks;
    using System.Windows;

    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
        public MainWindow()

        // This method is marked with the new async modifier and its
        // name ends with Async.
        private async void StartButtonClick(object sender,
                                            RoutedEventArgs e)
            // Indicate that the program is busy with the user's input.
            this.startButton.IsEnabled = false;
            this.startButton.Content = "Working";

            // Get user input to use for a work load in our Process
            // function. Note there is no input validation here.
            int maxCount = Convert.ToInt32(this.userInput.Text);

            // Create a new Task that will run on a background thread
            // and await the results.
            double result = await Task.Run(() =>

            // Display the results.
            this.resultDisplay.Text = result.ToString();

            // Indicate that the program is ready for a new input.
            this.startButton.Content = "Start";
            this.startButton.IsEnabled = true;

        private double ProcessStuff(int maxCount)
            double result = 0;

            for (int i = 0; i < maxCount; i++)
                for (int j = 0; j < maxCount; j++)
                    result += i * j;

            return result;

NaGaProMo Update - Post Mortem

I failed at NaGaProMo.  I ended up delaying NaGaProMo for two reasons.

The primary issue is that I wasn't ready to dive into graphics programming.  I had dabbled in this with XNA in the past and was expecting a similar experience when using DirectX or OpenGL directly.  This ended up not being the case.  So before I reattempt NaGaProMo, I will be familiarizing myself with OpenGL.

I had also been hoping to get two fellow programmers involved with writing their own games for NaGaProMo.  Unfortunately, waiting until November 3rd was probably not the best way to try to convince someone to write a game within the time frame of November.

I'm not giving up on the idea of NaGaProMo.  I will attempt this again in a few months, but until then, I need to catch up on some other projects I've let lapse.

NaGaProMo Update - DirectX or OpenGL

Day -1 of NaGaProMo (October 30) found me trying to familiarize myself with DirectX 11.  I wasn't starting on my game yet, but I did want to get a head start on learning how to draw graphics on the screen.  The only time I'd used DirectX before was when writing a small test program using Microsoft's XNA tools.  XNA is an SDK that works with Visual Studio to simplify the process of making games with DirectX 9.  This simplified approach worked well, but I never did get far with my program.

Since then, shaders have taken over the graphics scene and DirectX 10 and 11 have changed drastically to accommodate this new paradigm.  I figured this wouldn't be too difficult to relearn because I hadn't really learned the old DirectX 9 / XNA in the first place.  So I found a nice looking tutorial on DirectX 11 and got to programming a simple test program.  My goal here was to get some cubes and other shapes on the screen and maybe have some user input to either move one of the shapes or the camera around.  Using XNA, that was easy enough to do in an hour or so.

After an evening spent going through tutorials with DirectX 11, I had a triangle on the screen (which the tutorial did for me), and I could change the color of it (which I did myself!).  I could also change the points of the triangle, or make a second triangle, but user input eluded me.  The graphics pipeline that went through all of the various shaders seemed overly complicated and left me more confused than when I had started.  Discouraged, I didn't do any more programming until NaGaProMo Day 4 (November 4th).

In the interim, I debated using XNA again, but this had a few downsides.  First, it would require me to use an older version of DirectX.  By itself this wasn't an issue, but I also look at NaGaProMo as a good chance to learn some new programming skills.  I'd prefer to be using and learning the most up-to-date tools.  The second issue was that XNA only works with older versions of Visual Studio.  Once again, this would be an out-of-date tool.  Finally, I've read some posts online that indicate XNA games may not run on Windows 8, which is my current OS.  Ultimately, I ruled out XNA for this project.

Once I decided to try again with drawing some graphics, I switched gears to OpenGL.  This immediately set me on a search for compatibility between OpenGL and C#.  Most graphics libraries tend to be written for C or C++ for performance reasons.  Therefore, OpenGL is not directly compatible with the managed framework offered by C#.  Fortunately, OpenTK offers a solution to this problem by wrapping the OpenGL libraries in managed code.  This makes it a bit difficult to follow OpenGL tutorials and references because the names of most OpenGL methods and variables have changed, but there are some easy tricks to deal with these changes (expect another post with my methodology for this).

OpenTK has a quick tutorial that gets some graphics on the screen in a simple (though not quite as simple) manner that is reminiscent of XNA.  It starts out with a basic triangle again, which seems to be the equivalent of "Hello, World" for graphics, but the code was much simpler to understand.  This got me excited for my NaGaProMo game again.

My next step was to add some debug capabilities to the window in the form of a text overlay.  Initially, I wanted to add a frames-per-second counter in the corner.  A couple tutorials talk about text overlays, but none of them seemed to work.  They all focus on creating a texture with the desired text and a transparent background, and then applying this texture to a quad (four-sided polygon) that fills the screen.  Mostly, this just ended up hiding my "Hello, World" triangle and not showing any text.  This consumed the remainder of NaGaProMo day 4 and part of day 5.

While I still don't have the text overlay working, I changed tacks once again and sought out recommendations for better OpenGL instruction.  Different people tend to have different favorites, but the overall recommendations I was finding can be summed up by this answer on Stack Exchange.  One thing this research indicated is that the OpenTK tutorial seems to be the old, pre-shader method of programming graphics that was common in OpenGL versions 1 and 2.  This is known as fixed-function pipeline as opposed to the newer shader pipelines that are used in OpenGL 3 and 4.

Ultimately, I settled on two sources for learning OpenGL 3/4:

OpenGL SuperBible - 5th edition
Learning Modern 3D Graphics Programming (online tutorial by Jason L. McKesson)

I ended up buying the Nook version of the OpenGL Superbible from Barnes & Noble (that whole shopping experience did not go well), and also started working through the tutorials for Learning Modern 3D Graphics Programming.  Hopefully, I'll begin making some progress and can actually get to the game portion of this project before the end of the month!  If not, maybe December will become NaGaProMo instead.


I humbly present an idea and an experiment:

National Game Programming Month (NaGaProMo)

Based on the idea of National Novel Writing Month (NaNoWriMo), NaGaProMo instead focuses on programming a game from start to finish in one month.  You shouldn't try to create the next blockbuster title. Instead, NaGaProMo is a fun way to get some extra programming in while creating a new video game.  Get together with your friends to share tips and bounce ideas around throughout the month.


1)  The game must be created entirely during the month of November.
2)  All programming must be done by you, the sole author.  (You can still use other libraries and APIs created by other programmers.)
3)  At the end of the month, you should have a reasonably stable game that can be run on your target device (PC, Android, etc.).

Next year, there may be some sort of length requirement, but I'm working through this for the first time myself this year.  You'll notice I called this whole thing an experiment at the start of this entry.

I'll be blogging about my progress throughout the month of November and hope to have a finished game in about a month.

Code Smiles - Refuctoring

Programmers often spend time talking about ways to avoid code "smells" but very little time is spent dealing with code "smiles".  Fortunately, I found a presentation that deals with the latter:

Sample quote: "Over time code "smiles" build up to create what is sometimes called maintainable code, more specifically, code that can be maintained by somebody other than the person that wrote it, and that means YOU!"