Thursday, 7 April 2011

MVVM Revisited

I have been working with MVVM and Prism for a couple of years now and have had some recent revelations which you may find useful.  Working with MVVM by itself, is relatively straightforward.   Combine it with other patterns, such as MVC and IoC, and things can get complicated.

Here is a common implementation of MVVM:

This example also utilises a CustomerController along with some services, all of which are supplied by the “Model”.  If you’ve worked with Prism you’ll probably recognise this rather unorthodox implementation of MVC, something I’ve never been comfortable with.  Injecting a controller into a ViewModel seems backasswards to me.  I would prefer to have the Controller be aware of the ViewModel and indirectly control/manage the Views.

Aside from being awkward, this approach does work.  But don’t expect your modules to be “modular”.  Sure, within your solution it will have the appearance of being a module, but it won’t very portable.  If you’re persistent and are dedicated, you can try to “reuse” the Customer module above, but be prepared to drag a half dozen dependent assemblies with it.

So, what is modularity without portability?  Without portability, modularity is reduced to a code organisation concept.  

Looking over this situation it occurred to me that the injection of dependencies in the ViewModel was pretty much unrestrained.  If the ViewModel needed it, just add another parameter to the constructor.  The entire Model was wide-open for consumption, provided it was registered with Unity.  Needless to say, this leads to greater and greater consumption, until finally the ViewModel is entrenched in implementation.

When viewed as a microcosm, MVVM can act like a tiered architecture.  And tiered architectures are great for scalable server applications, but pretty much ruin any hopes of portability.  

The other undesirable aspect of this is, while the ViewModel may require the ability to display a MessageBox (provided by the IMessageService), it has no use for the other 10+ methods provided by the service.  So, why not give it exactly what it needs – and no more.

One way to accomplish this through the introduction of a custom Model class:

Here the CustomerModel class defines exactly what the ViewModel demands of the Model.  In effect, it is a subset of the Model and is specific to that ViewModel.   It’s the ViewModel’s shopping list – “if you’re going to use me, this is my list of demands”.  It is now up to the implementer to provide this functionality – which is where the responsibility belongs.

With this approach the ViewModel has now been liberated and all of the “dependencies” removed.  Service methods have been replaced with delegates.  The ICustomerService can reside in the module itself, effectively making the CustomerModule a self-contained, standalone assembly.

A side benefit is that the View now contains no code-behind and is no longer dependent on the ViewModel interface.

While working through this I’ve created a new Prism sample solution, which includes a CustomerModule and an OrdersModule, Implementation project and a Shell.  I have reduced the module dependency down to a single Core assembly.  The Implementation project contains controllers, core services, a persistence manager, etc.  It knows about the modules and can orchestrate the workflow and manage the views.  The controllers “wire up” the Model and inject them into the ViewModels.   

At the moment, CustomerModule + Core is about as portable as it gets.

Monday, 20 September 2010

Update

After months of defect resolution and testing our code finally shipped this morning.  The effort to deliver this product was beyond anyone's estimation.  The difficulty was not so much on the .Net front, but more in the area of system coordination.

Some background...we set out to develop a WPF/Prism application which would be run on a mobile handheld device (think fat, rugged iPad).  That, in itself, is not terribly difficult, it was everything else that proved to be challenging.  Namely four separate SAP systems, all contributing data which get bundled up and distributed to the mobile device via SAP's NetWeaver.  And then back up again...

On a good day it's hard enough to get SAP to play with SAP, raise that to the fourth power and add SAP's own client synchronization framework in the mix...well, you get the idea.  It's a minor miracle it works at all.

This is my second large SAP/.Net development project, and this one being the largest and most complex of the two.  Now, I'm the first to admit that I can be a techno-bigot.  I love working with C# and .Net and frameworks like Prism and MEF.  There is a real elegance that can be achieved and when you get it right it's poetry in motion.

Compare that with SAP...well, it's a dinosaur.  A plodding, kludgey artifact from the Stone Age.  I'm sorry, it's not my intention to offend, but it's true.  I sometimes wonder how long SAP can continue, while the rest of the world races ahead with more and more sophisticated development tools?  Not to mention the inherent complexity and true cost of ownership.

