Windows Support Number

  • Subscribe to our RSS feed.
  • Twitter
  • StumbleUpon
  • Reddit
  • Facebook
  • Digg

Monday, 23 September 2013

Integration tests written in .Net using locally hosted node.js server

Posted on 13:15 by Unknown
I've blogged before about hosting web services created with Web API inside a test fixture in .Net, what follows is the same idea but in this case hosting a node.js implemented web service, this is using the node.js server I created in this previous post.

Jumping straight to the solution this is what I came up with:
As you can I've managed to reduce the amount required to be specified for each test fixture to 3 parameters:

  1. working directory for node.js server,
  2. full path to the node executable, 
  3. node server name and any arguments (note the port number).
The implementation detail has been pushed into the base class - WebServiceIntegrationFixtureBase.

Before showing the implementation for this class, the test runner & fiddler outputs are shown below:
The base class implementation is shown below, as you can probably guess this uses the Process class from the System.Diagnostics namespace:
Loading ....
As you can see there isn't much going on, the main thing to notice is the use of an event handler for the Process class Exited event. This is done to check if the process starts up and remains running. The node server will return an exit code '8' if it fails to start the server correctly. The most likely reason this will happen is because the port the derived test fixture is using is already in use by another process, and if this happens I want to fail the test.

You might ask why bother?

I run my test using a continuous testing plugin like nCrunch and it's configured to run test simultaneously. This means if I'm not careful about the port I specify for each test they may clash and cause node to crash on start-up - in the example above I'm not worrying about this as there is only one test, but if there were multiple tests in the fixture I would be using some mechanism to generate a unique valid port number.


Read More
Posted in .Net, Development, integration testing, javascript, node.js | No comments

Saturday, 21 September 2013

Building mock web service in node.js instead of Web API

Posted on 12:44 by Unknown
I needed to build a mock back-end web service this week because the middle-ware team wasn't ready (they're useless standard Java 'enterprise' developers) and @Jason challenged me to write it in node.js. He showed me an example of how this was done before and said it shouldn't take more than 5 minutes to have something up and running, I've done this kind of requirement previously in Web API and thought it would be interesting to finally do 'something' in node.

All coding contexts have been changed to protect the innocents :)

The requirement was for a web service returning JSON defined resources and the idea was to map the request URL to the local the file system, where the actual content to be returned is contained in a *.json file and the actual file-name represent the HTTP code to be returned, some examples are show below:

'http://localhost:1008/examples/user/1' maps to 'd:\work\node\resources\user\1\200.json'

'http://localhost:1008/examples/user/2' maps to 'd:\work\node\resources\user\2\404.json'

'http://localhost:1008/examples/user/3' maps to 'd:\work\node\resources\user\3\302.json'

So the above example User '1' maps onto a valid response (200 HTTP code) and returns a User JSON object contained in the 200.json file, user '2' maps onto a unknown resource (404 HTTP code) and will return the message contained in the 404.json file and finally user '3' cause a URL redirect to another User resource as defined in the 302 file.

This could very easily be done using Web API or node.js, either implementations allow me to dynamically add resources as I require - I can modify the types & number of the resources without having to recompile & restart anything for the new resources to work. Having built mock service in Web API before I was interested to find out how much & how quick it would be to build it with node.

First, download and install node from here, I went for the standard install using the MSI installer:
Second, download Web Storm evaluation version from here, I decided to try out Web Storm and esque my usual choice of Visual Studio:
After going with the standard install node needs to be configured in Web Storm. This can be done by going to File -> Default Settings and selecting 'node' - and installed the pre-requisties and configure the executable path for the node executable:
Once configured ready to do some node development:)

I created an emtpy project and add a 'server.js' file:
Next was to configure debugging to use node, this is simple, just selected the node configuration and add the 'server.js' to application server path:
The project is ready to go, okay it does nothing, but I can at least start the debugger and see the output in the Web Storm console window:
I used express.js to handle the HTTP requests & responses and node-fs to access the local file system. These are 'added' using node package manager - this is similar to nuGet, except that it is more mature and reliable IMO. These and other modules are referenced in the 'server.js' file as 'require' statements, you can see this in the following screenshot:
Loading ....
Hopefully what should be obvious from the above, there are two handlers for HTTP requests, one is for resources under the 'examples' sub path and the other is a wildcard for everything else which will return a 404 HTTP code. The other thing to note is the use of the options module, this is for parsing command line parameters and this give the ability to specify a port for HTTP server (defaults to port 1008 if not specified).

