Windows Support Number

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

Thursday, 28 November 2013

MVVM anti-pattern: Injecting the IoC container into a View Model

Posted on 15:17 by Unknown
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 models & services - service locator pattern:
The service locator pattern has been around for a while - Fowler was writing about this back in 2004!

It's not a pattern that is specific to MVVM, it's a pattern associated with using DI & IoC, if you're doing MVVM you should be using DI & IoC. A lot has also be written about this being an anti-pattern and I agree completely with Mark Seaman on the topic.

For me why this is an anti-pattern for MVVM is for the following reasons:
    Breaks SOLID principles - the view model now has multiple responsibilities and not all dependencies are being explicitly injected. The view model is now responsible for the lifetime of anything it has resolved (this includes scope as well),

    Encourages view models to become god-like objects - they become bloated - all the implementation in a single view model, it's no better than a testable code-behind file,

    Makes unit testing brittle  - when having to test such a view model you have either look through the whole class to see all the dependancies you need to mock or just try a 'hit & hope' approach and keep running and refeactoring the test until it passes. Either way you end up with a lot of test setup which is a smell in it's own right and importantly greatly discourages a developer to write tests,

    And generally destroys the structure and ethos of the MVC (MVVM) pattern - if I can resolve anything anywhere eventually you'll end up with spaghetti code which has no discernable architecture and for me this is probably the most important point when dealing with a large XAML application. 

    What's also interesting about the above example is the fact it actually mixes normal DI with service locator, injecting both other interfaces as well as the IContainer interface - neither one nor the other. The example wasn't contrived to do this it was taken from a real world example - with names changed to protect the innocent. 

    There are times when I believe using the service locator pattern is justified, but these are few and far between. An obvious one is when the creation of a class is costly in time or memory (if this was ever the scenario for me with a view model it would be a code smell and need to be refactored out).

    But if I had to use a service locator I would be either injecting a strongly typed factory or by injecting a Func<T> - all IoC containers support this feature. A couple of examples are shown below:
    Read More
    Posted in C#, Development, MVVM, WPF, XAML | No comments

    Monday, 18 November 2013

    MVVM anti-pattern: View code behind with no implementation

    Posted on 14:13 by Unknown
    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. Imagine the code behind file is nothing more than the auto generated code, but the XAML file contains the usual controls and bindings:
    The user control is used in one or more data templates as follows:

    The reason this is an anti-pattern is because it has introduced files into the solution which aren't required:
    The two highlighted files are the user control files - XAML and code behind, the resources.xaml file contains the hosting data templates.

    The reason why these aren't required is because the code behind for the user control is doing nothing, and therefore can be removed and the XAML can be moved into the hosting data template - now the view (MVVM) is no more than a data template:
     And you can now see the user control files have been removed from the solution:
    Read More
    Posted in Development, MVVM, WPF | No comments

    Sunday, 17 November 2013

    MVVM anti-pattern: explicitly using data context in View code behind

    Posted on 05:41 by Unknown
    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-pattern. The view has no need to explicitly access the data context it is there purely for binding concerns. The following screen shot illustrates what I mean:
    This is an anti-pattern because the view knows about the view model - as you can see the data context is being cast to the DataContextViewModel. The view (user control) is explicitly coupled to the view model and has reduced the cohesiveness of the view - it can now only be bound to instance of DataContextViewModel. Now you could argue if it was interface this would make is more useful but this doesn't reduce the tight coupling it just gives the illusion.

    I guess the reason why this is common is because it makes the XAML appear very clean and simple, but this is also not ideal because it's not obvious what's being bound between the view model and the view:
    How should this have been done?

    By defining a Dependancy Property on the view (user control) and then binding this in the XAML to the FirstNames property of the view model, then there is no need to access the DataContext in the code behind of the view:
    The XAML has now changed to be more declarative, which is a good thing:)



    Read More
    Posted in Development, MVVM, WPF | No comments

    Sunday, 10 November 2013

    Implementing a message box using a visual overlay in MVVM

    Posted on 08:29 by Unknown
    I've blogged about implementing a busy indicator before, this post is an extension of this pattern to implement a message box - this is instead of using the namespace provide by the .Net framework.

    The UI is shown below, and when the button is clicked in the middle content it will display the message as an overlay - as you can see I've coloured it green to get your attention:
    As with the previous post, the XAML for the View hasn't changed it's still very simple:
    What's changed is the style applied to the ViewHost class, as you can see there's now a MessageOverlay as well as a BusyOverlay. You'll notice the z-order of the MessageOverlay is one less the BusyOverlay, this is to make sure the busy indicator is always displayed at the highest order and hence would be an overlay on top of the message overlay:
    The message overlay is trigger by the binding MessageMonitor, this is an implementation of the following interface, the one I'm using is shown below along with interface:
    Loading ....
    What you see is the message is exposed as a view model implementing the IMessageViewModel interface, the implementation I'm using is shown below as you can see I'm injecting in the actual message and the busy indicator, I use these to simulate an action when the 'Show Busy & Close' button is clicked.
    Loading ....
    The code is available for download from github.
    Read More
    Posted in C#, Development, MVVM, WPF | No comments

    Saturday, 2 November 2013

    Using IoC nested lifetime scopes with View Models in MVVM

    Posted on 11:37 by Unknown
    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 during the processing of the request is viewed as being part of the transaction and therefore when the request is completed any memory allocated during the processing of the request can be garbage collected.  Whether the request is successfully or not is irrelevant in this context the important concept is the freeing of the allocated memory- controller, services, view engines etc. This pattern takes the form of using a nested (child) lifetime scope inside the IoC container used to host the web service - each request is processed inside a unique lifetime scope and when complete this scope is disposed. 

    Can I apply this pattern to view models in a WPF (XAML) application?

    To clarify what I mean, I'm not referring to every possible view model in an application, I'm referring to the main view model for a screen within an application where there could be multiple screens open at the same time.

    You'll probably thinking - why?

    Separation of concern  - the separating of different screen concerns from the point of view of the IoC container, this leads to better design of services, specifically shared services within the view models of a a screen - you don't have to be concerned with designing scoping into services & view models because it's taken care for you by the nested lifetime scope. The other main benefit, and this is more tangible, is the tracking down of high memory usage and leaks - because when the nested lifetime scope in the IoC container is disposed then everything allocated in the container should be disposed and the memory freed, anything that is still 'reachable' is likely to be a leaking allocation.

    Before I jump into the code I better define a couple of key terms:

    Workspace - this is the root class for a UI, it contains the main view model, controller and any resources (XAML). Instances of this class will be created in the nested lifetime scope of the IoC container by a WorkspaceFactory class,

    Chrome - this is the application chrome, everything UI that is not a Workspace - the layout, menu, title bar etc.

    In the following screenshot the Chrome is highlighted yellow and the Workspace is highlighted in red:
    Before I get into the details about the classes, lets have a look at the example UI. When the user selects a Workspace from the combo box it is rendered into the application - the Workspace fills the available space, shown below are three of the example Workspaces:
    From a technical point of view when the user selects a Workspace from the combo box the following happens:

    1. A new IoC nested lifetime scope is created,
    2. A WorkspaceFactory class is created inside the newly created IoC nested life scope,
    3. A new Workspace is created using the newly created WorkspaceFactory,
    4. Any XAML resource required for the Workspace are dynamically loaded,
    5. The view model is created and bound to the UI,
    6. Any previous Workspace is disposed.

    Starting with the application boot-strapper, this uses Autofac for all IoC concerns and as you can see from the code snippet below there isn't much going on:
    You can see pretty standard IoC registration stuff, the interesting parts start at line 49 where the WorkspaceFactory type is register as instance per nested lifetime scope - this basically means a singleton per lifetime scope. The next line is the actually building the IoC container and then resolve the root WorkspaceFactory instance - this is the important part you can see the root scope IoC container interface is being injected as a constructor parameter.

    The Workspace is shown below, as you can see it's a very simple class containing the Controller which has the view model, any XAML resources and importantly an injected function to be called when the Workspace is being disposed - this is the important part when it comes to clean up, the Workspace which is the root object in the nested lifetime scope disposes the actual nested lifetime scope, which means everything in the nested lifetime scope is disposed when the Workspace is disposed :)
    Loading ....
    The WorkspaceFactory is shown below, the responsibilities are to created the nested lifetime scope, created the WorkspaceFactory for the newly created nested lifetime scope and then finally created the Workspace instance.
    Loading ....
    The WorkspaceFactory is used by a WorkspaceDescriptor, these descriptors are used in the example application to populate the names in the combo box. When a selection is made the CreateWorkspace method on the WorkspaceDescriptor is invoked which uses the WorkspaceFactory to create the Workspace (which contains the view model). The Example WorkspaceDescriptor is shown below:
    Loading ....
    These classes are part of the following structure, you can see there are 4 workspaces defined - AnotherExample, Example, Recursive & YetAnotherExample. Each workspace has a Controller, View Model and XAML resource files. The application Chrome is defined in the Startup directory, specifically the Chrome is defined by the MainController, MainViewModel & MainWindow:
    One final class of interest is the WorkspaceHost user control. This has two responsibilities, firstly rendering the content (view model) of the Workspace and secondly loading any XAML resources. Importantly these resources are scoped to the user control they aren't loaded into the application resources, this is to prevents any resource naming clashes across Workspaces:
    Loading ....
    The XAML is very simple:
    Loading ....
    To demostrate it working I've used Ants Memory Profiler, I took several memory snapshots during the application, and each time I've highlighted on the screenshot the number of LifetimeScope instances there are 'live' in the application. A LifetimeScope object is an Autofac class which represents a lifetime scope inside the Autofac IoC container.

    There's 1 LifetimeScope when the application is first started and a Workspace has not been selected:
    There's 2 LifetimeScope instances when I selected a Workspace from the combo box:
    And then the count drops back to 1 for the number of LifetimeScope instances when the Workspace selected is cleared from the combo box:
    Earlier I mention the different types of Workspace in the example application, there is a special one called Recursive. This is a Workspace which hosts a nested instance of the application it's self - hosts the application inside application ad infinitum. See below for what I mean, again I've highlighted the number of LifetimeScope instances:
    The code is available for download:

     
    I've also pushed an updated version of this code base to github - Simple.Wpf.Composition.

    Read More
    Posted in Development, IoC, ViewModels, WPF | No comments

    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
    Older Posts Home
    Subscribe to: Posts (Atom)

    Popular Posts

    • Unit testing Rx methods Timeout & Retry with moq
      Earlier this week I was trying to unit test an asynchronous service (Foo) which used another asynchronous service (Bar) internally and ran i...
    • Understanding RefCount in Reactive Extensions
      A couple of weeks ago  @LordHanson  & I ran into an issue converting a stateless async service exposed as an Rx cold observable to a  co...
    • StructureMap: ILifecycle
      The other day I wanted to control the scope of a service inside a web based app with semantics which didn't fit either 'HttpContextS...
    • 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...
    • How many pins can Bing Maps handle in a WP7 app - part 1
      part2 -  http://awkwardcoder.blogspot.com/2011/10/how-many-pins-can-bing-maps-handle-in.html part3 -  http://awkwardcoder.blogspot.com/2011/...
    • Bad developers love 'The Daily WTF'
      When 'The Daily WTF' started up back in 2003/2004 it was a great laugh looking at shocking code other developers wrote, but after a ...
    • Using CompositeDisposable in base classes
      To help make an object eligible for collection by the GC (garbage collector) one would implement the IDisposable interface. Executing the di...
    • Implementing a busy indicator using a visual overlay in MVVM
      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 whil...
    • Daily Dilbert Service - the most important service I've ever written...
      NuGet package available here ... First off a big shout to  @hamish  &  @leeoades  on this one - I'm just blogging about it. At work ...
    • Comparing performance of .Net 4.5 to .Net 4.0 for WPF
      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 dec...

    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