Consider very simple code
1 class Program
2 {
3 static void Main(string[] args)
4 {
5 AppDomain newDomain = AppDomain
6 .CreateDomain("MyDomain_1");
7 }
8 }
Question: How many domains are there at line 7, given this code run as a managed console application?
Think about it before continuing reading.
Without additional searching of the Internet or digging clever books it is easy enough to check what's happening. CLR has had several debuggers that allow developers to to debug the code on the edge of managed and unmanaged code. One of these debuggers is Son of Strike (SOS).
Let's get our hands dirty. I put a break point at line 7 and start debugging in Visual Studio. Once the breakpoint is hit, I load SOS from the Immediate Window in Visual Studio. There are usually some troubles with just loading the debugger extension, so consider this post to troubleshoot SOS.
.load sos
This will hopefully load SOS and now let's run the command to get all AppDomains:
!DumpDomain
The output on my machine was
--------------------------------------
System Domain: 59da1478
LowFrequencyHeap: 59da1784
HighFrequencyHeap: 59da17d0
StubHeap: 59da181c
Stage: OPEN
Name: None
--------------------------------------
Shared Domain: 59da1140
LowFrequencyHeap: 59da1784
HighFrequencyHeap: 59da17d0
StubHeap: 59da181c
Stage: OPEN
Name: None
Assembly: 00240a20 [C:\Windows\Microsoft.Net\assembly\GAC_32\...\mscorlib.dll]
ClassLoader: 00240ac0
Module Name
589e1000 C:\Windows\Microsoft.Net\assembly\GAC_32\...\mscorlib.dll
--------------------------------------
Domain 1: 001f19f0
LowFrequencyHeap: 001f1d6c
HighFrequencyHeap: 001f1db8
StubHeap: 001f1e04
Stage: OPEN
SecurityDescriptor: 001f3168
Name: Test.exe
Assembly: 00240a20 [C:\Windows\Microsoft.Net\assembly\GAC_32\...mscorlib.dll]
ClassLoader: 00240ac0
SecurityDescriptor: 0023b5a8
Module Name
589e1000 C:\Windows\Microsoft.Net\assembly\GAC_32\...mscorlib.dll
Assembly: 0024b048 [C:\Projects\Private\Test\bin\Debug\Test.exe]
ClassLoader: 0024b0e8
SecurityDescriptor: 0024c0e0
Module Name
003c2e9c C:\Projects\Private\Test\bin\Debug\Test.exe
--------------------------------------
Domain 2: 0024f730
LowFrequencyHeap: 0024faac
HighFrequencyHeap: 0024faf8
StubHeap: 0024fb44
Stage: OPEN
SecurityDescriptor: 00252c28
Name: MyDomain_1
Assembly: 00240a20 [C:\Windows\Microsoft.Net\assembly\GAC_32\...mscorlib.dll]
ClassLoader: 00240ac0
SecurityDescriptor: 002542c8
Module Name
589e1000 C:\Windows\Microsoft.Net\assembly\GAC_32\...mscorlib.dll
Answer: so as you can see 4 domains will get created. Namely: system, shared, one default user domain and the last one that the user code additionally creates (lines 5-6). I found really nice article describing what happens when CLR starts and how CLR bootstrapper loads domains.
If you enjoyed this post, make sure you subscribe to my RSS feed!
6a0f951c-c0dd-4be8-8597-3aa7ddd969b4|0|.0
This is one of the typical interview questions: when do I need to use a StringBuilder and how a simple implementation would look like?
The problem with a System.String type is that it is actually an immutable reference type although it seems to behave like mutable value type. Immutability means that for any write operation performed with the same string, a new object is mandatory created. For example, s1 = s1 + s2 will not modify s1, but will create a new object with a concatenated s1 and s2 and drops the reference to the old s1 to garbage collector. This is required to support long strings (< 2GB in .NET 4), save time and space complexity and maybe (which would be a pure guess) it was easier to follow a successful example of Java strings.
StringBuilder class has internal access to the string object and is useful for any string manipulations, especially numerous. Internally, StringBuilder uses string object, and since .NET 4 it uses a char array. This class does not create copies of string objects but rather acts as if it works with one mutable string
Because StringBuilder implements a Builder design pattern any state-changing operation should return the object itself (this). ToString() method acts as a Build() method and as it is defined in the System.Object, there is no need to include ToString() in the contract.
public interface ISimpleStringBuilder
{
ISimpleStringBuilder Append(string value);
ISimpleStringBuilder Clear();
int Lenght { get; }
int Capacity { get; }
}
A very simple implementation of the builder class may look like this
public class SimpleStringBuilder : ISimpleStringBuilder
{
private char[] _internalBuffer;
public ISimpleStringBuilder Append(string value)
{
char[] data = value.ToCharArray();
//check if space is available for additional data
InternalEnsureCapacity(data.Length);
foreach (char t in data)
{
_internalBuffer[Lenght] = t;
Lenght++;
}
return this;
}
public override string ToString()
{
//use only non-null ('\0') characters
var tmp = new char[Lenght];
for (int i = 0; i < Lenght; i++)
{
tmp[i] = _internalBuffer[i];
}
return new string(tmp);
}
...
}
This code is of course very basic, inefficient, not thread-safe, doesn't make any input validation etc. It does however demonstrates the idea behind StringBuilder class.
SimpleStringBuilder.zip (75.77 kb) [Downloads: 8]

