Friday, 31 December 2010

WCF service reference not creating correct proxy classes

Problem

I had a test project using NUnit to run unit tests for some components of a WCF service. In addition, I decided to include some integration tests that actually called a WCF service running in IIS on the localhost. To run the integration tests I created a service reference (which should generate the proxy classes) some types I had expected to find didn’t appear as proxies. The types that didn’t appear were declared as known types against the WCF service definition and all data contract attributes were correct. 

When I tried to use a type I had expected to find as a proxy class ReSharper was trying to help me out by referring me to the actual classes in the service projects, not from generated proxies. Even stranger, when I looked at the Reference.cs file (which should contain the proxy classes) the proxy classes were indeed missing but I could find declarations for the actual classes from the service projects.

Image1 
To find References.cs – in the Solution Explorer, View All Files and expand the service reference.

Solution

The fact that ReSharper was helping by pointing at the service projects was the clue. Because this was a test project I had included unit tests that created instances of classes from the service projects and as such had included references to those projects. When I added the service reference it looks like the actual service classes were used in preference to creating proxies.

I removed the references to the service projects, commented out code that needed those references and then re-added the service reference. The proxies were generated correctly.

The moral of the story is, don’t add references to the actual service projects as well as service references to the same code. It’s a good idea to run integration tests in a separate project so the references and service references don’t trip over each other.

Friday, 31 December 2010

Thursday, 30 December 2010

Shapefile basics

It looks like I’m going to have to get to grips with shapefiles and GIS data so here’s a post to give me a heads-up on shapefiles.

What is a shapefile?

A shapefile stores nontopological geometry and attribute information for the spatial features in a data set. The geometry for a feature is stored as a shape comprising a set of vector coordinates.

Because shapefiles do not have the processing overhead of a topological data structure, they have advantages over other data sources such as faster drawing speed and edit ability. Shapefiles handle single features that overlap or that are noncontiguous. They also typically require less disk space and are easier to read and write.

Shapefiles can support point, line, and area features. Area features are represented as closed loop, double-digitized polygons. Attributes are held in a dBASE® format file. Each attribute record has a one-to-one relationship with the associated shape record.” *

Note that a geographic element forming part of a shapefile is referred to as a feature.

“A representation of a geographic feature that has both a spatial representation referred to as a "shape" and a set of attributes.” ***

So, key points:

  • The data is nontopographical geometry it faster to search.
  • Shapefiles can support point, line, and area features.

A shapefile is capable of storing a mixture of different shape types but this is prevented by the specification: "All the non-Null shapes in a shapefile are required to be of the same shape type."

Parts of a shapefile

Firstly, a shapefile actually consists of several files, not one, and a shapefile can contain a combination of mandatory and optional files. A shapefile will contain 3 mandatory files:

  • .shp - the shape file containing the feature geometry
  • .shx - the shape index containing a positional index of the feature geometry (facilitates quick searching)
  • .dbf - the attribute file containing attributes for each shape (dBase IV format)

An ESRI shapefile consists of a main file, an index file, and a dBASE table. The main file is a direct access, variable-record-length file in which each record describes a shape with a list of its vertices. In the index file, each record contains the offset of the corresponding main file record from the beginning of the main file. The dBASE table contains feature attributes with one record per feature. The one-to-one relationship between geometry and attributes is based on record number. Attribute records in the dBASE file must be in the same order as records in the main file.” **

There are a number of optional files but I am currently interested in:

  • .prj – the projection file containing the coordinate system and projection information in plain text
  • .sbn and .sbx – both containing the spatial index of the features
  • .shp.xml - metadata in XML format

 

References

* http://www.esri.com/library/whitepapers/pdfs/shapefile.pdf, p.5
** http://www.esri.com/library/whitepapers/pdfs/shapefile.pdf, p.6
*** http://www.esri.com/library/whitepapers/pdfs/shapefile.pdf, p.31

Thursday, 30 December 2010

Viewing contents of the Global Assembly Cache (GAC)

Here’s a quick tip, if you view the GAC using Windows Explorer you get a nice sanitised view; the underlying folders are aggregated and the contents displayed. This can be useful for quickly finding and removing things from the GAC. However, it doesn’t show you where things really are.
The Windows Explorer view is provided by a shell extension and it is possible to disable it but you’ll lose drag and drop installation into the GAC.
To see where things are really living open a DOS prompt and navigating to the GAC directory:
untitled
The directory listing will reveal the following set of folders:
  • GAC – .NET 1.x assemblies
  • GAC_32 – .NET 2.x assemblies built for 32-bit
  • GAC_64 – .NET 2.x assemblies built for 64-bit (only of 64-bit machines)
  • GAC_MSIL – .NET 2.x assemblies that are architecture independent (32 or 64-bit)
  • NativeImages_Vx_Architecture – Each of these folders is used for storing native images of .NET assemblies that have been pre-compiled using NGen (i.e. no need for JIT). There can be a number of these folders for different .Net versions and compilation targets (e.g. 32 or 64-bit)
  • temp, tmp – Temporary folders
You can then navigate to individual folders and list the contents.

Tuesday, 30 November 2010

Useful tools

I always seem to be setting up development machines and need to install the same set of tools over and over. To help me keep track of them I’m starting a list:

