Wednesday, 28 July 2010

Service Locator pattern

A pattern that is showing up frequently in .Net development at the moment is Service Locator. It has appeared in the Composite Application Library (Prism - intended for use in Silverlight and WPF applications) as well as ASP.Net MVC. Service Locator is often seen going hand in hand with DI and IoC and one useful implementation of Service Locator might be to decouple an application from specific IoC containers (i.e. use the Service Locator pattern on top of IoC).

In essence, Service Locator is a simple pattern:

“Provide a global point of access to a service without coupling users to the concrete class
that implements it.”
*
Martin Fowler describes the pattern in the following terms:
“The basic idea behind a service locator is to have an object that knows how to get hold of all of the services that an application might need.” **

service-locator

The Composite Application Library documentation offers a number of drawbacks to Service Locator:

“The Service Locator pattern has the following liabilities:
  • There are more solution elements to manage.
  • You have to write additional code to add service references to the locator before your objects use it.
  • Your classes have an extra dependency on the service locator.
  • The source code has added complexity; this makes the source code more difficult to understand.” ***

In short the criticism is that Service Locator adds complexity to the application. Martin Fowler also notes that use of Service Locator can lead to testability issues:

“I've often heard the complaint that these kinds of service locators are a bad thing because they aren't testable because you can't substitute implementations for them. Certainly you can design them badly to get into this kind of trouble, but you don't have to.”

Common Service Locator

Many frameworks (including MVC 3) are now working to the Common Service Locator library. This is described in the following terms:
“The Common Service Locator library contains a shared interface for service location which application and framework developers can reference. The library provides an abstraction over IoC containers and service locators. Using the library allows an application to indirectly access the capabilities without relying on hard references.”
A number of IoC frameworks already provide implementations of the core interface (IServiceLocator) including Spring.Net, Unity, and Castle Windsor. The IServiceLocator interface requires that an IoC container provide the following methods:
TService GetInstance<TService>();
object GetInstance(Type serviceType, string key);
TService GetInstance<TService>(string key);
IEnumerable<object> GetAllInstances(Type serviceType);
IEnumerable<TService> GetAllInstances<TService>();

This is interesting but one has to ask if it’s an abstraction too far.

Update: If you are considering using the Service Locator pattern you should be aware that it is regarded by many as an anti-pattern. See Service locator anti-pattern.


* Service Locator, Game Programming Patterns / Communicating Patterns
** Using a Service Locator, Martin Fowler
*** Service Locator

Friday, 23 July 2010

A reminder about boxing and unboxing in C#

Here is a quick reminder about boxing and unboxing in C#. MSDN documentation contains this concise description of boxing and unboxing:

“Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. When the CLR boxes a value type, it wraps the value inside a System.Object and stores it on the managed heap. Unboxing extracts the value type from the object. In the following example, the integer variable i is boxed and assigned to object o.” *

All primitive types (byte, char, int, long, etc.) and structures are value-based types derived from System.ValueType. Because value types are stored on the Stack they can be created and accessed more efficiently than reference types. Reference types are stored on the Heap and must be accessed using references.

An example of boxing and unboxing:

int i = 123;
object o = (object)i; // boxing
int j = (int)o; // unboxing

Why is this important?

Boxing and unboxing operations are computationally expensive in relation to other simple assignments (for example, when a value type is boxed, a new object must be allocated and constructed). If you have code which undertakes a lot of boxing operations you may run into performance issues.

Determining which methods and properties will cause boxing is possible by checking their their signatures. If a method takes an argument of type object or the argument is an interface then if you were to pass in a value type instance it will be boxed.

Note it is very easy to slip into boxing operations:

var sb = new StringBuilder();
for(int i = 0; i < 10; i++)
{
    sb.AppendFormat("Boxing: {0}, {1}", i, i + 1); // Boxing here   
}

You could get around this by calling the ToString() method early to prevent allocation on the heap:

var sb = new StringBuilder();
for(int i = 0; i < 10; i++)
{
    sb.AppendFormat("No boxing: {0}, {1}", i.ToString(), (i + 1).ToString()); // No boxing   
}

Value types and reference types

Again MSDN documentation provides a description of value types:

“Variables that are based on value types directly contain a values. Assigning one value type variable to another copies the contained value. This differs from the assignment of reference type variables, which copies a reference to the object but not the object itself.” **

There are 2 main categories of value types:

  • Structs (e.g. numeric types: integral types, floating-point types and decimal; bool; user defined structs)
  • Enumerations

In essence, value types are lightweight objects that are allocated on the current thread's stack (see Stack and heap below). There are exceptions to this (e.g. when a value type is allocated as an element of an array or is a field of a reference type). When an instance of a value-type is created a single space in memory is allocated to store the value. When instantiating a reference type an object is created in memory and is handled through a reference (somewhat like a pointer).

Stack and heap

The Stack can be thought of as being responsible for keeping track of what's executing in the code (the call stack). When a method is called (a Frame) data is pushed onto the Stack. Once the method executes the data is popped off the Stack and is discarded. Only the ‘top’ item is available in the Stack (typical behaviour for a stack being a last-in-first-out memory structure).

The Heap can be thought of as being responsible for keeping track of the objects referenced by the code. Any element in the Heap can be accessed directly.

Garbage collection

The Stack does not require garbage collection. It is self-maintaining because items are popped off the stack and discarded as they are used during program execution. On the other hand the Heap is subject to garbage collection.

* Boxing and Unboxing (C# Programming Guide)
** Value Types (C# Reference)

Friday, 23 July 2010

Sunday, 18 July 2010

Visual Studio 2010 keyboard shortcuts

Here are a bunch of keyboard shortcuts for Visual Studio 2010 that I find useful but keep forgetting.

Code completion

Ctrl + Period (.) - Expands the Smart Tag Menu (e.g. to add a ‘using’ statement).
Tab - Inserts expanded code snippet using a shortcut (for example type ‘class’ and hit Tab twice)
Ctrl + Space - Completes the current word in the completion list

Building, running and debugging

Ctrl + Shift + B - Build the solution (also try F6)
F5 - Start the application with Debugging
Ctrl + F5 - Start the application without Debugging
F9 - Sets or Removes a breakpoint at the current line

Navigation

Ctrl + ] - Moves the cursor to the matching brace in the source file
Ctrl + Hyphen (-) - Moves cursor to its previous position
Ctrl + Shift + Hyphen (-) - Moves cursor to the next browsed line of code
Shift + F7 - Switch between the Design and Source View of the document
Ctrl + Shift + F - Displays the ‘Find in Files’ tab of the ‘Find and Replace’ dialog box
Shift + F12 - Displays a list of all references for the symbol selected
Ctrl + / - Moves focus to the Find/Command box

Windows

Shift + Alt + Enter - Toggle Full Screen Mode
Ctrl + M + O - Collapses all Regions to provide a high level overview of the types and members in the source file
Ctrl + M + L - Toggles all previously collapsed Regions
Shift + Esc - Closes the current Tool Window with focus

Other shortcuts

Ctrl + Alt + L - Show Solution Explorer
Ctrl + Shift + A - Displays the Add New Item dialog box
Alt + Shift + A - Displays the Add Existing Item dialog box

Friday, 16 July 2010

Comparing the MVC, MVP and MVVM patterns

Having spent some time looking at several presentation technologies recently I thought I should take stock of a number of design patterns that are frequently referenced.

Silverlight and WPF are often associated with the Model-View-ViewModel (MVVM) pattern (see frameworks such as Prism, MVVM Light, Caliburn etc). ASP.Net MVC of course utilises Model-View-Controller. In the past I have tried to overcome some of the short-comings of ASP.Net Web Forms using variations of the Model-View-Presenter (MVP) pattern.

Each of these patterns tries to address a number of problems:

  1. Where and how do we maintain state in the UI?
  2. Where does business logic live in the application and how is it invoked?
  3. How do we keep the UI synchronised with changes to the data and between UI elements?
  4. How can we ensure good separation of concerns and create loosely coupled testable code?

So the question is, how do they compare?

Note: There are variations on the theme here so there may be alternatives especially with MVP (e.g. Passive View, Supervising Controller, Front Controller).

mvc-mvp-mvvm

MVC MVP MVVM
Input is routed to the Controller.

The Controller decides which View to render and builds the Model which is bound to the View.

A Controller can choose to render one of many Views.

The View has no knowledge of its Controller.

Business logic exists in the Controller.

MVC is useful when state can’t be maintained between user input requests (e.g. over HTTP – a stateless protocol).
Input is routed to the View.

The Presenter updates the View usually in response to events raised by the View.

State is effectively stored in the View.

Business logic exists in the Presenter.
Input is routed to the View.

The View knows about nothing but the ViewModel.

The ViewModel knows about nothing but the Model.

The View gets its data from the ViewModel, not the Model itself. This is generally accomplished by data binding. 

State and business logic exist in the ViewModel.

The ViewModel can be thought of as an abstract representation of the UI.

MVVM is useful when state can be maintained between UI requests (e.g. Silverlight, WPF).

Monday, 12 July 2010

WCF Service Reference returns array and not List<T>

If you create a Service Reference to a WCF service that has operations that return generic collections you might be surprised to find the collection is exposed on the client as an array. This is the default behaviour for a WCF Service Reference but it is configurable.

To change the collection type for operations:

  1. In Visual Studio 2010 right-click on the appropriate service reference.
  2. Choose Configure Service Reference… from the pop-up menu.
  3. Choose an appropriate Collection Type on the dialog box (see image below).
  4. Click OK.

Image1

Monday, 12 July 2010

Sunday, 11 July 2010

Screen Conductor and other patterns

Silverlight and WPF development have lead to the uptake of a number of development patterns many of which were first introduced by Martin Fowler or which are variations of them. This post contains notes about the various patterns that are appearing in frameworks like Caliburn.Micro or Prism.

These patterns are put together to form a presentation framework.

Firstly, there is the Application Controller:

“A centralized point for handling screen navigation and the flow of an application.” http://martinfowler.com/eaaCatalog/applicationController.html (Martin Fowler)

The Application Controller is often comprised of a number of elements such as:

  • Screen(s)
  • Screen Factories
  • Screen Factory Registry
  • Screen Conductor
  • Screen Collection
  • Subject

Screen

  • The class that handles coordinates the Model, View and ViewModel.
  • Coordinates the marrying of a View to a ViewModel (the View doesn’t know about the ViewModel, the ViewModel doesn’t know about View).
  • Implements the IScreen interface.
IScreen
  • An interface that all Screens will implement.
  • Requires methods such as CanLeave() and CleanUp().

Screen Factory

  • There is a one-to-one relationship between Screen Factories and Screens.
  • Screen Factories implement the IScreenFactory interface
  • The Screen Factories are registered with the presentation framework (i.e. the Screen Factory Registry singleton class).
  • Screen Factories are used by the Screen Conductor to instantiate screens.
IScreenFactory
  • Requires a CreateScreen() method.

Screen Factory Registry

  • The Screen Factory Registry contains a registry of all of the screen factories.
  • Modules can register their Screen Factory classes with the Screen Factory Registry.
  • The Screen Factory Registry has methods including GetFactory(), HasFactory(), and a Screen Factory Dictionary

Screen Conductor

  • The Screen Conductor coordinates the creation and destruction of screens.
  • The Screen Conductor makes use of the Screen Factory Registry which it uses to create Screens as necessary.
  • Screen creation includes screen visibility, screen location, loading Subjects into screens, etc.
  • The Screen Conductor has a Screen Collection; a collection of all activated screen instances.
  • The Screen Conductor is often a singleton.

Screen Collection

  • The Screen Conductor has a Screen Collection which contains all of the activated screen instances.
  • The Screen Collection is maintained by the Screen Conductor.

Subject

  • The Subject is analogous to the Model; it’s what is required by the screen to fulfil its purpose.

 

After the Application Controller there is the Application Shell.

Application Shell

  • The Application Shell is analogous to the main form in the application.
  • The responsibility of the shell is to hold the main components of the user interface (e.g. menus, ribbons, panels, docking managers, etc.) for the screens that get activated later. 

 

There sometimes are other elements that are combined with the above as part of the Presentation Framework.

Bootstrapper

  • The Bootstrapper is responsible for instantiating elements like the Application Shell and the IoC container (should one be used).
  • The Bootstrapper can also be used to activate services used by the application (e.g. caching service).

Wednesday, 7 July 2010

What is the Windows Process Activation Service (WAS)?

Here are some brief notes on the Windows Process Activation Service.

“Windows Process Activation Service (WAS) is the new process activation mechanism for the Windows Server 2008 that is also available on Windows Vista. It retains the familiar IIS 6.0 process model (application pools and message-based process activation) and hosting features (such as rapid failure protection, health monitoring, and recycling), but it removes the dependency on HTTP from the activation architecture. IIS 7.0 uses WAS to accomplish message-based activation over HTTP. Additional WCF components also plug into WAS to provide message-based activation over the other protocols that WCF supports, such as TCP, MSMQ, and named pipes. This allows applications that use communication protocols to use the IIS features such as process recycling, rapid fail protection, and the common configuration system that were only available to HTTP-based applications.” * (my bold)

“The Windows Process Activation Service (WAS) manages the activation and lifetime of the worker processes that contain applications that host Windows Communication Foundation (WCF) services. The WAS process model generalizes the IIS 6.0 process model for the HTTP server by removing the dependency on HTTP. This allows WCF services to use both HTTP and non-HTTP protocols, such as Net.TCP, in a hosting environment that supports message-based activation and offers the ability to host a large number of applications on a given machine.” ** (my bold)

WAS allows applications to be hosted in a more robust and manageable way:

  • Applications start and stop dynamically in response to incoming work items that arrive using HTTP and non-HTTP network protocols.
  • Process recycling to maintain the health of running applications.
  • Centralized application configuration and management.
  • Applications can take advantage of the IIS process model without a full IIS installation.
  • A single WAS server instance can be home to many different applications.
  • Applications are organised into groups called sites.
    • For the purposes of addressing and management.
    • Applications are also grouped together into application pools.
      • An application pool can house many different applications from many different sites.
      • Each application pool corresponds to an instance of a worker process (w3wp.exe).
  • Within a site, applications are arranged in a hierarchical manner
    • Reflects the structure of the URIs

 

* http://msdn.microsoft.com/en-us/library/ms730158.aspx
** http://msdn.microsoft.com/en-us/library/ms734677.aspx

Wednesday, 7 July 2010

Adjacent in space; stacked in time

The Dirtiest Word in UX: Complexity” from UX Magazine elucidated 2 interesting UI concepts:
  • Adjacent in space
  • Stacked in time
adjacent
Adjacent in space is taking elements of an application and positioning them all on the same screen. Depending on the information and number of features an application has, it can make the screen appear more, or less, complex. An airplane cockpit is an extreme example of this approach. It makes all of the controls readily available to pilots and keeps critical readouts and important data ready at hand to help pilots make quick decisions. The adjacent in space UI approach gives more immediate power and control. It also reduces the need for navigation between screens to reach additional functionality, speeding up interactions.
Stacked in time is splitting the functionality up into several screens or layers, like a story being spread across pages in a book rather than crammed into a single long page. This approach can reduce the chance of the users making a mistake by guiding them down clear path. It also offers a gradual engagement, showing and hiding controls so only the necessary UI/information is displayed, reducing the perceptive complexity of the UI. It can allow more screen space for feedback and guidance for the user, and can allow for a more aesthetically pleasing and/or branded experience. The stacked in time approach tends to make an application less intimidating and doesn't overwhelm the user with choices.
The adjacent in space and stacked in time approaches each has its own trade-offs. In most cases placing too many elements on screen at the same time creates unnecessary complexity. Not all controls are needed at once, so they should only be presented when needed. However, a stacked in time approach also can become overwhelming to a user if not executed correctly. If the features aren't mapped in logical paths or are split across too many layers, users might not be able to quickly find what they need. This is especially apparent on smaller screens for devices.”
These 2 simple concepts are critical for UI development and appropriate use is key to good mobile development.

Saturday, 3 July 2010

X.509 error when running simple WCF services

I was running through some tutorials and hit a problem when adding new endpoints to a WCF service. The Visual Studio service runner showed the following error:
System.InvalidOperationException: Cannot load the X.509 certificate identity specified in the configuration.
   at System.ServiceModel.Description.ConfigLoader.LoadIdentity(IdentityElement element)
   at System.ServiceModel.Description.ConfigLoader.LoadServiceDescription(ServiceHostBase host, ServiceDescription description, ServiceElement serviceElement, Action`1 addBaseAddress)
   at System.ServiceModel.ServiceHostBase.LoadConfigurationSectionInternal(ConfigLoader configLoader, ServiceDescription description, ServiceElement serviceSection)
   at System.ServiceModel.ServiceHostBase.LoadConfigurationSectionInternal(ConfigLoader configLoader, ServiceDescription description, String configurationName)
   at System.ServiceModel.ServiceHostBase.ApplyConfiguration()
   at System.ServiceModel.ServiceHostBase.InitializeDescription(UriSchemeKeyedCollection baseAddresses)
   at System.ServiceModel.ServiceHost.InitializeDescription(Type serviceType, UriSchemeKeyedCollection baseAddresses)
   at System.ServiceModel.ServiceHost..ctor(Type serviceType, Uri[] baseAddresses)
   at Microsoft.Tools.SvcHost.ServiceHostHelper.CreateServiceHost(Type type, ServiceKind kind)
   at Microsoft.Tools.SvcHost.ServiceHostHelper.OpenService(ServiceInfo info)
The problem lay in the App.config <identity> block of some of the newly added endpoints. Originally they looked something like this:
<identity>
    <certificatereference x509findtype="FindBySubjectDistinguishedName" storelocation="LocalMachine" storename="My" />
</identity>
Adding a <dns> element fixed the issue:
<identity>
    <dns value="localhost" />
    <certificatereference x509findtype="FindBySubjectDistinguishedName" storelocation="LocalMachine" storename="My" />
</identity>
The <dns> element is described as:
“Specifies the DNS of an X.509 certificate used to authenticate a service. This element contains an attribute value that is a string, and contains the actual identity.”
See the MSDN documentation:
Saturday, 3 July 2010

Friday, 2 July 2010

What is AppFabric?

Here are some brief introductory notes on the AppFabric platform. According to the Microsoft AppFabric site:
“Windows Server AppFabric is a set of integrated technologies that make it easier to build, scale and manage Web and composite applications that run on IIS.”
AppFabric provides 2 core services which can be used independently or together:
  • AppFabric Caching Services, which can speed up access to frequently accessed information such as session data used by an ASP.NET application.
  • AppFabric Hosting Services, making it easier to run and manage services created with Windows Communication Foundation, especially those built using Windows Workflow Foundation.
AppFabric is provided as extensions to the Application Server role of Windows Server.

AppFabric caching services

The original codename for AppFabric Caching Services was Velocity. AppFabric Caching Services speeds up access to frequently accessed data.
The main components of AppFabric Caching Services are:
  • A cache client - accesses a cache cluster containing some number of cache server machines.
    • e.g. an ASP.Net page.
  • Cache server(s) - running instances of AppFabric Caching Services and maintaining cached data.
    • All the cache servers in the cluster appear as a single logical store.
    • The client neither knows nor cares which physical server winds up holding the cached data.
  • Cache client local cache – also using services provided by AppFabric Caching Services.
When a cache client acquires data it can use the AppFabric Caching Services client library to store the data in the cache cluster under a unique name. When the client needs the same data again, it asks for it using the item’s name:
  • The query first checks the local cache (if one is being used).
  • If the data is found the client uses the cached value.
  • If the data item isn’t in the local cache the query is sent to the cache cluster.
  • If the data is found the client uses the value returned from the cluster.
  • If the data isn’t found the client needs to look elsewhere for the information (e.g. the database).
A cached data item can be any serialized .NET object.
All cached data is stored in memory. By default, cached data is only stored on one node in the cluster but AppFabric Caching Services also has a high-availability option that creates a secondary copy of each cached data item on another node in the cluster.
Cached data items can be removed from the cache by client applications or by the caching service itself (e.g. through expiration based on a configurable time-out period or by being evicted to make room for more frequently accessed information). This applies to local caches as well as the server caches. Local caches can can be set to synchronize automatically with changes to data items in the cache cluster.
Data sent between cache clients and cache servers can be digitally signed and encrypted. Administrators can limit which accounts have access to each cache.
Note that AppFabric Caching Services have built-in support for storing ASP.Net session data.

AppFabric Hosting Services

The original codename for AppFabric Hosting Services was Dublin. WCF and WF services need service hosts and AppFabric Hosting Services provide some infrastructure for hosting in IIS.
AppFabric Hosting Services build on what’s already provided by IIS and Windows Process Activation Service (WAS), adding additional capabilities for running and managing WCF services, including workflow (WF).
WCF services and WF services run in worker processes provided by IIS - AppFabric Hosting Services doesn’t provide its own host process.
AppFabric Hosting Services extends the IIS Manager and provides facilities which include:
  • Setting WCF configurations
  • Starting and stopping services
  • Examining service endpoints
  • Suspending, resuming, or terminating specific instances of workflow services
  • An IIS manager dashboard for monitoring WCF and WF services
AppFabric Hosting Services also provide PowerShell ‘commandlets’ for service management.
Visual Studio WCF and WF projects created with the built-in project templates are immediately deployable in AppFabric Hosting Services.
The WF runtime automatically persists the state of a workflow that’s waiting for input, then rehydrates it when input arrives. Using WF by itself the developer must create and configure a persistence database. However, AppFabric Hosting Services provides a pre-configured persistence store.
WF allows a workflow’s execution to be tracked giving the developer a detailed record of its execution with the tracking data being stored in a monitoring database. Conventionally the WF developer must supply a monitoring database but AppFabric Hosting Services provides a built-in monitoring database for this purpose.
AppFabric Hosting Services allows a service to be deployed to a load-balances server environment so that workflow etc. is coordinated across multiple servers in the cluster. AppFabric Hosting Services lets the same instance of a workflow service execute on different machines at different times (i.e. it makes the service more scalable).