That said, I can say SAP does what it says on the tin, often times with a half dozen SAP Consultants hovering over scratching their chins.  I have to admire these guys, namely because they have the patience and persistence to work with these types of systems.  I don't know if I could do what they do.  If the technology I'm working with becomes too restrictive or cumbersome or complex I simply find another.  Not so in the world of SAP.  What you see is what you get...warts and all.

Enough of that.  In the end, after shedding blood, sweat and tears, we got there and it was a real team effort of two very different IT cultures.

Now onto version 2...
        

Monday, 3 May 2010

Some Observations...

Sorry for neglecting this blog, I'm in the throes of delivering a large mobile application, which has consumed all my waking hours.

In our big push to get this product out the door, we've brought on-board additional developers.  Unfortunately,  they were not sufficiently grooved in to our architecture and coding standards.  As you can imagine, the result was less than expected.  One of the purposes of having a known architecture, in my opinion, is that it serves as a point of agreement within the team.  It defines where things are located, what function it performs, what its relationship is to other parts of the system.  In short, it establishes order and structure to a large number of projects and should bring about simplicity.

When someone does not adhere to the agreed upon architecture they can be counted upon to introduce complexity.  To the uninitiated faced with a solution with 40-50 projects, all is complex.  Any changes they introduce will undoubted contain that complexity.

On a similar note, regarding WPF....

Whenever I see Xaml loaded up with Alignment, dimension attributes, etc, or StackPanels within StackPanels within Grids within StackPanels...ad nauseum, I know what the developer was experiencing.  He is using more and more settings and properties to force the Xaml to behave a certain way.  This brute force approach always bloats your code and is always inefficient.  If the UI does not bend to your will, the compulsion is to add more settings - this is almost always a mistake.

My golden rule when working with Xaml is:  Less is More.

If I'm faced with sorting out some misbehaving Xaml, the first thing I do is delete all the unnecessary properties and work with the core object.

Anyway...just some observations.  I'm hoping to be more active on this blog once I've completed this current project.

One new development effort I've been working on in the evening, is creating a Win 7 Media Center Add-in using Visual Studio 2010 and the Media Center SDK.  It's my first attempt, so I hope to have something worthwhile to report.

Wednesday, 24 March 2010

New Composite/Pattern Forum

A new developer forum has been launched dedicated to composite technologies and design patterns, including Prism, MEF and MVVM.

http://www.compositedevpatterns.com/forum.php

Wednesday, 10 February 2010

Prism Guidelines

Introduction
Due to the number of projects and files which can make up a Prism solution, it is important to adhere to conventions which are intuitive and sensible.  Maintaining these conventions takes the guesswork out of working with Prism and makes navigating through a solution predictable.
This document assumes a basic understanding of Prism, the Model-View-ViewModel (MVVM) design pattern, the Model-View-Controller (MVC) design pattern and Windows Presentation Foundation (WPF).

Modules
Prism requires that each module contain a class which implements IModule.  This effectively serves as a stub, allowing Unity to load the module.  IModule has an Initialize method that is often overridden and is used to register items in the container.


Avoid using the Initialize method to register the module’s items, instead create an entry in your unity.config file.  It is easier to maintain and does not involve code.

Views
GOAL: To maintain a separation of UI and business logic.
It is rare that a UI requirement cannot be expressed using Xaml alone.  Effort should be made to eliminate any UI logic contained in the View. 

Views always have a corresponding ViewModel.

Setting the ViewModel
Each View should contain a setter for its ViewModel, as shown below.
This property uses the Microsoft.Practices.Unity.DependencyAttribute, which gets picked up by Unity and automatically set.

Use of Styles
Avoid defining custom styles which effect appearance within your module or view.  Instead, use styles defined in your application resource assembly.  If you need to modify a control’s behaviour through the use of a Trigger, use the BasedOn property of the Style, referencing the resource Style.
Always reference the resource Style by using a ComponentResourceKey defined in your Interfaces assembly.
Style="{StaticResource {ComponentResourceKey TypeInTargetAssembly={x:Type Resources:Styles}, ResourceId=DialogBorderStyleKey}}"