Tool name Description Location
ILSpy ILSpy is the open-source .NET assembly browser and decompiler. A replacement for Reflector which is now a commercial product. http://wiki.sharpdevelop.net/ilspy.ashx
Regulator An advanced, free regular expressions testing and learning tool. http://www.osherove.com/tools
XMLPad XML Notepad 2007 provides a simple intuitive user interface for browsing and editing XML documents. http://www.microsoft.com/downloads/en/details.aspx?familyid=72d6aa49-787d-4118-ba5f-4f30fe913628&displaylang=en
Notepad++ Notepad++ is a free source code editor and Notepad replacement that supports several languages. Running in the MS Windows environment, its use is governed by GPL License. http://notepad-plus-plus.org/
Baretail A real-time log file monitoring tool. http://www.baremetalsoft.com/baretail/
Gallio The Gallio Automation Platform is an open, extensible, and neutral system for .NET that provides a common object model, runtime services and tools (such as test runners) that may be leveraged by any number of test frameworks. http://www.gallio.org/
Sandcastle

Documentation compiler for managed class libraries.

http://sandcastle.codeplex.com/releases/view/47665
NDepend NDepend is a Visual Studio tool to manage complex .NET code and achieve high Code Quality. http://www.ndepend.com/
PartCover Open source code coverage tool. https://github.com/sawilde/partcover.net4
WinMerge WinMerge is an Open Source differencing and merging tool for Windows. http://winmerge.org/

Query Express

Query Express is a simple Query Analyzer look-alike, but being small and free it can be run where the SQL Server client tools are not installed or licensed. http://www.albahari.com/queryexpress.aspx
AnjLab SQL Profiler A free SQL Server Express Edition Profiler that provides the most of functionality standard profiler does. http://anjlab.com/en/projects/opensource/sqlprofiler
TreeTrim This is a command line tool that trims your source code tree. It removes debug files, source control bindings, and temporary files. http://code.google.com/p/treetrim/
LogParser Log parser is a powerful, versatile tool that provides universal query access to text-based data such as log files, XML files and CSV files, as well as key data sources on the Windows® operating system such as the Event Log, the Registry, the file system, and Active Directory®. http://www.microsoft.com/downloads/en/details.aspx?FamilyID=890cd06b-abf8-4c25-91b2-f8d975cf8c07&displaylang=en
Lizard GUI A GUI for parsing log files (use with LogParser). http://www.lizard-labs.net/log_parser_lizard.aspx
cURL cURL is a computer software project providing a library and command-line tool for transferring data using various protocols. http://curl.haxx.se/
Wget GNU Wget is a free software package for retrieving files using HTTP, HTTPS and FTP, the most widely-used Internet protocols. It is a non-interactive commandline tool, so it may easily be called from scripts, cron jobs, terminals without X-Windows support, etc. http://www.gnu.org/software/wget/
Console2 Console is a Windows console window enhancement. Console features include: multiple tabs, text editor-like text selection, different background types, alpha and color-key transparency, configurable font, different window styles. http://sourceforge.net/projects/console/
WireShark A network protocol analyser. http://www.wireshark.org/
Fiddler Fiddler is a Web Debugging Proxy which logs all HTTP(S) traffic between your computer and the Internet. http://fiddler2.com/fiddler2/
Tuesday, 30 November 2010

Thursday, 18 November 2010

WCF service throwing immediate timeout

The problem

I was recently writing automated integration tests against a WCF service using NUnit when out of the blue all the tests failed and kept failing. An examination of the exceptions thrown showed that in each case a CommunicationException was being thrown because of a timeout.

What was most perplexing was that the apparent timeouts were being reported immediately but the client configuration was set to defaults:

<system.serviceModel>
        <bindings>
            <wsHttpBinding>
                <binding name="WSHttpBinding_EnquirySubmissionService" closeTimeout="00:01:00"
                    openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                    bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard"
                    maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
                    messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true"
                    allowCookies="false">
                    <!-- snip -->
                </binding>
            </wsHttpBinding>
        </bindings>
        <!-- snip -->
  </system.serviceModel>
</configuration>

The service was using WsHttpBinding and was hosted by IIS over HTTPS. The service was also secured using TransportWithMessageCredential and UserName credentials on the message (i.e. username and password).

 

The solution

Firstly I enabled tracing on the service by modifying the Web.config file to include the following:

<system.diagnostics> 
    <sources> 
        <source name="System.ServiceModel" switchValue="Information,ActivityTracing" propagateActivity="true"> 
            <listeners> 
                <add name="xml" /> 
            </listeners> 
        </source> 
        <source name="System.ServiceModel.MessageLogging"> 
            <listeners> 
                <add name="xml" /> 
            </listeners> 
        </source> 
    </sources> 
    <sharedListeners> 
        <add initializeData="C:\logs\TracingAndLogging-client.svclog" type="System.Diagnostics.XmlWriterTraceListener" name="xml" /> 
    </sharedListeners> 
    <trace autoflush="true" />
</system.diagnostics>

I then queried the service again to promote a timeout communication exception. I found the trace log contained:

System.ServiceModel.Security.MessageSecurityException: Message security verification failed. ---&amp;gt; System.ComponentModel.Win32Exception: The event log file is full
at System.Diagnostics.EventLog.InternalWriteEvent(UInt32 eventID, UInt16 category, EventLogEntryType type, String[] strings, Byte[] rawData, String currentMachineName) 
at System.Diagnostics.EventLog.WriteEvent(EventInstance instance, Byte[] data, Object[] values) 
at System.Diagnostics.EventLog.WriteEvent(String source, EventInstance instance, Object[] values) 
at System.ServiceModel.Security.SecurityAuditHelper.WriteEventToApplicationLog(EventInstance instance, Object[] parameters) 
at System.ServiceModel.Security.SecurityAuditHelper.WriteMessageAuthenticationSuccessEvent(AuditLogLocation auditLogLocation, Boolean suppressAuditFailure, Message message, Uri serviceUri, String action, String clientIdentity) 
at System.ServiceModel.Security.SecurityProtocol.OnIncomingMessageVerified(Message verifiedMessage) 
at System.ServiceModel.Security.TransportSecurityProtocol.VerifyIncomingMessageCore(Message&amp;amp; message, TimeSpan timeout) 
at System.ServiceModel.Security.TransportSecurityProtocol.VerifyIncomingMessage(Message&amp;amp; message, TimeSpan timeout)

So, the problem actually was that the event log was full! Having emptied the event log everything started working again.

Thursday, 18 November 2010

Monday, 8 November 2010

Compiled help files (.chm) not working

Here’s a quicky that’s bugged me a few times and I can never remember the solution.

Sometimes when you download a .chm file, open it and try to navigate around you get an “address is not valid” error such as the following:

clip_image001

The solution is quick and simple:

  1. Right-click the .chm file and then click Properties.
  2. Click the Unblock button.
  3. The .chm file may now be opened and will work normally.

Sunday, 7 November 2010

When to install assemblies into the GAC

I have recently been working on an established project which makes use of the Global Assembly Cache (GAC) for most of the assemblies in the application. I have found the experience quite frustrating because keeping the assemblies in sync with the code has been tedious. But I realised I wasn’t really sure if using the GAC was a good idea or not so I’ve done a bit of research.

“Each computer where the common language runtime is installed has a machine-wide code cache called the global assembly cache. The global assembly cache stores assemblies specifically designated to be shared by several applications on the computer.

You should share assemblies by installing them into the global assembly cache only when you need to. As a general guideline, keep assembly dependencies private, and locate assemblies in the application directory unless sharing an assembly is explicitly required. In addition, it is not necessary to install assemblies into the global assembly cache to make them accessible to COM interop or unmanaged code.” *

OK, so there’s the first point. Microsoft suggest, “You should share assemblies by installing them into the global assembly cache only when you need to”.

The GAC is useful for deploying assemblies to be shared by a set of applications but I like the possibility of XCOPY deployments. However, deploying an assembly to the GAC is reported to improve its load performance compared to assemblies not located in the GAC. In addition strongly named assemblies are reported to load faster from the GAC because they are verified at the time they are installed rather than at runtime. In effect the .NET framework skips runtime verification for assemblies loaded from the GAC.

Back to Microsoft:

“There are several reasons why you might want to install an assembly into the global assembly cache:

  • Shared location.

Assemblies that should be used by applications can be put in the global assembly cache. For example, if all applications should use an assembly located in the global assembly cache, a version policy statement can be added to the Machine.config file that redirects references to the assembly.

  • File security.

Administrators often protect the systemroot directory using an Access Control List (ACL) to control write and execute access. Because the global assembly cache is installed in the systemroot directory, it inherits that directory's ACL. It is recommended that only users with Administrator privileges be allowed to delete files from the global assembly cache.

  • Side-by-side versioning.

Multiple copies of assemblies with the same name but different version information can be maintained in the global assembly cache.

  • Additional search location.

The common language runtime checks the global assembly cache for an assembly that matches the assembly request before probing or using the codebase information in a configuration file.” **

I find reasons such as side-by-side versioning quite compelling. I for one have worked on projects where various open source tools refer to different versions of other libraries. Getting all of the assemblies to live together in a single application directory can be a challenge. However, it must be noted that earlier in the article quoted above states:

“You should share assemblies by installing them into the global assembly cache only when necessary. As a general guideline, keep assembly dependencies private and locate assemblies in the application directory unless sharing an assembly is explicitly required.” **

* Global Assembly Cache
** Working with Assemblies and the Global Assembly Cache

Sunday, 7 November 2010

Problem using Fiddler with localhost

I recently had a problem getting Fiddler to show the traffic to and from an application running on localhost when viewing the application with Internet Explorer. I completely forgot the workaround so thought a post on the subject would help.

There are some known issues with Fiddler and this is one of them. In short, both Internet Explorer and the .Net framework are setup not to send requests for localhost through a proxy. Of course Fiddler is a proxy and therefore will not receive the traffic.

One workaround is to use your machine name instead of localhost. So, http://localhost:8081/mytestpage.aspx becomes http://mymachinename:8081/mytestpage.aspx.

Another is to insert a dot (.) immediately after localhost. So, http://localhost:8081/mytestpage.aspx becomes http://localhost.:8081/mytestpage.aspx.

See also

The Fiddler website - http://www.fiddler2.com/fiddler2/

Saturday, 9 October 2010

Viewing SOAP message contents

