February 2007 - Posts

Windows Mobile 6 For Developers

I just came across a very good article on MSDN about the new features of Windows Mobile 6 for Developers.

The product naming has changed for the new version:

Windows Mobile for Smart Phone => Windows Mobile 6 Standard
Windows Mobile for PocketPC => Windows Mobile 6 Classic
Windows Mobile for PocketPC Phone Edition => Windows Mobile 6 Professional

And the SDK for Windows Mobile will be available on MSDN on the 1st of March. The SDK will come in two editions:

Windows Mobile 6 Standard SDK: For devices without a touch screen (WM6 Standard)
Windows Mobile 6 Professional SDK: For devices with a touch screen (WM6 Classic and Professional)

It is good to see the .NET Compact Framework 2.0 SP1 and SQL Server 2005 Compact Edition are both pre-installed in the ROM of all WM6 devices.

Can't wait to get my hands on the WM6 SDK, only 5 days left...

Posted by Mehran Nikoo | with no comments

WCF Behaviours

WCF has an extensible architecture that allows us to customise various elements like Hosts, Bindings, Channels and Behaviours. Behaviours enable us to modify the runtime behaviour of services and add custom extensions to inspect and validate the service configuration and messages.

Behaviours come in four flavours based on their scope so it is important to choose the right type:

Service Behaviour
- Applies to the entire service runtime (which may implement multiple Contracts), including ServiceHostBase.
- Implements IServiceBehavior.

Contract Behaviour

- Applies to the entire contract, ClientRunTime and DispatchRuntime.
- Implements IContractBehavior.

Operation Behaviour

- Applies to the service operation, ClientOperation and DispatchOperation.
- Implements IOperationBehavior.

Endpoint Behaviour

- Applies to the endpoints and its EndPointDispatcher.
- Implements IEndpointBehavior.

It is interesting to know that although these interfaces are called IXXXBehavior and follow a unified method naming scheme, we don't have an "IBehavior" interface. This is because the parameters passed into those methods are different (they are scope related).

All these interfaces have the following four operations, except the IServiceBehaviour, which is missing the ApplyClientBehaviour as it only applies to the service.

  • AddBindingParameters: You can use this method to support custom bindings by providing additional information about the entity (Contract, Service, Operation or Endpoint) to the runtime.
  • ApplyClientBehavior: Allows you to examine, modify and add insertion points to the client application.
  • ApplyDispatchBehavior: Allows you to examine, modify and add insertion points to the server application.
  • Validate: Use to validate the configuration of the entity and to make sure it supports the required behaviour and/or binding.

In order to add custom behaviour to a service, you need to follow these steps:

  • Create a class that implements the appropriate behaviour interface.

  • Implement the methods on the interface. Note that you do not have to provide functionality for every single method. For example, if you want to inspect all messages when they arrive at the server, all you need to do is to add the inspector objects in ApplyDisptachBehavior so the rest of the interface operations can be left empty.

    The behaviours do not do much on their own. WCF calls the methods you implement during the initialisation of the service just before it is opened. So you can use those methods to inject your customised behaviour into the runtime (i.e. by adding message inspectors, modifying the serialisers, etc).

  • Add the behaviour to the runtime. You can do this by:
    • Writing code: Add your behaviour to the Behaviors collection of the related entity before starting the host.
    • Decorating with an attribute: Some people prefer the declarative approach. Change your behaviour class (which implements IXXXBehavior) so that it inherits from Attribute. Then decorate the appropriate entity with the behaviour class. You cannot use this approach for Endpoint Behaviours.
    • Configuration: This is the most flexible option as it allows you to configure your service without changing the code. However, you cannot add Contract or Operation behaviours using the configuration, which makes sense as Contract/Operation behaviours have an impact on design so they should be defined and added at design time as opposed to run-time. In order to expose your behaviour through configuration, you need to create a class that derives from BehaviorExtensionElement. This page on MSDN provides more details.
Posted by Mehran Nikoo | with no comments
Filed under: ,

Sysinternals Troubleshooting Utilities