Use of Converters
Avoid excessive use of custom converters (IValueConverter).  Often the same can be accomplished using Triggers or DataBinding.  Converters can act as “hidden” code-behind, making testing difficult.  Always look for a Xaml solution before resorting to the use of converters.

Naming Conventions
TYPE NAMING RULE EXAMPLE
View <name>View CustomerDetailView
Interface I<name>View ICustomerDetailView


ViewModels
GOAL: To encapsulate all UI-related logic in a single, testable class.

The ViewModel exists to serve the View, so use it.  Instead of using custom Converters do it in your ViewModel.

Avoid passing the IUnityContainer (or an abstract version) in your ViewModel constructor.  This hides the actual dependency and makes testing difficult.

Consider implementing INotifyPropertyChanged on your ViewModel so your View can respond to changes in the ViewModel.

Naming Conventions
TYPE NAMING RULE EXAMPLE
ViewModel <name>ViewModel CustomerDetailViewModel
Interface I<name>ViewModel ICustomerDetailViewModel


Interfaces
GOAL: To provide contracts that define a public interface, separate from its implementation.

Prism relies heavily on the use of interfaces.  All entities registered in the UnityContainer must include an interface and an entity that implements the interface.

Do not include public interfaces in your implementation assemblies, as this defeats the purpose of decoupling interface from implementation.


UserControls
GOAL: To provide reusable UI elements independent of implementation.

WPF UserControls differ from Views in that they do not have a related ViewModel.

Consider adding DependencyProperties to your UserControl to take advantage of DataBinding and Triggers, this makes your UserControl more versatile and reusable.

Avoid including binding to specific properties in your UserControl as this can greatly limit its reuse.

Naming Conventions
TYPE NAMING RULE EXAMPLE
UserControl <name>UserControl AddressUserControl


Services
GOAL: To provide static, stateless business logic and functionality across domains.

Services are normally registered in Unity as a singleton.

It is best to think of Services as a static library of methods.  If state persistency is required consider using a Controller (MVC pattern).

When consuming Services, avoid accessing them through IServiceLocator, instead explicitly use the service interface in your class constructor.  This makes for predictable testing and does not hide functionality or dependencies.

Naming Conventions
TYPE NAMING RULE EXAMPLE
Service <name>Service LoggingService
Interface I<name>Service ILoggingService

Events
GOAL: To provide multicast notifications across domains.

Note: The events referred to here are to be used by the EventAggregator, not standard .Net events.

Do not define events in your implementation assemblies. Since other assemblies will need to reference your event class placing them in an implementation assembly forces you to create a strong reference. Instead, place it in your interface assembly or, if appropriate, a shared core assembly.

Naming Conventions
TYPE NAMING RULE EXAMPLE
Event <name>Event SaveCustomerEvent
Handler <name>EventHandler SaveCustomerEventHandler


Commands
GOAL: To provide an input mechanism which allows for multiple and disparate sources to invoke the same command logic.

Include command logic in your ViewModel, or if using a Controller you may want to defer execution to the Controller.

Consider using a Command Behavior AttachedProperty to convert events to Commands on controls that do not natively support ICommand.

Naming Conventions
TYPE NAMING RULE EXAMPLE
Command <name>Command SaveCommand
Handler <name>CommandExecute SaveCommandExecute
<name>CommandCanExecute SaveCommandCanExecute

Conclusion
Prediction and consistency go a long way in working with Prism. Not subscribing to agreed upon conventions adds confusion and slows down development.

Monday, 25 January 2010

Code Complexity and Prism

I've recently had to review a number of problem areas of a large Prism project.  In the course of review, I had a number of realisations regarding design patterns, WPF and code complexity.  We use MVVM and MVC design patterns throughout our project.  Not surprising, many of our problem areas were related to divergence from these patterns.

In our implementation of MVVM we strive to have a complete decoupling of our Xaml views and any business logic.  So, finding views riddled with code-behind indicated a lack of understanding of:

  1. The MVVM design pattern, or
  2. The benefits of code separation

Or as I was to find out, a limited understanding of Xaml.  The view in question utilised over ten custom converters.  Not that converters are inherently evil, however, these converters were being used where Triggers or Data Binding could have easily gotten the job done.  But, if one is unfamiliar with these, they tend to use techniques they are familiar with -- in this case, IValueConverter.  Poor use of custom converters effectively becomes "hidden code-behind," and is difficult to debug and test.