The service is going to map HTTP requests to file system locations, the project viewer in Web Storm give a good idea of what I mean, the screenshot below shows the file structure of not only the javascript files but also the mock resources I'm going to use:
The resource is going to be a 'User', and as you can see there will be three available, id = 7, id =8 & id = 9. Each will return a different HTTP code and possible data as described:

    Id = 7 - this will return HTTP code 200, with the contents (json) of the 200.json file,

    Id = 8 - this will return HTTP code 404, with the content (message) of the 404.json file,

    Id = 9 - this will return HTTP code 302, with the header (location) of the 302.json file,

So this pattern allows me to mock out any response scenario from the service - any HTTP code can be mocked.

The other thing to note about the above screenshot is the 'statusCodes.js' file - this is a locally defined npm module. It's responiblity is to dynamically load the other local modules in the 'status_code_handlers' folder, these modules provide the specific logic for full-filling a HTTP code, e.g. the '200.js' file is shown below:
The completed 'server.js' file looks like this:
Loading ....
Running the server up I get the following responses in Fiddler:

Requesting User resource Id = 7 return a 200 code with the specific data (json):
Requesting User resource for Id = 8 returns a 404 with the specific error message:
Requesting User resource for Id = 9 redirects to User Resource Id = 7, hence the two requests seen in Fiddler:
That pretty much covers it, it's been a much quicker refactoring loop using Web Storm and node instead of Visual Studio and Web API - Web Storm is a much more responsive development environment, quicker to load, quicker to start a debugger etc...

The code is available for download:

Read More
Posted in Development, javascript, nodes.js, RESTful, web api | No comments

Sunday, 15 September 2013

Suspending & resuming property notifications when using INotifyPropertyChanged

Posted on 10:24 by Unknown
Currently I'm working with some UI code which has a 'domino effect' when a property changes on a view model - the data is being rendered in a tree view, and the reason for the 'domino effect' is because the value of a node in the tree view is an aggregation of multiple child nodes (leaf nodes hold the actual values which are aggregated up). The dataset is dynamic, it can be updated during it's visualization and when this happens we want the ability suspend NPC events being fired until recalculating all the aggregates has completed.

I have the following base class for all bind-able (view model) classes:
What I wanted was the ability to prevent suspend the firing of the PropertyChanged event and then resume later, I wanted to do this via a single new method exposed on this class and the return type would IDisposable and importantly it should reference count when called multiple times without being disposed. I wanted the ability to do something similar to the following test - where I can have nested calls to suspend but it will only resume when the underlying reference count returns to zero:
Loading ....
The User class is shown below:
Loading ....
I wanted minimal changes to the Bindable class - I wanted to avoid increasing the memory foot print of class as much as possible as well as only adding a single public method to the class. Ideally I wanted the Bindable class to have no knowledge directly of the reference counting going on when nested calls to SuspendNotifications method are made.

I came up with the following changes to the Bindable class:
As you can see the only change to the public signature is the addition of the SuspendNotifications method and the internal structure now has a reference to a disposable instance. The RaisePropertyChanged method has been modified to check whether notification have been suspended - if they have then it is added to the instance of the SuspendedNotification class:
Loading ....
The SuspendNotifications method is defined as follows, as you can see there isn't much to the method, you're probably wondering - 'when does the created instance of SuspendedNotifcations get disposed?'
Loading ....
The answer is when the internal reference counter of the SuspendedNotifications class returns to zero.

Looking at the method above what you notice is the returned IDisposable is not the instance of the SuspendedNotification class but the one returned by the call to the AddRef method. Every time the IDisposable returned by the AddRef method is disposed the reference count on the instance of SuspendedNotifications is decremented, once this returns to zero the property changed events are fired for all the properties which have changed whilst notifications have been suspended.

This is all achieved by the parameter passed to the SuspendedNotifications class - basically I've inverted the responsibility for when the SuspendedNotifications instance is disposed, the instance disposes of it's self when the reference count returns to zero. This can be seen in the SuspendedNotifiication class below:
Loading ....
And this produces a successful test output:


Read More
Posted in Development, WPF | No comments

Friday, 2 August 2013

Daily Dilbert Service - the most important service I've ever written...

Posted on 10:09 by Unknown
NuGet package available here...

First off a big shout to @hamish & @leeoades on this one - I'm just blogging about it. At work we have a test harness for launching the application in different environments, the test harness like the app is written in WPF. We got very bored of looking at the test harness UI and decided to make it a bit more interesting - we added the Daily Dilbert comic strip to the button to launch the app - a full on VB style button taking up most of the UI :)

This was originally done using code provided by Brian Ritchie, but since the image was removed from the daily Dilbert RSS a couple of months ago this no longer worked, fortunately a couple of weeks later a Yahoo pipes URL implementation appeared with the daily image.

We took this and used it inside a service to abstract away to complexity, here it is:
Loading ....
As you can see you can either get the image as either a file (*.jpg) or a .Net Stream. Also it makes use of Task and since the service is designed to support .Net v4.0 it means you will need to have this Hotfix KB2468871 installed on Windows XP machines.

I've pushed the code to Git here & published a NuGet package here.

So you'r only a couple of clicks away from getting it working, a quick example WPF app is shown below:
The test app is available for download.
Read More
Posted in Development, WPF | No comments

Wednesday, 31 July 2013

Testing when the culture changes in WPF

Posted on 13:06 by Unknown
Recently I've do some work on a WPF app which required to support multiple languages in the UI - a spike to see how easy supporting multiple languages is in WPF, the test UI is shown below in English & French:
The app is easy enough to understand - change the UI language and all the text based values are updated with the locale specific instances. I wanted to follow the standard pattern of using language specific resource files to store the translated text, these were placed in the standard location inside the project structure:
One of the big advantages of using this mechanism is the resources are compiled into a class which can be used in your ViewModels and Views and this is why see above the 'Resource.resx' file - this contains the 'untranslated' resource strings etc:
I've been aware for a long time there are 2 culturing settings per thread in .Net - Thread.CurrentCulture & Thread.CurrentUICulture, the second is the one of interest here, it is used by the ResourceManager to load the correct resources at run-time. What's interesting  is in .Net 4.5 they introduced a couple of static methods to set these properties globally - CultureInfo.DefaultThreadCurrentCulture & CultureInfo.DefaultThreadCurrentUICulture, once set these are used as the default setting for all threads created after this point. This brings up an interesting scenario - if you create a thread before initializing these properties it will default to the behavior seen in .Net 4.0, it will take the current culture from the system locale (windows system culture), but once set then any existing threads will be updated (in the same app-domain). The default value for both properties is NULL, I was expecting it to be set to the system locale.

To keep my ViewModels simple, I decided to push the complexity of using these new properties into a service which is able to notify any interested ViewModels when the selected culture has changed:
Loading ....

As you can see I'm using the CultureChanged property to notify anyone interested when the thread UI culture has changed. To make sure the same instance is shared between all ViewModel instances, the interface & class are registered as a singleton with the IoC container (Autofac):
This then allows a ViewModel to update any text which needs to be translated when the current culture changes, the following snippet shows the CultureChanged property being subscribed too and when the stream pumps it raises IPNC for all the required fields on the ViewModel:
So the point of the post was testing when the culture changes and this is done by putting the implementation of the ICultureService interface under test, this was easy as the service has a high level of SRP, infact I only need 3 tests to cover off the behaviour. The first two are straight forward they test when the culture changes we get notified via the CultureChanged property:
As you can see from the green icons these tests are passing as expected - the icons are a visualisation provided by nCrunch.

The third test produced the interesting results, this test was not specifically testing the CultureService, it was more around testing the vertical slice of changing culture - when the culture changes then the ResourceManager should provide the correctly translated text when requested.

To test this requires translated resource strings in culture specific *.resx files, the following screenshot shows resources for English & French and the test:
Does the test pass or fail?

It depends...

When run as a single test from either nCrunch, Resharper or any other test runner it works as expected:
But when run as part of a group of tests - running all tests in a class or assembly then it will fail:
How can this be explained?

I thought it must be because the ResourceManager only gets updated on the dispatcher thread - I was thinking single tests are run on the UI (dispatcher) thread, where as if your running multiple tests they are run on a background thread. A quick look at the threads running threads showed this wasn't the case, single test:
Multiple tests running (also on a work thread):
At this point I gave up looking for a reason for the failure and started looking for a workaround solution to getting it working when running multiple tests, the answer turned out to be simple - explicitly set the compiled Resource class Culture property, this is done in a CultureChanged property subscription:
The updated test now looks like this:
Read More
Posted in .Net, CultureInfo, Development, testing, WPF | No comments

Monday, 17 June 2013

Implementing a busy indicator using a visual overlay in MVVM

Posted on 13:24 by Unknown
This is a technique we use at work to lock the UI whilst some long running process is happening - preventing the user clicking on stuff whilst it's retrieving or rendering data. Now we could have done this by launching a child dialog window but that feels rather out of date and clumsy, we wanted a more modern pattern similar to the way <div> overlays are done on the web.

Imagine we have the following simple WPF app and when 'Click' is pressed a busy waiting overlay is shown for the duration entered into the text box. What I'm interested in here is not the actual UI element of the busy indicator but how I go about getting this to show & hide from when using MVVM. The actual UI elements are the standard Busy Indicator coming from the WPF Toolkit:
The XAML behind this window is very simple, the important part is the ViewHost. As you can see the ViewHost uses a ContentPresenter element which is bound to the view model, IMainViewModel, it contains 3 child view models, one for the top, middle & bottom.
The ViewHost is nothing more than a ContentControl, its not only a place holder for the desired content but it also has the overlay and progress bar shown above.
Where is the XAML for the overlay defined?

The XAML is defined in a style - see below, I've defined it like this so I don't have to explicitly write any extra XAML when I want to use the ViewHost control - if I had an app with multiple Views I wouldn't have to keep defining the Grid for the overlay.

As you can see I have a specific view model - IBusyViewModel, this has a property called BusyMonitor which is used to trigger both the visibility of the grid containing the busy overlay as well as the actual overlay. I do this because the BusyMonitor property on the IBusyViewModel could be null and I don't want a binding exception thrown if I bound to BusyMonitor.IsBusy and BusyMonitor is null.
As you can see I have a specific view model - IBusyViewModel, this is bindable obejct because the IsBusy property is bound to the busy overlay. I've also included an Rx observable to allow any ViewModel to observe when the value changes.
Instances of this interface are then injected into the MainViewModel instance:
Also injected into the ContentViewModel & FooterViewModel, in this example these view models don't do very much:
The interesting view model in this example is the HeaderViewModel. The IObservableCommand handles the button click, which executes the ExecuteClick method. This sets the BusyMonitor.IsBusy property to true initially and when the observable timer pumps the BusyMonitor.IsBusy is set back to false.
Now at this point you might be thinking...

'but you've got 4 view models and 4 instances of the IBusyMonitor interface, how can setting IsBusy to true in the HeaderViewModel affect the whole application?'

The answer in fact is the exact opposite, they are all sharing the same instance of the IBusyMonitor interface and this is achieved by using an IoC container with a singleton registration for the IBusyMonitor interface, I'm using AutoFac for this example:
That pretty much rounds it up, the code is available for download:
Read More
Posted in .Net, Development, MVVM, WPF | No comments

Saturday, 15 June 2013

Comparing performance of .Net 4.5 to .Net 4.0 for WPF

Posted on 13:52 by Unknown
Currently I'm working on a .Net 4.0 WPF app and we've had some discussion about moving to .Net 4.5, we don't get to make the decision :( but we're interested to know what performance gain we'd get.

What follows is a comparison of the same app compiled against .Net 4.0 & 4.5. The app makes use of a couple of NuGet packages - Autofac & Reactive Extensions, both of which provide versions for both .Net 4.0 & 4.5. It also makes use of Telerik grid control to render the data.

What does the app do?

Pretty simple, it generates a 1000 rows of data asynchronously and binds this to a telerik grid, for every iteration the grid is clear of any data first.
How am I going to measure any performance improvement?

I'm using the code from a previous post - 'Measuring UI Freeze...', I'm expecting any improvement to be visible in a reduced amount of time on the dispatcher thread - if the (.Net) code base is more efficient it should surely reduce the amount of time required to render the UI.

I'm going to repeat the generation and rendering of data 100 times for each version of the framework, this should allow an statistical anomalies to be ignored.

How am I going to record any improvement?

Simply write out to file any value that exceeds 1000 milliseconds, this is done in the App_Startup method:
So what's the outcome?

The outcome is best visualised as a set of graphs, first a scatter graph where x-axis represents the iteration and y-axis represents the UI freeze duration in milliseconds:
and more impressively a bell curve,where the x-axis represents the duration in milliseconds of any UI freeze and frequency on the y-axis:
Averages are as follows:

.Net 4.0 average = 1605 ms
.Net 4.5 average = 1337 ms (elite :))

Or to put it another way this is a 16% increase in performance!

Okay so this wasn't anywhere near a scientific approach but it did show over 100 iterations there is measurable improvement, I've made the code available for the .Net 4.5 version.

Read More
Posted in .Net, Development, MVVM, Performance, WPF | No comments
Newer Posts Older Posts Home
Subscribe to: Posts (Atom)

Popular Posts

  • MVVM anti-pattern: View code behind with no implementation
    I've seen rather a lot of this anti-pattern recently, to be explicit about what I mean, lets define this in terms of a WPF user control....
  • Be careful of the culture when using Bing Maps REST API
    When developing the Bing Maps Wrapper service for the WP7Contrib we weren't aware of the importance of the instance of the CultureInfo ...
  • WP7Contrib: Bing Maps REST Services Wrapper - Deep Dive
    Following on from Rich's post introducing the Bing Maps Service in the WP7Contrib I'm going to explain in more detail how we built ...
  • MVVM anti-pattern: explicitly using data context in View code behind
    I believe explicitly using the data context in the code behind of the view (custom, user control etc) in any MVVM application is an anti-pat...
  • Implementing a message box using a visual overlay in MVVM
    I've blogged about implementing a busy indicator before, this post is an extension of this pattern to implement a message box - this is...
  • MVVM anti-pattern: Injecting the IoC container into a View Model
    This is another anti-pattern I've seen a lot recently, the dynamic use of the IoC container inside a view model to resolve child view mo...
  • Using IoC nested lifetime scopes with View Models in MVVM
    A common pattern you see when developing web services is the use of the Unit of Work applied to the HTTP request - anything that happens dur...
  • Azure - RoleEnvironmentException in OnStart
    My previous post was a bit of rant at the developer experience in Azure when trying to set-up diagnostics. I managed to work out what was c...
  • Coupling and cohesion
    I was reading ploeh's blog  this morning and it made me think about coupling and cohesion in general. These are import concepts in softw...
  • Building a multilingual MVVM app
    Last week I built a sample multilingual app in WPF using MVVM for a proof of concept. This was the first time I've built a desktop app w...