I struggle to visualise the contents of a SOAP message by looking at WSDL. This is compounded by the somewhat indirect way changing settings in WCF service configuration (either in configuration files or code attributes) affects the WSDL and ultimately the SOAP message. It is much easier to actually have a peek at the contents of the SOAP message.
The solution to my problem was provided by Kory Becker in his article Displaying SOAP XML Messages in a Simple WCF Web Service.
For convenience I’ve created a little Visual Studio project (C#) with the code already implemented here. Note that to see the output in Visual Studio for services hosted in IIS the trick is to debug the service by attaching the debugger to the ASP.Net worker process.
Saturday, 9 October 2010

Convert a service to view metadata over HTTPS

I wanted to host a WCF service in IIS over HTTPS (i.e. using SSL). I already had a service host setup in IIS with a mex endpoint configured for HTTP. So, I configured the host site to use SSL but when I browsed to the service in a web browser I got the following error:

https-error
“Could not find a base address that matches scheme http for the endpoint binding MetadataExchangeHttpBinding…”

To change the service to use HTTPS I hade to make a couple of changes.

  1. Set the metadata exchange endpoint to use the mexHttpsBinding (not the mexHttpBinding).
  2. Modify the service behaviour to enable getting metadata over HTTPS (httpsGetEnabled).
  3. Changed the service base address to use HTTPS.
<system.serviceModel>
  <services>
    <service behaviorConfiguration="ServiceBehavior" name="Service.Service">
      ...
      <endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange" />
        <host> 
          <baseAddresses>
<add baseAddress="https://www.domaingoeshere.com/" />
</baseAddresses>
</host>
</service> </services> <bindings> ... </bindings> <behaviors> <serviceBehaviors> <behavior name="ServiceBehavior"> <serviceMetadata httpsGetEnabled="true" /> <serviceDebug includeExceptionDetailInFaults="false" /> ... </behavior> </serviceBehaviors> </behaviors> </system.serviceModel>

NB: Don't forget that existing clients will have to update their service references.

Saturday, 2 October 2010

Keyset does not exist

I was trying to run a WCF service with additional security and generated the following “Keyset does not exist” error:

Image4 

Reading the stack trace I got the following additional information:

[ArgumentException: It is likely that certificate 'CN=RPKey' may not have a
private key that is capable of key exchange or the process may not have access
rights for the private key. Please see inner exception for detail.]

This turned out be file security settings on the key file. To fix the problem you may need to grant file permissions to the appropriate key file (in this case the RPKey file). To find the location of the key file I ran the FindPrivateKey utility which shipped with the WF and WCF Samples obtained from MSDN. Build the FindPrivateKey sample an run it in a command window:

C:\...path here...\FindPrivateKey\CS\bin>findprivatekey My LocalMachine -n "CN=RPKey" –a 

This gave the location of the key file and I was able to grant permissions to the ASPNET user. You may need to grant permissions to the network service user.

Normal service restored.

Missing security tab on folder properties (Windows XP)

I was on a Windows XP machine and needed to access file security settings for a certificate file but the Security tab was missing.

Image1

To make the tab available I did the following:

  1. Launch Windows Explorer or My Computer.
  2. Click on the Tools > Folder Options.
  3. Click on View tab.
  4. In Advanced Settings uncheck the “Use simple file sharing (Recommended)” check box.
  5. Click OK.

Image2

Note: If that doesn’t work try clicking on “Apply to ALL Folders”. The result should be a restored Security tab.

Image3

Wednesday, 29 September 2010

Instancing and concurrency in WCF

It doesn’t take long for my head to explode when thinking about threading and there is no exception when it comes to WCF. Here are a few notes on some of the main points.

How a WCF service reacts when it comes to threading and concurrency issues is basically governed by 2 concepts associated with the ServiceBehaviourAttribute: how the service is instantiated (e.g. as a singleton) through the use of the InstanceContextMode enumeration, and whether the service supports single-threaded or multi-threaded access through the use of the ConcurrencyMode enumeration.

[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single,
    ConcurrencyMode=ConcurrencyMode.Multiple, 
    UseSynchronizationContext=false)]
public class MessagingService : IMessagingService
{
 // other code here...
}

Instancing with the InstanceContextMode enumeration

InstanceContextMode  specifies the number of service instances available for handling calls that are contained in incoming messages.It therefore controls how service instances are allocated in response to client calls. InstanceContextMode can be set to the following values:

  • Single – One service instance is allocated for all client calls.
  • PerCall – One service instance is allocated for each client call.
  • PerSession – One service instance is allocated for each client session.

The default setting for InstanceContextMode is PerSession.

Note that when InstanceContextMode is set to PerCall, the ConcurrencyMode setting is ignored because each client call is routed to a new service instance. Only one thread is running in a service instance at one time.

Also note that when InstanceContextMode is set to PerCall, a new service instance is created for each client call and the instance is destroyed when the client call completes. In this case there are no synchronisation issues because each client call gets its own service instance.

If InstanceContextMode is set to Single the service can only process one message at a time unless you set the ConcurrencyMode to Multiple.

Concurrency with the ConcurrencyMode enumeration

ConcurrencyMode controls how multiple threads are allowed into the service at one time. ConcurrencyMode can be set to one of the following values:

  • Single – One thread can enter the service at one time.
  • Reentrant – One thread can enter the service at one time but callbacks are allowed.
  • Multiple – Multiple threads can enter the service at one time.

The default setting for ConcurrencyMode is Single. Setting ConcurrencyMode to single allows you to share service instances across multiple clients.

MSDN documentation states that the default value was chosen so that developers do not have to think about synchronisation by default.

Note that when the ConcurrencyMode is set to Multiple, multiple client calls can get through but it is the developer who is responsible for synchronising access to shared data.

The following table shows when an operation can be invoked while another one is in progress:

ConcurrencyMode Value Can a new operation be invoked?
Single Never
Reentrant Only while invoking another service or a callback
Multiple Always

 

Using the SynchronizationContext

In the C# example at the top of the page there is another property of the service behaviour attribute that is being used: UseSynchronizationContext. This property is of particular use if the service is being invoked from Windows clients (Win forms or WPF) and especially if callbacks are being used.

This is quite a complex topic which is covered in detail here.

See also

MSDN documentation:

Wednesday, 29 September 2010

Tuesday, 28 September 2010

Processes and application domains

I thought it was time to review process and application domains in .Net…

Processes

In general terms a processes is an operating system construct used to run programs. A process can own resources like memory and kernel objects and often a single process can have multiple threads running inside it which in turn execute the code. Where multiple threads are used code can execute concurrently. It is the operating system that takes the responsibility to protect processes from interfering with each other.

Application domains

The .Net framework and the CLR introduced a new concept above standard operating system processes: the application domain. An application domain forms an isolation boundary for security, versioning, reliability, and unloading of managed code. Each application domain has its own virtual address space which scopes the resources for the application domain. In effect an application domain is the CLR equivalent of an operation system process and is used to isolate one application from another.
A CLR application domain is itself contained within an operating system process and a process may contain many application domains. In effect the CLR functions like an operating system within an operating system; it runs in a single process but contains multiple sub-processes (application domains).
MSDN documentation states:
“Operating systems and runtime environments typically provide some form of isolation between applications. For example, Windows uses processes to isolate applications. This isolation is necessary to ensure that code running in one application cannot adversely affect other, unrelated applications.
Application domains provide an isolation boundary for security, reliability, and versioning, and for unloading assemblies. Application domains are typically created by runtime hosts, which are responsible for bootstrapping the common language runtime before an application is run.” *
Some features of application domains are:
  • Multiple threads can run in a single application domain
  • Security access levels can be applied to application domains individually
  • Faults or exceptions in one domain do not affect another domain or the entire process that hosts the domains
  • Configuration is scoped to the application domain and not the scope of the host process
  • Code running in one domain cannot directly access code running in another
  • Stopping an application in one application domain does not affect the state of another domain in the same process
The advantage of Application Domains is that running multiple Application Domains requires fewer resources, such as memory, than running multiple operating system processes. Again, MSDN documentation states:
“Application domains provide a more secure and versatile unit of processing that the common language runtime can use to provide isolation between applications. You can run several application domains in a single process with the same level of isolation that would exist in separate processes, but without incurring the additional overhead of making cross-process calls or switching between processes. The ability to run multiple applications within a single process dramatically increases server scalability.” *

A quick note on worker processes and application pools

An Internet Information Services (IIS) worker process is a windows process (w3wp.exe) which runs web applications, and is responsible for handling requests sent to a web server for a specific application pool (see below). Each worker process hosts its own CLR.
An Internet Information Services (IIS) application pool is a grouping of URLs that are routed to one or more worker processes. Application pools provide a way to administer a set of web sites and applications and their corresponding worker processes. Worker processes are separated by process boundaries so a web site or application in one application pool will not be affected by problems in other application pools. Application pools increase the reliability and manageability of a web infrastructure.

See also

* MSDN documentation, Application Domains. TechNet documentation, IIS Application Pool.

Sunday, 26 September 2010

WCF bindings

Here is a quick aide-mémoire about WCF bindings. This table is basically taken from the MSDN documentation for WCF bindings in .Net 3.5 with a few extra notes here and there.

Binding Configuration Element Description

BasicHttpBinding

<basicHttpBinding>

A binding that is suitable for communicating with WS-Basic Profile conformant Web services, for example, ASP.NET Web services (ASMX)-based services. This binding uses HTTP as the transport and text/XML as the default message encoding.

WSHttpBinding

<wsHttpBinding>

A secure and interoperable binding that is suitable for non-duplex service contracts.

Supports the latest interoperable web service standards (WS*) and is compatible with more recent web service stacks. *

WSDualHttpBinding

<wsDualHttpBinding>

A secure and interoperable binding that is suitable for duplex service contracts or communication through SOAP intermediaries.

WSFederationHttpBinding

<wsFederationHttpBinding>

A secure and interoperable binding that supports the WS-Federation protocol that enables organizations that are in a federation to efficiently authenticate and authorize users.

A web service binding that supports WS* as it relates to federated and single sign-on security scenarios. *

NetTcpBinding

<netTcpBinding>

A secure and optimized binding suitable for cross-machine communication between WCF applications.

A connection-oriented binding for communications across process and machine boundaries over TCP. *

NetNamedPipeBinding

<netNamedPipeBinding>

A secure, reliable, optimized binding that is suitable for on-machine communication between WCF applications.

A connection-oriented binding for communications on the same machine over named-pipes. *

NetMsmqBinding

<netMsmqBinding>

A queued binding that is suitable for cross-machine communication between WCF applications.

Supports durable reliable messaging over MSMQ. *

NetPeerTcpBinding

<netPeerTcpBinding>

A binding that enables secure, multiple machine communication.

Supports peer-to-peer and broadcast communications. *

MsmqIntegrationBinding

<msmqIntegrationBinding>

A binding that is suitable for cross-machine communication between a WCF application and existing Message Queuing applications.

Supports integration with legacy MSMQ components. *

BasicHttpContextBinding

<basicHttpContextBinding>