If you enjoyed this post, make sure you subscribe to my RSS feed!
8c2470ab-3e33-49ed-9a48-e4ee7842dcff|0|.0
I was trying to create a simple project based on WCF where a service can notify clients about something (as oposed to the standard scenarios where a client asks a service to perform some operation). The simplest way to do so is to use callbacks. I have made up a very simple solution to demonstrate this concept. A sample solution has two interfaces: one for the usual service contract and another one for the client callback.
[ServiceContract(CallbackContract = typeof(IContractCallback))]
public interface IContract
{
[OperationContract]
void Foo();
}
[ServiceContract]
public interface IContractCallback
{
[OperationContract]
void OnFooCallback();
}
A very basic implementation of these contract can look like this
internal class WcfService : IContract
{
public void Foo()
{
//Do work...
var callback = OperationContext.Current
.GetCallbackChannel<IContractCallback>();
callback.OnFooCallback();
}
}
internal class ContractCallback : IContractCallback
{
public void OnFooCallback()
{
Console.WriteLine("...");
}
}
This is how this small app looks


Using the callback contract can be straight-forward, however there are some limitations:
- Only NetTcpBinding, NetNamedPipeBinding and WSDualHttpBinding bindings are supported
- One callback contract per service contract is allowed
- Client must keep the connection open the whole time
- Service must use reentrant or multiple concurrency mode
This project can be downloaded using the link below or from the github.
CallbackService.zip (17.49 kb) [Downloads: 108]

If you enjoyed this post, make sure you subscribe to my RSS feed!
c5eea1dd-b34c-4515-b2cc-a001f7d31e6a|0|.0
Any service oriented architecture, including WCF, follows a convention where a client implements a proxy pattern. Proxy allows the client to abstract from the concrete implementations and locations of the service. Client often creates stubs that work well in the compile time, whereas in runtime stubs are resolved and actual calls are made to the service.
Closing WCF client
A client has an inherited responsibility of gracefully closing the connection. It is always recommended to close the proxy client. If the binding between a client and a service is transport-layer sessionful, then closing a proxy is essential to tear down the connection between both parties. Service has a payload threshold defined for concurrent connections. If the number of concurrent connections goes above this threshold linearly then the overall service performance exponentially decreases. This is why it is crucial to dispose of the connection as soon as possible. Closing the proxy also notifies the service instance that it is no longer in use and may be collected by GC. If the client does not close a connection, it is still automatically torn down by WCF timeouts (found in the configuration files).
Aborting WCF client
In the situation where there is a fault in the service-client interaction, the objects on both ends are potentially totally broken. Thus using a proxy after the exception is not advised. Given the WCF binding use transport sessions, the client after a fault would not even be able to close it (if there was no transport layer session then the client could use or close the proxy, but this is not recommended as the configuration of sessions could change). So after a fault has happened the only safe operation is to abort a proxy.
Coding
Close (and Abort on fault) needs to be called for all the client calls, therefore these methods can be moved to a proxy itself
class Client1 : ClientBase<IContract1>, IContract1
{
public void DoWork()
{
try
{
Channel.DoWork();
Close();
}
catch
{
Abort();
throw;
}
}
}
If you enjoyed this post, make sure you subscribe to my RSS feed!
cc69a51c-4367-4251-aae4-04ca22863759|0|.0
It is well known that WCF service can be hosted as a self-hosted application, IIS web service or a Windows service. This post is dedicated to the Windows service hosting and it goes through some advanced techniques on how to host many WCF services in one windows service.
So, here I have got three projects: multiple WCF services project, a client and a Windows service installer. Let us start with the WCF services. This project has three service interfaces and correspondently three service implementations.

