Improving Integration Tests In .Net By Using Attributes To Execute SQL Scripts
A common problem I find while writing integration tests is the lack of a nice way to control the database. Since it is an integration test, you don’t want to mock out the database completely, just set it up with the required test data. As part of the Arrange step of the Arrange, Act, Assert loop, it is common to want to run some SQL scripts to set up your database and another script to clean up after the test finishes. This leads to various solutions such as having a standard method invocations at the start and end of the test to run the appropriate SQL scripts. These methods could even be inside of a test base class.
public void UpdateUserNameTest() { ExecuteSqlScript(@"SetupTestUserDetails.sql"); // Act. Call the appropriate methods and Assert everything went well. ExecuteSqlScript(@"CleanupTestUserDetails.sql"); }
One of the problems with that is that if the “Act” part of your test throws an exception, the clean up script might never get run. This will require you to add a try catch block around your test to catch exceptions and always run the clean up scripts. This makes the code a bit more messy by increasing the plumbing noise around your main logic. Wrapping the test in a SQL transaction has it’s own problems. The changes made by the set up script won’t be visible outside the transaction. This can be a problem if you are making service calls as you do in integration tests.
A neater of doing the same thing in my opinion is taking a more Aspect Oriented approach. Since the set up of the test data and the clean up are not logic being tested, they can be yanked up to become Attributes. But the built in [TestInitialize] and [TestCleanup] attributes in MS test framework don’t take any parameters which makes it hard to run different SQL scripts for each test. This requires the use of an AOP framework that allows attribute pointcuts. The problem with using Attributes and AOP is that the built in MS Test Runner that comes with Visual Studio cannot be made to get the test classes from an AOP container rather than just new’ing them up. This rules out the usage of runtime weavers such as Spring. Compile time weavers such as Postsharp would make life so much easier. But often, when you start on a project, the AOP framework that is used by the team is already set.
To get around this problem I found a clean solution using a feature that is already built in .Net called “Context Bound Objects”. Objects derived from ContextBoundObject allow you to inject custom services into the object’s interception chain. More information about Context Bound Objects can be found here . As part of creating a new context for a Context Bound Object, we have the chance to execute our own code. A diagram of this architecture is shown below.
We can use this process to create our “Aspectable Test” as shown by Callum Hibbert here along with his Codeplex project.
Since taking a dependency on a third party dll can be a contentious issue requiring many team meetings, I have simplified and isolated the releavant parts to only a few classes that can be added into any project. Callum’s framework is a very extensible and highly decoupled. I have distilled this to 5 tightly coupled classes that will get the job done. This is available for download at the bottom of this post.
The key classes are the AspectOrientedUnitTest, which inherits from ContextBoundObject. It is also decorated with a [AspectOrientedUnitTestContext] attribute which is an attribute that derives from ContextAttribute. Here, we override the “GetPropertiesForNewContext” method to inject in our own aspect. In our case, the aspect is the SqlExecuteAspect.
I have removed all the indirection from the TestExtension Framework to make this class implement the required interfaces of IMessageSink, IContextProperty, IContributeObjectSink. The method of interest is the “SyncProcessMessage” method in this class. Here, we can execute code before and after we pass the call to the next object in the message sink chain. We wrap up the actual method execution in a try/finally block to make sure the clean up sql always runs. This is shown below.
public IMessage SyncProcessMessage(IMessage msg) { if (msg == null) throw new ArgumentNullException("msg"); // Pre processing code ProcessAttributes(msg); IMessage returnMessage; try { // The following line is the call to the actual method we have intercepted. We can do stuff // before we call this or after. This lets us change behaviour. returnMessage = _nextSink.SyncProcessMessage(msg); } finally { // Post processing code ProcessAnyPostSqlAttributes(msg); } return returnMessage; }
Here, we can examine the MethodInfo object in the IMessage object to see if its been decorated with any of the attributes we are interested in. If it is, we can extract the parameters from the attributes and execute the appropriate code. Using this pattern, now we can have a very nice attribute driven unit test, that lets us set up and tear down data in our database for our tests as shown below.
[PreSqlExecute("SetupTestUserDetails.sql")] [PostSqlExecute("CleanupTestUserDetails.sql")] public void UpdateUserNameTest() { // Act. Call the appropriate methods and Assert everything went well. }
Note that this also requires the unit test class itself to derive from our ContextBoundObject derived class like so …
public class UnitTest1 : AspectOrientedUnitTest { ... }
The performance hit associated with having to derive from the ContextBoundObject and it’s impact on your object model preclude it from being used as part of your application classes. But for Unit or Integration testing, it shouldn’t really matter much. The most important thing is that it we achieve this with very little code and without taking any dependency on other libraries or frameworks or having to use a completely different testing tool or framework. It should be very easy to introduce this into any .Net code base on any project in less than half a day without having to seek a team wide consensus or approval. Try it out and let me know what you think.
Amex Security Fail
Posted by Chaitanya in Uncategorized on December 18th, 2010
As Jeff Atwood pointed out on his blog, security on the web is generally a hard problem and passwords are the Achilles heel of such security. Companies should generally encourage customers to use strong passwords. What really irks me though is when a company like American Express, who should be taking this with the utmost seriousness tends to limit password complexity.
I am pretty sure that a few months ago, the password length could only be a maximum of 8 characters, that seems to have changed. But they still only allow a limited a set of special chars and here’s the kicker, the password is not case sensitive ! Is it just me or does this scream out home grown Crypto or some sort of direct pass through authentication to a legacy system? Bravo Amex, Braaavooo … *slow clap*

Powershell, Command Prompt and the Visual Studio Command Prompt
Posted by Chaitanya in Uncategorized on October 22nd, 2009
As an Enterprise Developer, I often find that there are plenty of batch files I need to run as part of my tool chain, either for code generation, deployment or testing. And its always annoyed me that they needed to be run from the Visual Studio Command prompt.
“oohh… look at me, I am a Visual Studio Command prompt. I am so cool. Only I can run these scripts. I am the greatest ! waahh, waah !”…. pfft … arrogant little command prompt. Who does it think it is? Anyway, where was I? Oh yeah, running these batch files.
So I set out to take down the Visual Studio Command Prompt down a notch, which turned out to be pretty easy. Basically you just need to add some locations to the “Path” environment variable that Visual Studio Command Prompt has, but that an ordinary command prompt and Powershell don’t. An automated version of this process for Powershell can be found here
So find the vsvars32.bat file in your visual studio installation’s “Common\Tools” directory and copy the locations that are being added to the Path variable. See the picture below for more details …

Now add these locations to the end of the Path environment variable and Voila ! Your standard command prompt and Powershell, with all its inherent goodness, will suddenly start running your MsBuild scripts.
Show and Tell as part of Scrum
It seems nowadays everyone is following the Scrum methodology. One of the tenets of Scrum is openness. The whole point of burndown charts and daily stand ups is to make the development more open. Scrum won’t magically fix all the weak links in your development methodology, but it will help you identify them quickly and accurately.
One of the most recognisable aspects of Scrum are the daily stand up meetings. In my experience though, I found them to be of limited value. But in my most recent project, even though we weren’t really following Scrum, we had a variation of the standups that I found tremendously useful. We called these “The Weekly Show and Tell”. It combined the best parts of Scrum standups with the quality control of peer reviews.
We had a small team of 4 developers and a Business analyst sequestered in a seperate room. We also had access to a projector and an empty wall to project onto. Basically, the show and tells were quick 10 minute screencasts/presentations of the work each team member has been doing for the week. The team member would hook the projector cable to their machine and demo the bits they had working so far. Since the audience was mostly developers, part of the demo could even be in visual studio. This allowed every team member to not only hear about the work in progress, but also see it with their own eyes and as we know, a picture is worth a thousand words. It also allowed each of the team members to make suggestions about features, code, architecture etc.
On the whole, I found this system to be very useful and productive and much more in line with the spirit of openness. Having a regular visual presentation of different aspects of the system builds a lot of familiarity with the whole system. It also allows everyone to solicit and provide more pertinent and high quality feedback. Like the Scrum stand up meetings, the users and execs were welcome to come to the Show and Tells to get an idea of how the project was progressing. Looking at the features on screen, even in their partly finished state, gave them a lot more confidence about the project and understand any challenges we might be facing. Some of these things would be very hard to communicate in stand ups or through status reports.
So, my suggestion is to try the weekly Show and Tells in your next project and let me know how it works out for you.
Changing Pie Slice colours in Silverlight 3 Chart Control
Posted by Chaitanya in Silverlight on August 24th, 2009
As most of you know, Silverlight 3 includes the new charting controls. It is a functionality that Windows developer hoped would ship out of the box for a long time. It lets us easily add visually compelling functionality and the “Wow” factor to our applications.
On my most recent project, I was using the Pie chart control of SL3 to display some data in the application. Hmmm… pie …
Anyway, The Legend on the chart was taking up too much room and I wanted to have bit more control on the colours of each of the pie slices. This would allow me to create my own fancy Legend/Key into the graph and have full control over the display.
As it turns out, the PieSeries control doesn’t really expose the pie datapoint property in an easily consumable manner. After some research I found some resources that demonstrated how to change certain properties of various charts. The most relevant one was the one dealing with how to change the mouse over text for each of the pie slices.
Essentially, it requires us to Re-Style the Pie chart and supply our own customisations in a new style. Since the charting controls are open source, we don’t have to start from scratch. We can cut and paste the existing style and modify it as we see fit.
None of these other posts dealt with the matter of changing the colour of a pie slice though. They all seemed happy cycling through the predefined colours in the style and not having access to them outside of the chart control.
My customisations allow us to have more control over the slice colours. In a typical Model-View-View-Model pattern, we might have a colour associated with a particular data point. We might use that property to set the colour of a pie slice or a border or foreground of a completely different control.
In the example below, I set the graph colors and use the same colours in a Datagrid to fill a rectangle to generate my own “Legend”. Basically, I can bind the colour associated with this data point to any control in the application.

The “View-Model” class in this case is a class called PieSlice. This exposes three important properties, the percentage (Dependent value), the Description (Independent value) and the Radial Gradient Brush (Completely customisable). In our PieSeries control, we specify a new Style by setting the StylePalette property as shown below.
<chartingToolkit:Chart x:Name="SamplePercentageChart" Grid.Row="0"
DataContext="{Binding ElementName=PieSampleUserControl}" >
<chartingToolkit:PieSeries DependentValueBinding="{Binding Percentage}"
ItemsSource="{Binding PieSlices}"
StylePalette="{StaticResource MyStylePalette}"
IndependentValueBinding="{Binding }" >
</chartingToolkit:PieSeries>
</chartingToolkit:Chart>Note that Silverlight 3 also supports Element binding which we will take advantage of to set the DataContext to the “Code Behind” class. This allow us to quickly expose a dummy PieSlices property in our user control that we can bind to. Our user control class looks something like this
public partial class MainPage : UserControl { public List<PieSlice> PieSlices { get; set; } public MainPage() { InitializeComponent(); List<PieSlice> sampleData = new List<PieSlice>(); sampleData.Add (new PieSlice("SliceOne", 25, "#FFB9D6F7", "#FF284B70")); // Blue sampleData.Add (new PieSlice("SliceTwo", 25, "#FFFBB7B5", "#FF702828")); // Red sampleData.Add (new PieSlice("SliceThree", 25, "#FFB8C0AC", "#FF5F7143")); // Light Green sampleData.Add(new PieSlice("SliceFour", 25, "#FFFDE79C" , "#FFF6BC0C" )); // Yellow } }
Now that we have set the custom style for the style palette, we need to actually write it. We create a PieChartStyles.xaml file and create a resource dictionary to hold our custom styles and control templates. We can then add this dictionary to our application wide resource dictionary or our control specific resource dictionary.
First, we overwrite the control template for the PieDataPoint by setting the template property as shown below
<datavis:StylePalette x:Key="MyStylePalette" >
<Style TargetType="Control">
<Setter Property="Template" Value="{StaticResource MyPieDataPointTemplate}">
</Style>
</datavis:StylePalette>Note that you need to add the “datavis” xml namespace that references the “System.Windows.Controls.DataVisualization” CLR namespace. (All this is available in the sample project that can be downloaded as a zip file.)
Now we have to specify the Template we will use with each of the Pie data points. For this we pretty much get the existing control template as it is from here. This ensures that our charts look just like the out of the box charts. The most important customisation we do is change the Background property of the Path Control. Currently it is set as
...
<Path
x:Name="Slice"
Data="{TemplateBinding Geometry}"
Fill="{TemplateBinding Background}"
Stroke="{TemplateBinding BorderBrush}"
StrokeMiterLimit="1">The background property in turn is set by the style palette. But now that we are exposing the colour we want as a ColorGradientBrush property, we can bind to it directly. This changes our control template above to the following.
...
<Path
x:Name="Slice"
Data="{TemplateBinding Geometry}"
Fill="{Binding SliceColor}"
Stroke="{TemplateBinding BorderBrush}"
StrokeMiterLimit="1">Note that one possibility is to expose a start colour and end colour property on the View-Model and bind these to the gradient stops rather than create a RadialGradientBrush. But the GradientStop class does not inherit from FrameworkElement class. This stops databinding and throws up a very general and unhelpful AG_E_PARSER_BAD_PROPERTY_VALUE exception. So I ended up creating a RadialGradientBrush and binding to that instead.
The complete sample application can be downloaded here
Hello Blogosphere
After much procrastination, humming and harring, I finally got around to doing this. Carving out my little piece of the etherspace to voice my various thoughts and ideas. After much coaxing by my friends and collegues and hearing them speak of the joys of blogging – the fame, the fortune, the adventure and the adrenaline, I thought I would give it a try :-p
Mostly, this will be a tech blog and I will try to share various ideas and opinions as I navigate the seedy underbelly of the IT world in my day job. Mixed with my interminable wit, trenchant commentary and mostly adequate grammar, I am hoping this would make an entertaining read.
So, a toast! One small step for a man… and errr… well… seems like its just one small step for a man at the moment.