A binding that is suitable for communicating with WS-Basic Profile conformant Web services that enables HTTP cookies to be used to exchange context.

NetTcpContextBinding

<netTcpContextBinding>

A secure and optimized binding suitable for cross-machine communication between WCF applications that enables SOAP headers to be used to exchange context.

WebHttpBinding

<webHttpBinding>

A binding used to configure endpoints for WCF Web services that are exposed through HTTP requests instead of SOAP messages.

WSHttpContextBinding

<wsHttpContextBinding>

A secure and interoperable binding that is suitable for non-duplex service contracts that enables SOAP headers to be used to exchange context.

* pp160-161, Learning WCF, Michelle Leroux Bustamonte

Sunday, 26 September 2010

Saturday, 25 September 2010

So what’s this IExtensibleDataObject interface all about then?

When defining WCF data contracts (i.e. classes marked with a DataContractAttribute) problems can occur with regards to versioning; adding new members to a data contract for example. Data could be passed to a version of a service that was not expecting it. This data could then be lost at the service.

By implementing the IExtensibleDataObject interface a data contract class can preserve unknown members included in the serialised type. The DataContractSerializer will populate the ExtensionDataObject dictionary required by the interface during the deserialisation process. The dictionary is then used to provide the additional member values upon serialisation.

This is useful:

  • When clients send additional unknown data to a service that should be returned intact
  • When a later version client sends data to an earlier version service and you want to preserve the unknown data for version tolerance

Ignoring IExtensibleDataObject at the service level

Even if data contract classes implement IExtensibleDataObject you can tell a service to ignore it by applying a service behaviour.

<behaviour name="serviceBehavior">
    <dataContractSerializer ignoreExtensionDataObject="true" />
</behaviour>

Additional information

The MSDN documentation states:

*The IExtensibleDataObject interface provides a single property that sets or returns a structure used to store data that is external to a data contract. The extra data is stored in an instance of the ExtensionDataObject class and accessed through the ExtensionData property. In a roundtrip operation where data is received, processed, and sent back, the extra data is sent back to the original sender intact. This is useful to store data received from future versions of the contract. If you do not implement the interface, any extra data is ignored and discarded during a roundtrip operation.” *

* IExtensibleDataObject Interface

Saturday, 25 September 2010

Thursday, 23 September 2010

What are WCF behaviours?

WCF concepts such as endpoints, bindings, operations etc. have all seemed straight forward to me but for some reason behaviours have not. For example why, if I expose a metadata endpoint do I also have to explicitly implement a metadata behaviour? This post is an aide memoire about behaviours.

What are behaviours?

“Behaviors are types that modify or extend Service or Client functionality. For example, the metadata behavior that ServiceMetadataBehavior implemented controls whether the Service publishes metadata. Similarly, the security behavior controls impersonation and authorization, while the transactions behavior controls enlisting in and auto-completing transactions.

Behaviors also participate in the process of building the channel and can modify that channel based on user-specified settings and/or other aspects of the Service or Channel.

A Service Behavior is a type that implements IServiceBehavior and applies to Services. Similarly, a Channel Behavior is a type that implements IChannelBehavior and applies to Client Channels.” *

Michele Leroux Bustamonte, in her book Learning WCF describes behaviours in the following terms:

“While endpoints describe where to reach the service, which operations are available at the specified address, and what protocols are required – behaviors affect the service model locally at the client or service. What this means is that behaviours are not exposed as part of metadata, and they are not shared between clients and services. Instead, the locally affect how the service model processes messages.” **

There are 4 types of behaviour: service, endpoint, operation and contract. Endpoint behaviours can be associated with service endpoints or client endpoints.

A WCF behaviour can be added to the runtime using one of the following methods:

  • Programmatically
  • Using attributes
  • Through configuration

Service behaviours:

  • Implement System.ServiceModel.Description.IServiceBehavior
  • Applies to the service itself or to specific endpoints, contracts, and operations
  • Can be added by attribute, configuration or programmatically

Endpoint behaviours:

  • Implement System.ServiceModel.Description.IEndpointBehavior
  • Affects the operation of a particular endpoint
  • Can be added by configuration or programmatically

Contract and operation behaviours are used to apply extensions to contracts and operations. Contract behaviours:

  • Implement System.ServiceModel.Description.IContractBehavior
  • Applies to a particular contract
  • Can be added by attribute or programmatically

Operation behaviours:

  • Implement System.ServiceModel.Description.IOperationBehavior
  • Affects a particular operation
  • Can be added by attribute or programmatically

Endpoint, contract, and operation behaviours can be applied to both services and clients, but service behaviours can only be applied to services.

See also Extending WCF with Custom Behaviors.

* Windows Communication Foundation Architecture Overview
** Learning WCF

Thursday, 23 September 2010

Missing “Edit WCF Configuration” menu option

Sometimes when you have created a new WCF service the “Edit WCF Configuration” context menu option is not available when you right-click on the config file (e.g. app.config). I have reproduced the problem below by creating a new class library and adding a WCF service to it. Right-clicking on the app.config file does not show the “Edit WCF Configuration” option.

Image1

To restore the missing option go to Tools > WCF Service Configuration Editor. This opens the editor but does not open the appropriate configuration file.

Image2

Close the editor immediately. Right-clicking on the configuration file will now show the previously missing “Edit WCF Configuration” option.

Image3

Friday, 10 September 2010

Type checking in VB.Net

OK, here’s another little reminder about VB.Net syntax.

Take the following C# fragment:

if (instance is TestDomainObject)
{
    var testInstance = instance as TestDomainObject;
    _data.Remove(testInstance.Id);
}

In VB.Net the equivalent is:

If (TypeOf instance Is TestDomainObject) Then
    Dim testInstance = TryCast(instance, TestDomainObject)
    _data.Remove(testInstance.Id)
End If

Note the use of the TypeOf keyword.

Note also that casting in VB.Net takes a bit of getting used to. There are essentially 3 ways to perform casting:

Keyword Data types Argument relationship Run-time failure

CType Function

Any data types

Widening or narrowing conversion must be defined between the two data types

Throws InvalidCastException

DirectCast

Any data types

One type must inherit from or implement the other type

Throws InvalidCastException

TryCast

Reference types only

One type must inherit from or implement the other type

Returns Nothing (Visual Basic)

See DirectCast Operator (Visual Basic) to get started. You might also like to checkout Convert.ChangeType Method.

Friday, 10 September 2010

Thursday, 9 September 2010

Constructor initialisors in VB.Net

Something very simple had me scratching my head again when I tried to remember how to do it in VB.Net, namely constructor initialisors.

So, take the following C# fragment with instantiates a member variable and populates it with some test data:

_data = new List<Core.Domain.Configuration>();
_data.Add(new Core.Domain.Configuration() { Key = "key1", Value = "value1" });
_data.Add(new Core.Domain.Configuration() { Key = "key2", Value = "value2" });
_data.Add(new Core.Domain.Configuration() { Key = "key3", Value = "value3" });

In VB.Net the equivalent is:

_data = New List(Of Core.Domain.Configuration)()
_data.Add(New Core.Domain.Configuration() With {.Key = "key1", .Value = "value1"})
_data.Add(New Core.Domain.Configuration() With {.Key = "key2", .Value = "value2"})
_data.Add(New Core.Domain.Configuration() With {.Key = "key3", .Value = "value3"})

Note the use of the With keyword and prefixing the property names with a dot.

Saturday, 4 September 2010

Web readability tools

I found these 2 web readability tools recommended by Scott Hanselman really useful:

  • Instapaper – A simple tool to save web pages for reading later.
  • Readability - A simple tool that makes reading on the Web more enjoyable by removing the clutter around what you're reading.

Friday, 3 September 2010

When to use delegates

I was recently asked to describe delegates and when they should be used. As is often the case with simple questions like this trying to explain what I know got me in a bit of a knot, so…

Read A reminder about delegates first!

MSDN has an interesting little article about When to Use Delegates Instead of Interfaces. This draws a parallel between interfaces and delegates that I hadn’t considered before. The article states:

“Both delegates and interfaces enable a class designer to separate type declarations and implementation. A given interface can be inherited and implemented by any class or struct. A delegate can be created for a method on any class, as long as the method fits the method signature for the delegate. An interface reference or a delegate can be used by an object that has no knowledge of the class that implements the interface or delegate method.”

It goes on to suggest that a delegate should be used when:

  • An eventing design pattern is used.
  • It is desirable to encapsulate a static method.
  • The caller has no need to access other properties, methods, or interfaces on the object implementing the method.
  • Easy composition is desired.
  • A class may need more than one implementation of the method.

It also occurred to me that delegates could be used to implement the coroutine pattern by exposing an IEnumerable of Action types.

The MSDN article goes on to suggest that Interfaces should be used when:

  • There is a group of related methods that may be called.
  • A class only needs one implementation of the method.
  • The class using the interface will want to cast that interface to other interface or class types.
  • The method being implemented is linked to the type or identity of the class: for example, comparison methods.
Friday, 3 September 2010

Wednesday, 25 August 2010

Multiple inheritance with interfaces in VB.Net

I couldn’t recall the correct Visual Basic .Net syntax for creating an interface which itself extends other interfaces. So, as a reminder, here it is.

Lets say we have 2 simple interfaces: INameable and IIdentifiable. These interfaces simply require that implementing classes have an Id property and a Name property respectively. Lets also say that we want to define an IReferenceData interface that simply says implementing classes must implement INameable and IIdentifiable.

For comparison lets start with C#:

namespace Domain
{
    /// <summary>
    /// Classes implementing this interface will have a name property.
    /// </summary>
    public interface INameable
    {
        /// <summary>
        /// Gets or sets the name of the entity.
        /// </summary>
        string Name { get; set; }
    }

    /// <summary>
    /// Classes implementing this interface will have an Id property.
    /// </summary>
    public interface IIdentifiable
    {
        /// <summary>
        /// Gets or sets the unique ID of the entity.
        /// </summary>
        int Id { get; set; }
    }

    /// <summary>
    /// An interface to be implemented by reference data types (simple types with 
    /// Name and ID properties).
    /// </summary>
    public interface IReferenceData : IIdentifiable, INameable
    {
    }
}

Now, the same thing in VB.Net:

Namespace Domain
    ''' <summary>
    ''' Classes implementing this interface will have a name property.
    ''' </summary>
    Public Interface INameable
        Property Name As String
    End Interface

    ''' <summary>
    ''' Classes implementing this interface will have an Id property.
    ''' </summary>
    Public Interface IIdentifiable
        ''' <summary>
        ''' Gets or sets the unique ID of the entity.
        ''' </summary>
        Property Id As Integer
    End Interface

    ''' <summary>
    ''' An interface to be implemented by reference data types (simple types with 
    ''' Name and ID properties).
    ''' </summary>
    Public Interface IReferenceData
        Inherits IIdentifiable
        Inherits INameable
    End Interface
End Namespace

Note the separate Inherits statements on separate lines.

Sunday, 22 August 2010

VB.Net equivalent of C# typeof()

Here’s a quick gotcha that got me again today. In C# to get a type we might use code such as the following:

var type = typeof(SomeType);

The equivalent in Visual Basic .Net is:

Dim type = GetType(SomeType)

Equivalent of static classes is VB.Net

The closest thing in Visual Basic .Net to a C# static class is a Module (also known as a standard module). In C# a static class is described as follows:

“A class can be declared static, indicating that it contains only static members. It is not possible to create instances of a static class using the new keyword. Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.” *

There is no direct equivalent in Visual Basic .Net but a Module has some properties similar to those of a static class:

  • Every module has exactly one instance and does not need to be created or assigned to a variable.
  • Modules do not support inheritance or implement interfaces.
  • A module is not a type - you cannot declare a programming element to have the data type of a module.
  • You can use Module only at namespace level.
  • The declaration context for a module must be a source file or namespace (not a class, structure, module, interface, procedure, or block).
  • You cannot nest a module within another module, or within any type.
  • A module has the same lifetime as your program.
  • All a module’s members are implicitly Shared. **

Example in C#:

static class SomeName
{
    public static string SomeMethod1() { return "Value 1"; }
    public static string SomeMethod2() { return "Value 2"; }
    //...
}

Equivalent in Visual Basic .Net:

Public Module SomeName
    Public Function SomeMethod1() As String
        Return "Value 1"
    End Function
    
    Public Function SomeMethod2() As String
        Return "Value 2"
    End Function
    '...
End Module

* Static Classes and Static Class Members (C# Programming Guide) 
** Shared - specifies that one or more declared programming elements are associated with a class or structure at large, and not with a specific instance of the class or structure.

Tuesday, 10 August 2010

Notes on Service-Orientation

I was thumbing through my copy of SOA Principles of Service Design by Thomas Erl, and thought I’d make a few notes on some of the standout concepts as well as notes picked up from other locations.

As usual this is going to be a work in progress…

OASIS (Organization for the Advancement of Structured Information Standards) defines SOA as:

“A paradigm for organizing and utilizing distributed capabilities that may be under the control of different ownership domains. It provides a uniform means to offer, discover, interact with and use capabilities to produce desired effects consistent with measurable preconditions and expectations.”

Principles of Service-Orientation as a design paradigm

Erl describes some of the principles of a service-oriented design paradigm in the following terms:

  • Standardised Service Contract
    • The purpose and capabilities of a service are exposed by a service contract.
  • Service Loose Coupling
    • Emphasis should be placed on reducing dependencies between the service contract, its implementation and its consumers.
  • Service Abstraction
    • Hide the underlying details of a service from its consumers.
    • Enables and preserves loose coupling. 
  • Service Reusability
    • Emphasises the positioning of services as enterprise resources “with agnostic functional contexts”.
  • Service Autonomy
    • Underlying solution logic needs to have a significant degree of control over its environment and resources.
  • Service Statelessness
    • “The management of excessive state information can compromise the availability of a service and undermine its scalability and potential.”
    • Ideally, services should remain stateful only when required.
  • Service Discoverability
    • “For services to be positioned as IT assets with repeatable ROI they need to be easily identified and understood when opportunities present themselves.”
  • Service Composability
    • Services should be capable of participating as effective composition members.
Tuesday, 10 August 2010

Friday, 6 August 2010

Isolation levels in SQL Server

Isolation defines how or when changes made by an operation become visible to other concurrent operations. In other words you can use Isolation levels to isolate a resource for a transaction and protect that resource from modification by other transactions.

Resources are protected through the use of locks. SQL Server decides what locks to take out (and when) by looking at the Isolation Level for the transaction. Lower levels of isolation will allow multiple access to a resource simultaneously but may introduce concurrency related problems (e.g. dirty-reads, data inaccuracy). Higher levels of isolation should eliminate concurrency problems but risk introducing blocking.

Serializable

All transactions occur in a completely isolated fashion.

Places a range lock on the data set preventing other users from updating or inserting rows into the data set until the transaction is complete.

This is the most restrictive of the four isolation levels.

Repeatable read

All data records read by a SELECT statement cannot be changed. The transaction acquires read locks on all retrieved data, but does not acquire range locks.

Locks are placed on all data that is used in a query preventing other users from updating the data. However, new ‘phantom’ rows can be inserted into the data set by another user and will be included in later reads in the current transaction.

Read committed

Records retrieved by a query are not prevented from modification. Non-repeatable reads may occur (data retrieved in a SELECT statement may be modified by some other transaction when it commits). Read locks are acquired on selected data but they are released immediately. Write locks are released at the end of the transaction.

Shared locks are held while the data is being read to avoid dirty reads but the data can be changed before the end of the transaction.

This is the default Isolation Level of SQL Server. It eliminates dirty-reads but other concurrency problems remain.

Read uncommitted

Dirty reads are allowed. One transaction may see uncommitted changes made another transaction.

It is possible to read uncommitted or dirty data but values in the data can be changed and rows can appear or disappear in the data set before the end of the transaction.

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