Sample interface looks like this:
[ServiceContract]
public interface IService1
{
[OperationContract]
string DoAction1();
}
And its implementation is very simple
public class Service1 : WindowsManagedService, IService1
{
public Service1() : base(typeof(Service1)) { }
public string DoAction1()
{
return "Action 1";
}
}
These are the interfaces in WCF service project

Class diagram for the services that implement those interfaces

You must have noticed that there are a few other types like IWindowsManagedService and WindowsManagedService - this is basically a bridge that allows WCF services to be hosted within Windows service.
public interface IWindowsManagedService
{
void Start();
void Stop();
}
public abstract class WindowsManagedService : IWindowsManagedService
{
private ServiceHost serviceHost;
protected WindowsManagedService(Type serviceType)
{
serviceHost = new ServiceHost(serviceType);
}
public void Start()
{
serviceHost.Open();
}
public void Stop()
{
serviceHost.Close();
}
}
Next, let’s take a quick look into the host project. This project contains a configuration file for the WCF services. It also has one installer class which is picked up by installutil. But the main type here is WindowsManagedServices which uses reflection to find WCF services that can be hosted in one Windows service
public class WindowsManagedServices : ServiceBase
{
private List<IWindowsManagedService> services;
public WindowsManagedServices()
{
services = new List<IWindowsManagedService>();
var assembly = Assembly.GetAssembly(typeof(IWindowsManagedService));
var types = assembly.GetTypes();
foreach (var type in types)
{
if (!type.IsAbstract && typeof(IWindowsManagedService).IsAssignableFrom(type))
{
var serviceObject = (IWindowsManagedService)Activator.CreateInstance(type);
services.Add(serviceObject);
}
}
}
protected override void OnStart(string[] args)
{
foreach (var service in services)
{
service.Start();
}
}
protected override void OnStop()
{
foreach (var service in services)
{
service.Stop();
}
}
}
Then, I used installutil to install the windows service and here is what I end up with
- 1 Windows Service WCFServices
- 3 WCF services
http://localhost:8083/WCFServices/IService1
http://localhost:8083/WCFServices/IService2
http://localhost:8083/WCFServices/IService3
Lastly, a sample client to this application
class Program
{
static void Main(string[] args)
{
IService1 client1 = new Service1Client();
IService2 client2 = new Service2Client();
IService3 client3 = new Service3Client();
Console.WriteLine("Client 1 says: " + client1.DoAction1());
Console.WriteLine("Client 2 says: " + client2.DoAction2());
Console.WriteLine("Client 3 says: " + client3.DoAction3());
Console.ReadLine();
}
}

The whole project can be downloaded using the link below. Unzip it, run the solution file and hit F5 in Visual Studio 2010. It should start two projects: services and the client.
WCFServiceHosting.zip (46.48 kb) [Downloads: 12] [UPDATED after discovery of the client's port mismatch)

If you enjoyed this post, make sure you subscribe to my RSS feed!
3f9c2985-f063-447f-84ab-8261ee842cac|0|.0