Additionally, I found the ViewModel being underused and misused, providing a sparse selection of high level properties for binding.  This, in part, prompted the excessive use of custom converters.

The offending code-behind was an unusual solution brought about by a lack of Xaml know-how.   All of this code could have been expressed using Xaml.  Conclusion: Knowing a little about Xaml can reek havoc on a well-structured Prism project.

The hallmark of these decisions is code complexity, your first clue things have gone astray.

After much refactoring, including the removal of all the custom converters, the code-behind and reworking the ViewModel, the whole area straighten out and was greatly simplified.  It was a prime example of the power and importance of design patterns in maintaining good form and structure.

Saturday, 2 January 2010

MEF Presentation Video

A work colleague recently turned me on to Microsoft's Managed Extensibility Framework (MEF) [see http://mef.codeplex.com/].  For anyone into Prism, MEF is worth a look.  Headed up by Glenn Block of Prism fame, MEF is an impressive technology.

Glenn gives an hour long MEF presentation at PDC 09 at http://microsoftpdc.com/Sessions/FT24.

In addition to an MEF orientation, there is a short presentation on MEF + Prism.

Exciting stuff, in a geeky sort of way.

Sunday, 27 December 2009

Prism Sample: Resources

An area of Prism development that often gets overlooked is the management of resources.  I mentioned in a previous blog that View reuse is unlikely, but that doesn't mean you should create unnecessary dependencies to a resource assembly.

Similar to modules, resource assemblies can have an accompanying interface assembly.  This is done by defining ComponentResourceKeys in your interface assembly and using them as resource keys in your resource dictionary and in your Views.

public static class Styles
{
    public static ComponentResourceKey LargeTextStyleKey
    {
        get { return new ComponentResourceKey(typeof (Styles), "LargeTextStyle"); }
     }
}

and in your Xaml...

<textblock text="My Sample TextBlock Style"
           Style="{StaticResource {ComponentResourceKey TypeInTargetAssembly={x:Type Interfaces:Styles}, ResourceId=LargeTextStyleKey}}" />

Taking this approach decouples your modules from the resource assembly.  The advantage to do this is not so much in the area of reuse, but more in the implementation of themes.  Any Views that require the use of a resource can simply refer to it by its ComponentResourceKey.

Additionally, I would only have the Shell load the external resources, since the View modules are now unaware of the external resource.  The only draw back in doing this is you will lose your Visual Designer when editing your Xaml, because the designer cannot resolve the resource to render it.

It is also worth setting up default styles based on control types, by using the control type as the resource key (e.g. {x:Type TextBlock}).  This does not require the use of ComponentResourceKeys.

The area of theming WPF applications is a common one and there are a number of resources on CodePlex which address this area.  One example is the Razre WPF Framework, or you can build your own ThemeManager.

Conclusion
I think this pretty much concludes the PrismSample articles.  This was meant as an introduction for developers starting out with Prism and to provide some guidelines in setting up a Prism solution.  I hope this was of some use.  I'm certain others will have differing opinions, and that's okay too.  I'm always on the hunt for new approaches and new ideas.

I think Prism has a real future in WPF development.  Once you get into it and see the benefits, it changes how you think about and view WPF development; afterwards it is difficult not to think and develop that way, which is a good thing.

As always, comments/feedback welcome...

Saturday, 26 December 2009

Prism Sample: Services

In addition to Views and ViewModels, your Prism application will likely have one or more Services.  Per the CAL documentation, a service is defined as:

A service is an object that provides functionality to other components in a loosely coupled way through an interface and is often a singleton.

This is a fitting definition, but doesn't indicate belongs in a service or when something should be service.  Services reside outside the View-ViewModel pattern and provide functionality to anything that needs it.  In practice a service should address an area of business logic and have an appropriate name which describes the functionality it contains, like CustomerService or DataService, etc.
Avoid making a service a dumping ground for functionality you don't know where to put.  I tend to view services as static libraries of functionality, generally consisting of methods (think WCF Service Contracts).  My personal preference is to avoid storing state or exposing properties in services.  I don't use services to control workflow.  Instead I would implement a Controller to govern the workflow, and have the Controller consume the service.
On one Prism project, we would have regular design meetings where we would discuss where a given piece of functionality should reside.  The governing rule that came about, was that the ViewModel is directly concerned with the View and servicing the View; code that belongs in the ViewModel is there because of some requirement dictated by the View.  If that wasn't the case, we were probably looking at a general piece of business logic which likely belonged in a service (or Controller, if one existed).
Following this line of thinking, we found more and more of our code moving to services, until we had a robust services layer, and a lean ViewModel which simply became a consumer of the services.  This approach prevented business logic getting lost or hidden in ViewModels.  It also supported our decision to separate out our services into their own assemblies, which I would highly recommend.

Sunday, 20 December 2009

Prism Sample: Modules

Central to Prism is the concept of modules and modular design, therefore it's worth spending some time defining exactly what a module is, what it contains and what it shouldn't contain.  Per the Prism documentation:

A module in the Composite Application Library is a logical unit in your application. Modules assist in implementing a modular design. These modules are defined in such a way that they can be discovered and loaded by the application at run time. Because modules are self-contained, they promote separation of concerns in your application. Modules can communicate with other modules and access services in a loosely coupled fashion. They reduce the friction of maintaining, adding, and removing system functionality. Modules also aid in testing and deployment.

Having worked on a number of Prism projects with a wide range of developers, each interpreting this from their own perspective and experience.

Two of the guiding principles behind this are:
Single Responsibility Principle
Separation of Concerns

While most can agree on these principles, views differ on the depth and extent to which they are applied.  On one end of the spectrum we have the theorist, whose motivation may be to strictly adhere to these (some times with religious fervor).  And on the other end we have the realist, who simply wants to build a working piece of software that meets the business requirements.

The theorist looks beyond the business requirement, while the realist may argue that strict allegiance to these principles is outside the scope of the requirements.  Somewhere, somehow these views are resolved, usually by an architect or team lead; and the result usually falls somewhere in the middle.

Personally, I fall in the middle, and maybe lean towards the realist.  I don't feel software development should be an academic exercise.  If someone entertains the idea of using a certain design pattern, I'm always interested in "what problem does this solve?" and "what does it buy me?"  Unacceptable answers are "because Fowler said so" or "because that's what the Prism team does".

Enough of this, let's talk about modules...

In an earlier post, I talked about creating an Advertising module for Blogger and said I would create the following modules:

Blogger.Advertising.Interfaces
Blogger.Advertising.Views
Blogger.Advertising.ViewModels
Blogger.Advertising.Services
Blogger.Advertising.Services.Interfaces

Some developers would be tempted to bundle these up into two assemblies:
Blogger.Advertising
Blogger.Advertising.Interfaces

storing their Views, ViewModels and Services in a single assembly.

And I could be convinced of this.  It's certainly easier to maintain.  But I would argue that Views/ViewModels and Services are logically separate and warrant their own assemblies.  It's not inconceivable that another module or system could be a consumer of these services, without the need for Views or ViewModels.

So, why separate out Views from ViewModels?

I think it is somewhat idealistic to expect Views designed for Product A to be simply dropped into Product B (two different implementations).  In theory this is possible, but in practice I've never seen it happen.  Here we get into areas of look and feel and layouts.  While we can do a lot to make a view generic and use themes and skins to alter its appearance, at the end of the day there is always going to be something different or required which makes the view unusable.  So why bother?

I always assume my views are not going to be reusable; that they're part and parcel to a specific implementation.  My ViewModels, however, are completely reusable.  I would also argue that mocking up Views is far less time consuming than the creation of ViewModels.

Regardless of what I think, your design decisions are going to be driven by a number of factors.  I think its important to consider all views and options, and decide which is suitable.

Thursday, 17 December 2009

Prism Sample: Basic Concepts

As stated in my earlier post, this model solution attempts to illustrate how Prism and Unity are used, what is a module, what belongs in one and what doesn’t, the use of interfaces and design patterns.
One of the most basic aspects of code organisation is knowing “what goes where”.  This is especially true with Prism projects.  Given you will likely have a dozen or more projects in your solution, it’s pretty important to sort out early on where things belong.
I always try to minimise dependencies between my assemblies; and from time-to-time work-out what would be required to take a module and drop it into another application.  I’m always looking for ways to remove a dependency or decouple.  Even if I don’t have an immediate requirement to do that, as a general rule it’s a good idea.

Namespaces
Picking the right naming convention for your projects and namespaces is pretty important.  I would spend ample time on this before embarking on any serious coding.  Maybe start with a prototype solution and put in some basic modules, a shell, some services, and their accompanying interfaces.  Play around with it and massage it into something you're comfortable with.  I think there is a natural order and organisation for these various projects and components.

Microsoft's recommended namespace convention is:
Company.(Product|Technology)[.Feature][.Subnamespace]

for example, if I were creating an advertising module for Blogger, I would see something like...

Blogger.Advertising.Interfaces
Blogger.Advertising.Views
Blogger.Advertising.ViewModels
Blogger.Advertising.Services
Blogger.Advertising.Services.Interfaces

Microsoft has an excellent guideline for create .Net components at: http://msdn.microsoft.com/en-us/library/ms229026.aspx

Implementation vs Interface
It's important to understand the difference between implementation and interface as it applies to modular development.  An interface is simply a public contract that defines an exposed surface.  Whereas, implementation deals with the deploy or realisation of the interface.  Interfaces do not contain business logic,  simply a definition of what something will look like once it is implemented.
Prism and Unity makes heavy use of interfaces.  Interfaces are mapped to your implementation classes, either in code or in a configuration file.

The following tips may be obvious to some, but I felt it was worth mentioning:

Tip #1 - Do not create strong references to implementation assemblies.
The exception to this are assemblies which comprise your Model.

Tip #2 - Do not place anything in your implementation assemblies which forces other assemblies to create a strong reference.
An example of this are Event classes.  You may have a module which publishes events, presumably to be subscribed to by other modules.  Do not include the Event class in your module assembly, instead place it in your module's interface assembly.  This makes it available to other assemblies though the interface reference.  Another common example are enumerations.

Tip #3 - Do not register your implementation classes in the Module Initialize method.
Registering classes in the Initialize method implies a specific implementation, but not all implementations.  Instead map your classes in a Unity configuration file.

Tip #4 - Do not inject views into regions in the Module Initialize method.
I never understood why anyone would want to do this, as it pretty much ruins any chance of reusing the module.  Instead, delegate view orchestration to another module, layer or layout manager.

In fact, I can't think of good reason to put any code in the Module Initialize method.

These tips address some hidden or covert implementation that commonly occurs in Prism development.

Wednesday, 16 December 2009

Prism Sample: Introduction

I had a request to post some sample code illustrating the use of Model-View-ViewModel pattern, Controllers and DelegateCommands.  This lead to the creation of a sample Prism solution.  An interesting exercise, since it gave me a chance to incorporate many of what I consider to be Prism best practices.
I consider proper solution setup and organisation to be critical in working with Prism.  Mistakes made in this area often come back to haunt you.  There are many ways to organise your projects and code.  What is probably more important is pick a solution structure that everyone can agree with and stick with it.  A lack of agreement or ignorance of architecture can make team development a nightmare.

I intend to write a series of postings detailing out what I consider to be areas of interest, and why I've organised things as I did.
You can download the solution here (408kb).  You will require Visual Studio 2008 SP1.  I've stripped out all XML documentation and PDBs to keep the file size down.

Please let me know if you run into any problems loading and running this solution.

Thursday, 3 December 2009

Some Agile thoughts...

Is it me, or have others found Agile development projects to be chaotic?  I will not profess to be an expert in this area.  I've been a developer on about four Agile-based projects, ranging from a handful of developers to a team of 20.  And, on the larger projects, the more Agile is pushed the more chaos seems to result.

At worst it feels like a mad coding free-for-all, in an effort to meet development targets, while abandoning or ignoring coding conventions and best practices.  The idea being, "if we just get the cards done...the project will get done".

I don't know how many times I've coded up a piece of functionality, written tests, etc., only to find weeks later, that someone else on the team "refactored" it, rendering it unusable.  One step forward, two steps back.  I've only really experienced this on Agile projects.

Don't get me wrong, when I first encountered Agile I felt it had merit; and I still do.  But somewhere  between theory and execution the plot can get lost.

I've always consider myself to be self-managing.  You give me a spec and I will methodically design, develop, test and document it to a finished product.  Maybe that's a bit old-school, but it got the job done.

I would be interested in what others think about this.

Tuesday, 20 October 2009

Win 7 Anti-Virus

For those of you running Win 7, you may have found it frustrating finding a suitable anti-virus product.  From experience, major players promoting Win 7 compatibility have proven anything but.
A friend told me about Microsoft's new Security Essentials, which handles anti-virus, spyware and malware detection.  Best of all, it's free!  You can download it here:

http://www.microsoft.com/security_essentials/default.aspx

Unlike other products, Security Essentials has a remarkably small footprint and has negligible impact on performance.  Highly recommended.

Friday, 16 October 2009

The Golden Age of UI Design

If you’ve been using computers as long as I have, you will be familiar with the evolution of Windows, from the humble 3.x on up to Win 7. A lot has changed over the years. As developers we have had to shift gears with each new incarnation. I’m probably dating myself if I mention Windows 3.1 and VB 3.0, but given the time, VB 3 practically ushered in RAD and allowed developers to create respectable UIs for the platform.

With regards to the Windows User Interface, I can still remember the release of Windows 95 and all the fervour it created. There were developers and IT pros complaining bitterly about the change, citing their preference for 3.1 and their dislike for the new battleship grey 95. Those of us who embraced 95 in all its greyness, found new UI controls in our toolbox, most notably the Windows Common Controls. Enthusiasts, like myself, poured over Microsoft’s Windows 95 User Interface Guidelines book, a tome containing pixel by pixel specifications for creating standard Windows applications.

If you were like me, this wasn’t enough. The next rung on the ladder was exploiting (some times questionable) Win API and GDI hacks, all in the attempt to enhance our application interfaces.

The advent of .Net put an end to much of this. Designing WinForm applications certainly got easier and custom UIs no longer required slimy hacks. But, we were still limited to XP styled desktop applications.

Concurrent with the advancements in Windows programming, the internet exploded and took centre stage. Graphic designers and illustrators sat side-by-side with application developers to create a new breed of user interface. User expectations were raised; not only did a UI have to be functional, but it had to be sexy as well. Flash and Shockwave designers and developers expanded this further, raising the bar even higher.

All of these advancements made WinForms look rather antiquated.

All this was about to change with the release of .Net 3.0 and the introduction of Windows Presentation Foundation (WPF). For those unfamiliar with WPF, WPF is a XAML-based framework for creating Vista-styled desktop applications. Think XHTML meets WinForms and you’re almost there.

Not only was WPF structurally different from its WinForms cousin, but included new resources and functionality WinForm developers only dreamed of. At last, desktop developers could create dynamic, sexy user interfaces that rivalled their contemporaries. The capabilities of WPF are so vast, that if you can dream it, you probably can build it.

Gone are the stringent interface guidelines dictated by Microsoft; in its place are new collaborations between graphic designers and artists and software developers to produce user-centric software. All-in-all, this change is rather liberating. Where its headed I don’t know; will it be different from the past? Guaranteed.

However, this is no Holy Grail. Designers and developers will still manage to produce repulsive, poorly designed software. But this is a chance we’re going to have to take.

Wednesday, 7 October 2009

Using OnValidate method in LINQ to SQL

If you are using LINQ to SQL you may have noticed the OnValidate partial method.

public partial class Person : INotifyPropertyChanging,
                  INotifyPropertyChanged
{
     ...
     partial void OnValidate(ChangeAction action);
     ...
}

This method gets automatically called when the class participates in the DataContext SubmitChanges.

When working with LINQ to SQL classes I prefer to keep my code generated classes separated from any modifications or customisations.  Normally, I will create a folder in my project called ExtendedClasses, there I can extend my business objects, giving them a <classname>.extended.cs file name.  This allows me to regenerate my business objects without fear of losing these customisations.

So, in my extended class file I will include...

partial void OnValidate(ChangeAction action)
{
    if (action == ChangeAction.Insert)
    {
        //Do validation for inserts
    }
   
    if (action==ChangeAction.Insert ||
        action==ChangeAction.Update)
    {
        //Do basic validation for inserts and updates
    }
}

I avoid including any business rules in this class level validation, and stick to data related validation, such as field lengths, data ranges and required fields all based on my data model.  Any validation errors get raised by throwing an exception.
Because the OnValidate method is private, you may want to include a public Validate method.

public void Validate()
{
    if (PersonId==Guid.Empty)
    {
        OnValidate(ChangeAction.Insert);
    }
    else
    {
        OnValidate(ChangeAction.Update);
    }
}

With the public Validate method I can validate my business object from the UI layer before passing it down to my services layer.

try
{
    person.Validate();
}
catch (Exception e)
{
    MessageBox.Show(e.Message + "\n\n" + e.StackTrace);
    return;
}

Tuesday, 15 September 2009

UK Post Code Search using LINQ to XML

I recently delved into working with UK Post Codes, including validation and searching.  This is not my first contact with this area, and in the past it has always involved large SQL tables or by using third-party products.

This time, I was looking for something a bit more portable, like XML.

I was able to find freeware downloads of UK Post Codes including their longitude and latitude, which was easily imported into a SQL Server database.

I've created a class library called PostCodes.UK, which contains useful methods for validating post codes and determining which post codes fall within a given radial distance from a target post code.  All of the search and validation routines utilise LINQ to XML to query the XDocument.

The class library relies on a PostCodes.xml file (supplied in the Test Harness project), which gets loaded as an XDocument.  I've included a small WPF Test Harness application which illustrates how this library is used.


To run this solution you will need Visual Studio 2008 SP1.  The source code is available here.

For those interested in this area, there is an informative government page on Postal Geography, which explains the structure of the UK post codes.  You should be aware that UK post codes are always changing; however, if all you need is outward code resolution (e.g. PO6 ), chances are you can make do with public domain data.

Another site with useful information is: http://www.easypeasy.com/guides/article.php?article=64

Thursday, 10 September 2009

Juan Enriquez Video

A friend recently sent me this link to a presentation made by Juan Enriquez on TED.

http://www.ted.com/talks/juan_enriquez_shares_mindboggling_new_science.html

Enriquez has a unique viewpoint on recent global events, namely with the economy and technological advancements. And he has a sense of humour which appears to be a rare commodity nowadays.

Worth having a look.

Tuesday, 8 September 2009

IsIn Extension Method

Another useful extension method I've found is the IsIn() method. This is comes in handy when you have to test for enumeration values, for example:
public enum StatusValues
{
 Open,
 Closed,
 Pending,
 Cancelled,
 Expired,
 Suspended
}

   ...

if(myObject.Status == StatusValues.Closed ||
   myObject.Status == StatusValues.Pending ||
   myObject.Status == StatusValues.Expired)
{  
   ...
}

This can become cumbersome when testing for a number of values.

The IsIn Extension Method simplifies this by taking a param list of values.
public static bool IsIn<T>(this T thisObject, params T[] values)
{
    if (thisObject != null && values != null && values.Length > 0)
    {
        foreach (var value in values)
        {
            if (thisObject.Equals(value))
            {
                return true;
            }
        }
    }

    return false;
}
Using this method, the above code can be rewritten as follows:

//using the IsIn Extension Method
if(myObject.Status.IsIn(StatusValues.Closed,
                        StatusValues.Pending,
                        StatusValues.Expired))
{
   ...
}

Monday, 31 August 2009

Retro Flip Clock WPF Control

I know, I know...I last thing we need is another WPF Clock.  However, I recently went looking for a Flip Clock control and found surprisingly few - in fact, no usable ones.  So, it was back to the drawing board.

Most of the attention has been on appearance, rather than functionality.  Feel free to modify and enhance.
You can download the source code with sample project here.

Sorry for the broken link, the server that hosted this file has been rebuilt and no longer contains my downloads.  Here is a link on my SkyDrive.  This zip file contains the core files, you will need to add them to a project.