Monday, 19 September 2011

Windows 8: First Impressions

The wait is over, and by now many of you have had a chance to take Windows 8 Developer Preview for a test drive.  I haven't spent a huge amount of time with Win 8, but enough to form some initial opinions.

Start Screen and Touch

It appears Microsoft has opted to bring Touch front and center, as evidenced by the Start screen.  Unfortunately the experience is not terribly rewarding for desktop users with a traditional keyboard and mouse.  I am being kind here.  In fact, after spending a couple of hours with the Start screen I was looking for ways to turn it off.  Not because it is bad, just unnecessary.   I would liken it to running Media Center has your main shell.  Nice to look at, but in terms of productivity and value add, it brings very little to the table.  Great for tablets, but please Microsoft, make it optional for desktop users.
Desktop users are desktop users because we use a keyboard and mouse out of necessity; because we are primarily using applications like Visual Studio, Photoshop and Office.  I have no intention of running these applications on a tablet. So why impose obvious tablet-design on users who don't need them?

Metro UI

I am a big fan of Metro UI design and Win 8 has it in spades.  But again, this is central to the new shell and is of value to tablet users.  It feels like the desktop has taken a backseat, with Metro hogging the limelight.  On the desktop we see very little Metro influence, which is unfortunate, because Metro design principles could be put to good use.  For example, take a look at the newly designed Task Manager.
This design is influenced by Metro and is beautiful.  I would like to see the entire desktop adopt a similar look and feel.
Windows has been criticized for being Windows.  That rectangular boxes with content that can be minimized and resized were so 90s.  So what?  It's actually pretty workable, which is maybe why it's been with us for so long.  Could it use a facelift? Sure, but I don't see the value in discarding it as a concept.  But, with the time I've spent with Win 8 it feels like Microsoft is almost ashamed of its roots.  And that Metro represents it's commitment to it's new forward-thinking Un-Window philosophic shift.

The Eco-System
Microsoft's goal of a computing eco-system has been getting a lot of press.  I just have to ask Why?  Why an eco-system?  Why does my phone, tablet, laptop, desktop and TV have to share the same user experience?  Are the IT consumers so thick that they just can't cope with differences across these devices?  I think not.  If Windows 8 is the solution, what is the problem?  I've never felt stressed out that I use Android on my phone, Win 7 on the laptop/desktop, Media Center on the TV, and more recently WebOS on the tablet.  There are things I like and dislike about each of those.  I've never sat there and dreamt of a perfect world where all these devices work and function the same way...ahhh...think of it.

Conclusion
I understand it is early days, but my initial impressions of Win 8 were disappointing.  It feels too devoted to touch and IT consumers and less to hardcore computing (software development, databases, CGI, etc).  In its current state, I'll be looking for the "run as Win 7" hack.

Labels: ,

Monday, 25 July 2011

Metro for Dummies Part 4

I've adjusted my font sizes, along with my target screen size (1280 x 720).


I'm now going to turn my attention to my colour palette.

Picking your Palette
Because your Metro design is minimalistic, selecting the right font and palette is crucial for the whole design to work.

There are plenty of resources on the web which details the science of colour and colour combinations.  I tend to pick my palette based on what looks good or what works.  I know this is not terribly precise, and there probably is a methodology to do this.

I like to work with tools like Kuler.

I don't think there is any right or wrong here.  Similiar to picking your font, you need to play with it until it seems right.

For my sample application I've chosen this palette for my black background.

Applying my colour palette to my mock-ups...

















Next, I will need to nail down colour conventions for various controls and states (Hover, Disabled, Invalid, Selected, etc).  This may require expanding my palette, but should not require additional core colours.

Until I am satisfied with a full application screen mock-up, maybe a search screen with search results and a detail dialog, the colour assignments are likely to get shifted around.  I think consistency is probably more important than precision when working this out.  I'm sure you could find an expert to tell you this colour should or shouldn't be used with that colour.  But, at the end of the day, it's about what your client likes and fulfilling the purpose of the application.


Labels: ,

Sunday, 24 July 2011

Metro for Dummies Part 3

Font Sizes

Once I've selected my base font I then work out font sizes.  This is best done in Photoshop or other graphics application.  I prefer to use a Word/HTML/CSS styled naming convention for my font size (H1, H2, H3, etc).

This is often influenced by the target device.  In the example above, I'm targeting a laptop/desktop device with a minimum screen resolution of 1024 by 768.
I'll then mock-up some sample uses of these fonts and sizes, still working in Photoshop.  This gives me a feel for the sizes, screen real estate and spacings.  I'm not sure what you would call this? Feng shui, for a lack of better term.  But there seems to be a natural balance of content, space and function.


I usually do this without using a colour palette.  I don't want the colours to bias my perception of the content and space.  Once I apply my palette, it should enhance my design.  But my design should not depend on the palette.  So, I make it work without one.
Do as many mock-ups as needed.  Time spent in Photoshop is well spent.  I find that the simplicity of Metro makes this process quick and painless.  What you're really doing is establishing UI conventions for your application. 

Labels: ,

Metro for Dummies Part 2

Font Samples

The following is a collection of fonts which are primarily used for public signage.  Not all of these would be suitable for a Metro-styled user interface, but will give you some ideas on selecting a base font for your design.

Austria

Brusseline

Calvert


Casey

Clearview

DIN 1451

Drogowskaz


FF Meta

Frutiger

FHWA Series fonts

Futura

Gill Sans

Helvetica

Helvetica Neue

Johnston

Motorway

Myriad

NPS Rawlinson Roadway

Parisine

Rail Alphabet

Rotis Serif

Toronto Subway Font

Transport

Tratex

Univers

Labels: ,

Metro for Dummies Part 1

I have been experimenting with Microsoft’s Metro Design Language for the past couple of months, and wanted to share some ideas and tips I’ve picked up along the way.  I do not claim to be an expert on the subject, nor do I consider myself to be a visual designer.  I know what I like, but not always able to tell you why.

For those unfamiliar with Metro here is a good place to start:

Metro Design Language of Windows Phone 7

I do not recommend Metro Design Language being sold by Amazon.  It is a self-published book which contains about three pages on Metro UI and the rest is a copy and paste from Microsoft’s back catalogue.  At £29.00 it is quite simply, a rip-off.

Most references on the web speak of Metro and Windows Phone 7 in the same breath.  While it is true WP7 does incorporate the Metro design philosophy, it is however not alone; Zune, Xbox 360 and Windows Media Center utilise Metro to a greater or lesser degree.

What is Metro?
Metro is an internal code name for a typography-based design language created by Microsoft.

Microsoft defines Metro as..
Typography. Type is beautiful. Not only is it attractive to the eye, but it can also be functional. The right balance of weight and positioning can create a visual hierarchy. Additionally, well placed type can help lead you to more content.

Motion is what brings the interface to life. Transitions are just as important as graphical design. By developing a consistent set of motions or animations, a system is created that provides context for usability, extra dimension and depth and improves the perceived performance of the whole interface.

Content not Chrome is one of the more unique principles of Metro. By removing all notions of extra chrome in the UI, the content becomes the main focus. This is especially relevant due to the smaller screen size and gesture-based interactions.

Honesty. Design explicitly for the form factor of a hand held device using touch, a high resolution screen and simplified and expedited forms of interaction. In other words, be “authentically digital”

Gone are the days of Microsoft's User Interface Guidelines for Windows with its precision pixel specifications.  Metro represents a dramatic shift away from UI design.  Metro is much more fluid and dynamic.

Picking a base font
Since typography is central to a Metro design it's good to start with a nice clean font.  Your target device may influence what type of font you use.  My personal favourites, which look great on mobile devices as well as the desktop are:

Seqoe WP

Avenir

Segoe WP is a member of the Segoe font family specifically designed for WP7
Since Metro borrows heavily from civic and urban design, it is not surprising to find this last font used by the City of Amsterdam, as well as the Dallas airport and Hong Kong airport.
In many ways the design goals of public signage and Metro are alike.  They both seek to provide instant communication in a clean, unadulterated way.  The “user” has but seconds to understand and duplicate some piece of information while travelling down the motorway or while on a high-speed train.  Likewise, we want to provide instant understanding for our mobile user, often at a glance.
I have to admit this whole area of typography is somewhat addictive.  If you can recognise the aesthetics of the font, searching and viewing fonts can be time consuming; there are so many fantastic fonts to choose from.  
If you’re interested, this is a good jumping off point:
Signage Typeface at Wikipedia
You have been warned.
It is worth spending some time selecting your font.  It is going to dominate your Metro design.

Labels: ,

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.

Labels: , , , ,

Sunday, 17 October 2010

When isCode != Code?

You could say there are as many different coding styles as there are coders.  One in particular I find perplexing is the "inverse logic" approach.  I knew a developer to seemed to think 180 degrees from everyone else on the team.  Allow me to explain...

If we were designing a custom control, you may expect to find an IsVisible property.  This "inverse coder" would prefer an IsHidden property.  IsEnabled becomes IsDisabled, etc.

Within a method you may see something like:

public void SomeMethod()
{
     if(isSomeFlag)
     {
          //do something meaningful...
     }
}

Our "inverse coder" would see it like:

public void SomeMethod()
{
     if(!isSomeFlag)
     {
          return;
     }

     //do something meaningful...

}

My personal preference is to limit the number of exit points in a method, as in the former.  In complex methods, this individual would have several exit points all based upon some inverted logic.  Did it work?  Technically yes.  Was it intuitive and easy to follow?  Most times not.  The rest of the team, knowingly or unknowningly had to continually shift mental gears when debugging this code.  Based on this fact alone, I would say this is bad code, since it was inherently difficult to understand.  

Another example...let's say you want to write a method which processes an order, something like:
public void ProcessOrder(IOrder order)
{
     if(order.Status == OrderStatus.Open)
     {
          //order processing logic here...
     }
}
Pretty straightforward.  Our inverted coder sees it completely different, and goes has far to pervert the name of the method itself.
public void ProcessNonOpenOrder(IOrder order)
{
     if(order.Status == OrderStatus.Open)
     {
          return;
     }
}
Difficult where to begin to say what is wrong with that, other than it is more complicated than it needs to be.  As a coder I would expect to find an additional ProcessOpenOrder method to compliment this one, unfortunately not.

Another common inverse is:
if(null == someInstance)

as oppose to the more generally agreed upon:
if(someInstance == null)

or, my personal pet peeve:
if(0 >= myCollection.Count)

I simply have a bone-deep rejection of this.  And whenever I encounter it I have to stop and think about what it means.  Perhaps this is due to my own training patterns, years and years of well established coding practices, commonly agreed upon by most coders.  And I have to ask "What is the advantage of this?  What does it buy me to do it this way?"  I've searched and cannot find a reason.
I always strive to make my code simple, obvious and self-documenting.  Cryptic code is bad code, complex code is bad code.  When writing code as part of a team, self-expression or personal preferences have nothing to do with it.  What is important is that it is in alignment with the standards and practices of the rest of the team.

Including the way they "think".




  

Labels:

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...
        

Labels: ,

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.

Labels: ,

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

Labels: ,

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.

Labels: ,

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.

Labels: , , ,

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.

Labels: ,

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...

Labels: , , , ,

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.

Labels: ,

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.

Labels: ,