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