Wednesday, January 28, 2015

Performance Testing Framework




In this post I’ll introduce a set of performance testing classes and practices that I use when creating automated performance tests – with one main aim: simplify the task of measuring/verifying the performance of key areas of my .NET applications.

Source Code:
 

Often it is not practical, nor even recommended to measure all parts of an application – why waste time profiling sections of code that get called infrequently?  It’s also rather difficult knowing exactly where to start profiling an application, whether it’s server or UI, when that app either hasn’t had performance proactively “baked in” or when you’re trying to find the root cause of an occasional freeze. 

If I’m trying to isolate performance issues (or maybe retrofitting performance tests), then I tend to start off by using any of the popular . NET profiling apps, such as Red Gate’s ANTS.   These give me an idea of where to look, eg for methods that are called very frequently or take a while to run.  At least this gives me a fighting chance of where to concentrate my efforts, rather than wading through 1000s of lines of code…needle in a hay stack springs to mind.

There are many resources available showing common coding pitfalls, which can result in extra memory allocates that aren’t needed, making non-deterministic functions behave in a deterministic fashion, lack of caching, multiple enumerations etc.  Such examples include:
  • string concatenation rather than using a StringBuilder, 
  • switch versus multiple if statements, 
  • caching values for ToString/GetHashCode on immutable types

Friday, January 23, 2015

Displaying Colour Coded Percentage Columns in WPF XamDataGrid

Infragistic's XamDataGrid is a highly customisable WPF control.

I'm going to walk through the steps required to display a number of colour-coded fields on a XamDataGrid, where each field is bound to an underlying percentage based property.  

This is achieved by binding a Brush instance to the Background property of the Field's CellValuePresenter:


Detecting Binding Errors - WPF PresentationTraceSources.DataBindingSource

By default, Visual Studio (v2012 onwards) is configured to automatically log any binding errors detected whilst running a WPF application.

You can see examples of such in the Debug Output window:
System.Windows.Data Error: 40 : BindingExpression path error: 'MyUnknownProperty' property not found on 'object' ''Product' (HashCode=30581329)'. BindingExpression:Path=MyUnknownProperty; DataItem='Product' (HashCode=30581329); target element is 'TextBox' (Name=''); target property is 'Text' (type 'String')
This setting can be adjusted using the Debugging, Output Window settings: 



Often, it's useful to be notified in a more intrusive manner when a binding error has been detected...rather than silently continuing, just as WPF does.

In order to add your own handling, you need to add a class that derives from TraceListener to the PresentationTraceSources.DataBindingSource.Listeners collection.

Wednesday, January 21, 2015

WPF Frame Rate Calculator

I've been playing around with WPF's CompositionTarget.Rendering event.
From the documentation:

CompositionTarget.Rendering Occurs just before the objects in the composition tree are rendered.The Rendering event is routed to the specified event handler after animation and layout have been applied to the composition tree.
From this event, I've been looked at a way to calculate how many frames are being rendered per second in a WPF application.

Caveat Emptor:
  1. CompositionTarget.Rendering is a static member, so remember to unhook your delegate when you don't need it...leaks....
  2. The act of adding a delegate to CompositionTarget.Rendering might slow your WPF application down...so it's probably best used debugging performance, or as a user configurable options when used in a production environment.  
  3. My calculations aren't very scientific..but the numbers produced are close to those seen by attaching to the application with Perforator from WPF Performance Suite.
This could be handy if a low frame rate is detected, you could log the time stamp (using something like log4net) and compare what was going on in the rest of you app.

Sunday, January 18, 2015

Code Block/Scope Timing Snippet

You've got users complaining that it takes too long for a screen to open or for a certain piece of code to run.  Wouldn't it be handy to wrap the execution of a key block of code with some timing statistics?


The following TimeIt class is derived from IDisposable which makes it easy to wrap a code block (aka scope) with the using keyword (this will ensure that if any exceptions are raised you'll still get to final end scope logged).

The timing internals are hidden way - it's easily accessed via a static Log method:

using (TimeIt.Log("Calculate cost"))
{
    Debug.WriteLine("Retrieving price..");
    var price = pricingService.GetPrice();
    var cost = notionalCalculator.GetUSDValue(price);
}

Wednesday, January 14, 2015

Using RefCount To Create Automatic Disposal and Lazy Connections

This is quite a common scenario, I need to create a source data provider from some type of 'expensive' service, eg a stock market price ticker, which will automatically handle the job of connecting and disconnecting as the number of active observers changes.

By 'expensive' we could mean resource-wise expensive, ie amount of memory/ cpu time or financially expensive...perhaps there's a charge levied per subscription.

As an example, let's say you have a trading application with the following requirements:
  • User can open any number of trade entry screens.  
  • The trade entry screen allows the user to enter a stock symbol, eg MSFT
  • Once a symbol has been entered the application should subscribe to a market data source, eg Reuters, for that symbol and display the current price
  • If multiple screens request the same symbol then only one underlying subscription should be utilised - don't go creating yet another subscription for the same symbol
  • When a screen is closed or another symbol is selected, then we should notified when there no longer any active subscribers, thus allowing us to release the underlying source subscription
  • Subsequent requests to an already subscribed symbol should immediately send back the latest price received rather than wait until a new price arrives.