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