Categories

  • .Net
  • .Net 4.5
  • Abstractions
  • Advertising
  • Agile
  • Agile Courage
  • AOP
  • Async
  • automated testing
  • Azure
  • Azure IIS RESTful development
  • BDD
  • Bing Maps
  • Bounded Context
  • C#
  • C# 5.0
  • Caching
  • Chocolatey
  • CLoud
  • CodePlex
  • Coding
  • Coding Building CI Testing
  • Coding C#
  • coding C# IoC StructureMap
  • Coding Functional-Programming
  • Coding REST Knowledge
  • Coding Services
  • Coding TDD Refactoring Agile
  • Command
  • continuous testing
  • coupling
  • CultureInfo
  • DAL
  • databases
  • DDD
  • DDD Coaching
  • DDD Domain Events Auditing nHibernate
  • DDD Entities Value Objects
  • Debugging
  • Design Patterns
  • Design Patterns Databases Auditing
  • Developement
  • Development
  • Development Coding
  • Development Process
  • Development unit testing
  • Development VS 2011
  • Diagnostics
  • Disposable
  • Exceptions
  • FINDaPAD
  • FindaPad Property Rental Windows Phone 7 Mobile Devices
  • Fun Coding Duct-Tape
  • Hotfixes
  • integration testing
  • IoC
  • jasmine
  • javascript
  • Jobs Development
  • LINQ
  • marketplace
  • Mobile Devices
  • Mocking
  • MSDN Coding
  • MSpec
  • Multilingual
  • MVC
  • MVVM
  • nCrunch
  • nHbiernate Repository Pattern Criteria
  • nHibernate Auditing Design Fluent
  • nHibnerate Entities Events Listeners
  • node.js
  • nodes.js
  • Nokia
  • NoSQL RavenDB Azure Development
  • Observations
  • OO
  • ORM
  • Performance
  • Portable Class Library
  • Portable Library
  • PostSharp
  • Process
  • Rants
  • RavenDB IIS 7.5 Development
  • Reactive
  • Reactive Extension
  • Reactive Extensions
  • ReadOnlyCollections
  • Resharper
  • REST Distributed-Systems
  • REST HTTP
  • rest web
  • RESTful
  • Rx
  • Serialization
  • Silverlight
  • Silverlight Installation
  • Task
  • TDD
  • TDD IoC DI
  • TDD Mocking
  • TDD Team Observation
  • Telerik
  • testing
  • threading
  • TPL
  • UI
  • Undo-Redo
  • unit testing
  • ViewModels
  • VS 2012
  • wcf
  • web api
  • Web Services
  • web services mobile devices data
  • WebAPI
  • Windows
  • Windows 8
  • windows phone
  • Windows Phone 7
  • WP7
  • WP7 Bing Maps Development Network HTTP
  • WP7 Bing Maps Development UK Crime
  • WP7 Bing Maps Development UK Crime Clustering
  • WP7 Bing Maps Development UK Polygons Clustering Performance
  • WP7 cryptography bouncy castle
  • WP7 Cultures C#
  • WP7 feedback development app store
  • WP7 Javascript web browser
  • WP7 MSBuild
  • WP7 ORM Databases performance
  • WP7 Serialisation
  • WP7 SilverlightSerializer C#
  • WP7 sqlite performance development
  • WP7 WP7Contrib Bing Maps Development
  • WP7 WP7Contrib Bing Maps Polygon Development
  • WP7 WP7Contrib CodePlex
  • WP7 WP7Contrib CodePlex Bing Maps Development
  • WP7 WP7Contrib CodePlex ObservableCollection
  • WP7 WP7Contrib ILMerge .Net
  • WP7 WP7Contrib Phone Maps
  • WP7 WP7Contrib SilverlightSerializer C#
  • WP7Contrib
  • WP7Contrib Bing Maps WP7
  • WP7Contrib WP7 Geo-Location development C#
  • WP7Contrib WP7 HTTP Compression
  • WP7Contrib WP7 Url Development Rx
  • WP7Dev
  • WPF
  • WPF Cultures
  • WuApi
  • XAML

Blog Archive

  • ▼  2013 (16)
    • ▼  November (5)
      • MVVM anti-pattern: Injecting the IoC container int...
      • MVVM anti-pattern: View code behind with no implem...
      • MVVM anti-pattern: explicitly using data context i...
      • Implementing a message box using a visual overlay ...
      • Using IoC nested lifetime scopes with View Models ...
    • ►  September (3)
    • ►  August (1)
    • ►  July (1)
    • ►  June (3)
    • ►  May (2)
    • ►  January (1)
  • ►  2012 (44)
    • ►  November (2)
    • ►  October (8)
    • ►  September (5)
    • ►  August (2)
    • ►  July (4)
    • ►  June (3)
    • ►  May (1)
    • ►  April (2)
    • ►  March (13)
    • ►  February (4)
  • ►  2011 (52)
    • ►  December (3)
    • ►  November (5)
    • ►  October (7)
    • ►  September (7)
    • ►  August (11)
    • ►  July (4)
    • ►  May (2)
    • ►  April (1)
    • ►  March (5)
    • ►  February (3)
    • ►  January (4)
  • ►  2010 (1)
    • ►  August (1)
  • ►  2009 (32)
    • ►  December (3)
    • ►  November (7)
    • ►  October (6)
    • ►  September (11)
    • ►  April (1)
    • ►  March (4)
Powered by Blogger.

About Me

Unknown
View my complete profile