Just noticed (via Ohad's blog) that the Sysinternals troubleshooting utilities like FileMon, RegMon, ProcMon and ProcExplorer have been rolled up into a single downloadable package (8MB). Having to open every single product page before downloading was a real pain!
Posted by Mehran Nikoo | with no comments

The Magic of the CLR - ThreadAbortException

We are developing a multi-threaded job executor (a Windows Service) in our .NET 2.0-based application. We had a discussion this morning as to how we should respond to service control messages like "Pause" and "Stop". The requirement for "Pause" is fairly straightforward; all we need to do is not to pick up a new job once the current job has finished executing. But when the "Stop" control message is received, we need to wait for a pre-determined period (e.g. 3 seconds) of time before aborting all of the worker threads and shutting down the process.

We also have a requirement to mark any job whose worker thread was aborted as "Critically Failed". So we were thinking of asking the service main thread to join the worker threads with a timeout, and then abort any thread that did not complete its job within that time period. In .NET, you can abort a thread by calling the Abort method on an instance of the System.Threading.Thread class. The CLR in .NET 2.0 is a polite guy so rather than terminating the thread, it asks the thread to terminate itself. This is done by raising ThreadAbortException on the worker thread as soon as it is in an alertable status. This gives the worker thread a chance to perform the clean-up process by catching the ThreadAbortException.

Now the question is what happens if, God forbid, the code running on the worker thread has a nice catch all block, which swallows all of the exceptions including ThreadAbortException? If the CLR didn't do magic, the worker thread wouldn't be aborted and our service could wait for a long time (or more likely indefinitely - as it has been written by a developer who has created a catch all block that swallows unhandled exceptions so an infinite loop or a deadlock can be expected!) before it can be stopped.

So how does the CLR handle this? By re-throwing the ThreadAbortException at the end of the finally block (or the catch block if there is no finally block), which causes the worker thread to be aborted. However, in our scenario, we want to mark the job as "Critically Failed" and perform a graceful shutdown. This is where ResetAbort method on the Thread class comes to the rescue. Calling ResetAbort on the worker thread tells the CLR not to re-throw the ThreadAbortException so it should be used with care. As this piece of code is being written by our application framework team, we are confident that the clean up process won't take long.

Now, the final question is, what happens if a developer catches ThreadAbortException, calls ResetAbort on the thread in the catch block and then performs a long-running process or enters an infinite loop? Although the CLR can't do much in such scenario, but the project manager surely can by asking that developer to look for another job!

There are some cases where none of these polite solutions can stop an offending thread, so the "rude" termination command (a.k.a. End Task) is always an option.

Posted by Mehran Nikoo | with no comments
Filed under:

Serialisation and Encoding in WCF

Although serialisation and encoding can be considered as closely related subjects in messaging, but from a design/implementation perspective they are completely independent processes running at different points in time as messages are sent between applications. In this post I will try to show how they work and highlight their differences.

Serialisation

Messages in WCF can be serialised using one of the three built-in serialisers:

- XmlSerializer
- DataContractSerializer
- NetDataContractSerializer

You can also implement your own serilisation algorithm if you want to.

The way a message is serialised has a design impact on the contract and so, the serialiser forms part of the service contract. Why? Because the serialisation algorithm specifies which elements are published, how they are published, etc. For example, consider those scenarios where the default behaviour of the serialiser does not meet your requirements so you have to implement ISerializable or IXMLSerializable. This is what we call a design impact.

You can specify the serialiser by decorating the service with DataContractFormatAttribute or XMLSerializerFormatAttribute. WCF does not provide an attribute for the NetDataContractSerializer because the WCF team wanted developers to follow the service orientation best practices by sharing the contract not the type (more on NetDataContractSerializer here).

But no matter which serialisation option (XMLSerailizer, DataContractSerializer or NetDataContractSerializer) you choose, the serialised message will be an XML infoset, although the resulting XML will not look like the same. So even if you use a .NET native binding like the NetTcpBinding and choose the DataContractSerializer, your message will still be serialised into XML.

If you want to know more about WCF serialisers, go and read Aaron Skonnard's article on MSDN.


Encoding

Once the message is serialised into an XML infoset, the specified binding will be applied before the message is sent to the destination. Each system-provided binding consists of a set of binding elements, each of which belongs to a binding layer that deals with a specific aspect of the messaging like security, session/ transaction management, transport and encoding (transport and encoding elements are mandatory).

The encoding binding element specifies how the XML infoset is encoded before it is passed to the transport layer. WCF provides Binary, Text and MTOM encodings and they are only available if they are supported for the transport protocol specified in the binding. For example in order to use the Binary encoding you need to use NetTcpBinding or NetNamedPipeBinding whereas Text and MTOM encodings are supported for the transport protocols based on web services like WSHttpBinding.

As you can see, unlike the serialisation, the encoding does not have an impact on the service contract and choosing the encoding type is not necessarily a design-time decision. That is why the encoding can be specified as a configuration element rather than an attribute on the service contract.

Posted by Mehran Nikoo | with no comments
Filed under: ,

Empty Recycle Bin Shortcut in Windows Vista

It seems the first potential security hole in Vista has been identified. This is nothing to do with Windows Vista in particular as speech recognition and voice command have been out there for a while and the only thing Vista is going to change is to widen the adoption of this technology.

Anyway, in the meanwhile, if you have Windows Vista installed on your computer and you want to empty your "Recycle Bin", perform the following steps:

1- Make sure your computer is turned on and connected to the Internet.
2- Enable Speech Recognition and voice commands.
3- Place your microphone next to the speaker.
4- Turn the microphone and the speaker on.
5- Make sure the volume meter is high enough to allow the microphone to capture the speaker's sound and it is low enough so that it doesn't result in an echo. If this is not possible, try to use an echo cancellation feature.
6- Navigate to a web site that is known to play a malicious audio, sending the "Empty Recycle Bin" voice command to Windows Vista.
7- Go shopping.

When you come back home, there is a slight chance that your Recycle Bin has been emptied by that malicious web site. Don't panic if the shortcut doesn't work though. Just right click on the Recycle Bin icon and choose "Empty Recycle Bin".

I am so excited about this new shortcut that I have created a visualisation showing how it works:

Hope that helps!

PS: Icons from here

Posted by Mehran Nikoo | with no comments
Filed under: