Blog from Saravanan Arumugam

Let us talk about Technologies

Monthly Archives: April 2011

The virtual machine could not be started because the hypervisor is not running

Hyper-V is a key feature that Windows Server 2008 R2 provides. It is provided as one of the server roles. The main component of Hyper-V is called Hypervisor. It’s the virtualization software between the hardware and the operating system to support multiple operating systems to run on the same host machine.



I got the following error after installing the Hyper-V role in the Windows Server 2008 R2.

Hper-V exception



Though the virtualization software is provided by the Windows Server, its not the end of story. The hardware has to support it. Virtualization requires a 64 bit processor that is equipped with the virtualization (Intel VT and AMD-V) technology. Intel has a huge list of processors supporting virtualization technology and so is AMD.

By default the virtualization technology is disabled. Installation of Hyper-V also requires enabling of the virtualization technology in the hardware.



In my case, I have a Intel Xeon processor which supports the virtualization technology (Intel VT). The next possible solution is to enable the hardware-assisted Virtualization.

In the server startup, I pressed F2 to enter the BIOS set up. The dell machine’s Bios version was 1.6.4.

Under the Processor Settings I found the Virtualization Technology. I found it was disabled. I enabled it and saved the Bios changes.

This solved the exception in the Hyper-V. The Hyper-V then was able to connect and install another operating system on my new virtual machine.



Virtualization with Hyper-V: FAQ

Hypervisor is not running error: How to fix


DNS Installation & Setup

I bought a new Dell server recently. When I looked out for help in configuring DNS I found the following videos very much helpful. I write this blog just to make sure that I don’t lose these videos.


Following videos guides the setup of Active Directory Server

dcpromo.exe helps to install the Active Directory Services.

Lambda expressions

A lambda expression can be understood as an anonymous function which can contain expressions and statements. It is one of the key enhancements that C# 3.0 provided to support Linq.

Lambda expressions are useful in all the places where a delegate or expression tree is applicable. In particular, lambda expressions are very useful in the IEnumerable<T> typed objects, which carries extension methods accepting delegate parameter of type Func<T,TResult>.

A lambda expression is written in the following form

parameters => expression/{statements}

Here “=>” is read as “goes to”. Parameter can be a single parameter or group of parameters enclosed within parenthesis.

All the rules of anonymous methods are applicable to lambda expressions. Lambda expressions can be categorized as expression lambda and statement lambdas.

In this paper I am going to present different features of lambda expressions with examples.


Simple Lambda

To square a value, a function has to take the form fn(x) = x * x;

This can be represented as x => x * x in lambda expression.

The following C# code evaluates this function with lambda expression.

delegate long squareValue(int a);


static void Main(string[] args)


    //Simple Lambda

    squareValue squareOf = x => x * x;

    Console.WriteLine("Square of {0} is {1}", 5, squareOf(5));

    //Equivalent ananymous method

    squareOf = delegate(int x) { return x * x; };


Multiple parameters can be supplied by enclosing them in parenthesis. e.g (x, y)

Note: An expression can take zero parameters and can return void.


Lambda calling external method

A lambda can call a external function as follows. The following expression valuates the function fn(x, y) = x² + y.

delegate U expressionDelegate<T, U>(T m, U n);


static void Main(string[] args)


    //Lambda expression calling a method fn(x,y) = x² + y

    expressionDelegate<int, float> expression =

        x, y) => Square(x) + y;


    int a = 8; float b = 5.6f;

    Console.WriteLine("Result of {0}² + {1} = {2}",

         a, b, expression2(a, b));


Square(x) is the external method.


Lambda vs inbuilt System.Func<T, TResult> delegate

Many standard query operations take an input parameter whose type is one of System.Func<T, TResult> family. Func<T, TResult> delegate define the number of input parameters, type of the parameters and the return type. Func<T, TResult> can take up to 16 input parameters and a non void return type.

The last type specified in the Func<T, TResult> is the type of the result or return type.

For example Func<int, float, bool> indicates that this is going to hold a delegate with int and float type input parameters and is going to return a bool as output.

Func<int, int, bool> expression = (x, y) => x == y;
Console.WriteLine(expression(2, 2));



Currying is a function transformation technique with which a function with multiple parameters can be transformed into a series of multiple functions each taking a single parameter.

With currying technique, (x, y) = x*x + y*y is equivalent to x => (y => x*x + y*y )

Here is the C# implementation of the curried function.

//With Currying (x, y) => x*x + y*y is equivalent to x =>(y => x*x + y*y))
Func<int, Func<int, int>> curriedExpression = x => y => x * x + y * y;
int m = 5, n = 7;
Console.WriteLine("Result of {0}² + {1}² = {2}",m, n, curriedExpression(m)(n));

Note the declaration of curriedExpression. The outer expression is said to take the integer as input, and the output of it is another Func<> delegate. This delegate in turn accepts an integer and outputs an integer.

The execution of expression is also a little different from the that of usual expressions. curriedExpression (m) returns a function. Input n is sent to the resulting function to complete the execution.


Statement Lambdas

Statement lambdas take the following form

(parameters) => {statements;}

Any c# statement can be enclosed within the braces and all the paths should end with a return statement, unless the return message is declared to be void.

Let us take the expression to find the largest among 3 integers for discussion.

With the expression lambda we can specify it as

Func<int, int, int, int> greatestNumber = 
         (x, y, z) => 
         (x > y) ? ((x > z) ? x : z) : ((y > z) ? y : z);
Console.WriteLine("Greatest number in the given set is {0}", 
         greatestNumber(15, 6, 11));

The same can be expressed in the statement lambda as

Func<int, int, int, int> greatestNumber = (x, y, z) =>
    if (x > y)
        if (x > z)
            return x;
            return z;
        if (y > z)
            return y;
            return z;

The body of the statement lambda can have any number of statements. However it is recommended to have only a few statements in them say two or three. More than that might affect the readability of the expression.


Lambda inside another lambda

It is possible to have nesting in lambdas. For instance the example of finding greatest among 3 numbers can be expressed as greatestOf(x, y, z) = greaterOf(greaterOf(x, y), z)

The expression greatestOf requires another expression (greaterOf) to be executed within it.

Func<int, int, int> greaterOf = (x, y) => (x > y) ? x : y;
Func<int, int, int, int> greatestOf = (x, y, z) => greaterOf(greaterOf(x, y), z);
Console.WriteLine("Greatest number in the given set is {0}", greatestOf(7, 2, 3));


Variable Scope in Lambda expressions

Lambda expressions can refer to the variables outside the expression within the execution scope. The variables used within the expression would be retained even if the original variable goes out of scope or garbage collected. Here the rule is that the variables in the expression should have been assigned some value before being used.

An example to reflect lambda expression’s treatment of local variables follows.

class LambdaScope
    static Func<string> zeroParameterLambda = null;
    static void Main(string[] args)
        (new MyClass()).DoSomething();
    class MyClass
        public void DoSomething()
            DateTime startTime, endTime;
            startTime = endTime = DateTime.Now;
            zeroParameterLambda = () =>
         Console.WriteLine("Hash code of startTime from lambda expression: {0}", 
         return string.Format("Operation started by {0} and stopped by {1}", 
                 startTime, endTime);
            //Modify the endTime value                
            endTime = DateTime.Now;
            Console.WriteLine("Hash code of startTime from DoSomething(): {0}", 

In the code, you can note that the zeroParameterLambda is defined within MyClass.DoSomething() method. This expression uses the local variables startTime and endTime for its definition. But the zeroParameterLambda is executed only in the Main(). Here the values of startTime and endTime are kept safe to be used in zeroParameterLambda, even though they are out of scope.


I am still exploring on this topic to know more on how the variables are retained and the consideration of garbage collector on these variables. Looking forward to post more papers on this topic.


Lambda recursion

Recursion is the concept of a function calling itself. Recursion is useful in doing mathematical functions on series of numbers, such as factorial, sum/product of a series etc. With lambda expressions, recursion is so handy.

To make the recursion, first declare the Func<T, TResult> initializing it to null. In the next line we can define the expression which can make use of the expression name declared in the first line.

Here is an example of lambda recursion to find a factorial a number and to check if the number is prime or not.

//Factorial of n or n!
Func<int, int> fact = null;
fact = x => (x == 0) ? 1 : x * fact(x - 1);
int a = 6;
Console.WriteLine("{0}! is {1}", a, fact(a));
//Check prime number
Func<int, int, bool> prime = null;
prime = (x, y) => (y == 1) ? true : (x % y == 0 ? false : prime(x, y - 1));
Func<int, bool> isPrime = x => prime(x, x / 2);
int b = 2011;
Console.WriteLine("{0} is a {1}prime number", b, (isPrime(b)?"":"not "));


Use of Lambda expression

Lambda expressions are introduced to primarily support the Linq in C# 3.0. However lambda expressions are applicable to variety of places. Let me present a few uses of lambda expressions.


Use of Lambda expression in place of Predicate<T> and Action<T>

Lambda expressions can be used in the old style List.FindAll<T>/ConvertAll etc. where the parameter is of type Predicate<T> or Action<T>.

List<int> numberArray = new List<int> { 1, 4, 3, 2, 6, 7, 9, 13 };
Console.Write("\nOdd numbers in the array");
numberArray.ForEach(x => { if ((x & 1) == 1) Console.Write(" " + x); });
Console.Write("\nMultiples of 3 in the array");
numberArray.FindAll(x => x % 3 == 0).ForEach(y => Console.Write(" " + y));


Use of lambda expression as event handlers

Lambda expressions can be used as simple event handlers.

For instance in the following code snippet, I have used the lambda expression as a handler for Console.CancelKeyPress event.

A little background about the code snippet; following console application would start printing from 0 to 10000 sequentially. While printing, the operation can be interrupted by pressing Ctrl+C in the middle. This would terminate the current console operation. Before termination, the CancelKeyPress event would be triggered. So with the following code in place, we can see a custom message before console operation gets terminated.

Console.CancelKeyPress += 
    new ConsoleCancelEventHandler(
        (object obj, ConsoleCancelEventArgs e) => 
                 Console.WriteLine("Console is about to break...")
for (int i = 0; i < 10000; i++)


Use of lambda expression in IEnumerable<T> extension methods

IEnumerable<T> provides a variety of extension methods to support Linq. There are many extension methods that would accept lambda expressions in place of Func<T, TResult> delegate family.

Here is an example.

var myObject = new[] {
                   new {Name = "Saravanan", Age = 20},
                   new {Name = "Thomos", Age = 18},
                   new {Name = "George", Age = 25}
var filteredObject = myObject.First(obj => obj.Name.StartsWith("S"));
Console.WriteLine("Filtered Output: Name={0}, Age={1}", 
         filteredObject.Name, filteredObject.Age);


Use of lambda expression to do operations in a different thread

The following sample does a file operation in a different thread while the main thread continues to work on something. The main advantage of this technique is that the sub thread has full access to the local variables of main thread. It would be a real delight for those who have experienced the difficulty in passing objects between the threads.

string textToBeWritten = "Some sample text";
Thread t = new Thread(new ThreadStart(() =>
    using (Stream stream = File.Create(@"C:\Temp\somefile.txt"))
        StreamWriter sw = new StreamWriter(stream);
        lock (textToBeWritten)

Note that the textToBeWritten is a variable outside the scope of the sub thread, but still the sub thread has complete control over it.

Note: Care should be taken to use these variables in a thread safe way. Use of lock{} can help.



Lambda expression is a great value-add to .Net languages. While the lambda expression provide the flexibility and short cuts to coding, it comes with the cost of readability. So the recommendation is to limit the use of lambda expression with a clear consideration of readability and maintainability. In every other sense, lambda expression should be a favorite for developers.


Reference materials

Lambda Expressions (C# Programming Guide)

Anonymous Methods (C# Programming Guide)

Where to use Lambda Expression

Lambda calculus

Simple Duplex Channel Implementation

In WCF, we have three modes of message exchange, called Message Exchange Patterns (MEP)

  • Request/Response mode
  • One way message transfer
  • Duplex communication

Any default WCF service use the Request/Response MEP.

In places where we don’t expect any reply to come back from the receiver and where we simply trust that the communication channel would do its job right, we go for One way message exchange. In such cases even if an exception occurs at the receiving end we won’t receive it at the calling end. Example for such communication could be calling a logging service, Message queues etc.

The last one is the point of our interest in this paper, Duplex communication. By definition a duplex communication is, a communication between two parties with equal ability to exchange information. In terms of WCF, the service and client can talk to each other independently through two different end points. Upon client’s request to a service’s contract, the service would respond by calling a contract implemented in the client application itself.

WCF provides methods of implementing the duplex communication in a non-difficult but a little tricky way of coding. Let’s have a look at the very simple implementation of duplex communication.


    Step 1: Declare two services contracts, one for the duplex service and another for callback

    The very first thing is to create two service contracts. One is for the duplex service, the other one is the callback.

    In my example, I am going to create a service which will send a greeting message and the service would respond to the client with an acknowledgment.

    I consider it is important to mention where do I write each code. So on top of each code snippet let me write down if that’s done on client or server side.

  • //Written on Server Side

    namespace DuplexChannel
        [ServiceContract(CallbackContract = typeof(IGreetingCallback))]
        public interface IGreetingService
            void SendGreeting(string message);
        public interface IGreetingCallback
            void GreetingReceived (string message);

    Here IGreetingService is the service contract and IGreetingCallback is the callback contract.

    You can note that the ServiceContractAttribute takes the CallbackContract as the named parameter. This is a notification that the contract is a duplex service contract. CallbackContract parameter takes the type of the callback , in our example IGreetingCallback.

    Note that the duplex operations should be one way (Note that IsOneWay=true in SendGreeting operation). If we miss mentioning the operation as one way, we would end up in a time out exception.


    Step 2: Define the duplex service on the server side (not the callback)

    Next step is to write the definition or implement the duplex service contract into class.

    An important thing to notice here is that we write definition only for the duplex contract, not for the call back. Because callback is the one to be defined on the client side.

    In the step 1 we have declared the structure of the IGreetingService and IGreetingCallback, but in this step we implement only the IGreetingService.

    //Written on Server Side
    namespace DuplexChannel
        [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple)]
        public class GreetingService : IGreetingService
            public void SendGreeting(string message)
                IGreetingCallback callback = OperationContext.Current.
                callback.GreetingReceived("Received the message: " + message);

    In the SendGreeting you can see that we are expecting an instance of callback class. This has to come from the client side. Here the OperationContext.Current.GetCallbackChannel<T>() method retrieves the instance of callback class defined on the client side.


    Step 3: Specify the service behavior

    In the code snippet specified in step 2 we have provided a Service Behavior. Here we have explicitly marked the ConcurrencyMode to be Multiple. By default for any WCF service, the concurrency mode is Single. This means that only a single request would be serviced at a time.

    In the duplex service you can see that the current request (SendGreeting) has to be held in the middle while the call back instance (GreetingReceived) is signaled. So to do this, it either has to have an ability to serve multiple requests (One for the service itself and another one for the callback) or to leave the service in the middle (SendRequest) unprocessed, serve the other request (callback) and then come back to the original request (SendRequest) to complete it.

    The choice of this workflow is up to the design of the service. The workflow of serving multiple requests at the same time can be achieved by setting the concurrency mode as Multiple. Leaving a operation incomplete, jumping to another operation and coming back to the original operation can be achieved through Reentrant concurrency mode.

    So in summary the service behavior of a duplex service may look like this.

    [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple)] 


    [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Reentrant)]

    Step 4: Configure the duplex service

    In the configuration there is no need for any special coding except for the type of binding to use.

    Following is the list of  bingings that support duplex channel.

    1. WsDualHttpBinding (for Http protocol)
    2. NetTcpBinding
    3. NetTcpContextBinding
    4. NetNamedPipeBinding
    5. NetPeerTcpBinding
    6. PollingDuplexBinding (introduced with/for Silverlight 4)

    Note: For a complete list of inbuilt bindings and their capabilities refer to System-Provided Bindings.

    In my example, I am going to use WsDualHttpBinding.

  • <!—- Written on server side –><system.serviceModel>
          <service name="DuplexChannel.GreetingService">
                <add baseAddress="http://localhost:54927/"/>          
            <endpoint address="ws" binding="wsDualHttpBinding" 
             contract="DuplexChannel.IGreetingService" />
              <serviceMetadata httpGetEnabled="true" />
              <serviceDebug includeExceptionDetailInFaults="false" />
              <!--The default setting-->
              <serviceThrottling maxConcurrentCalls="16" 

    Step 5: Create service proxy

    Use service reference or svcutil.exe to create the proxy for the duplex service. This is an usual step.

    Unlike regular proxies, you can find the following changes in the duplex proxy class.

    • Usually the proxy class’s (e.g. GreetingServiceClient) base class would be ClientBase. But for duplex service, the base class would be DuplexClientBase.
    • We cannot find any empty constructor in the proxy class. Every constructor of proxy class would have a InstanceContext parameter. This parameter is inevitable because it has to presents the instance of callback class to the service.
        [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "")]
        public partial class GreetingServiceClient : 
            Messenger.GreetingService.IGreetingService {
            public GreetingServiceClient(InstanceContext callbackInstance) : 
                    base(callbackInstance) {
            public GreetingServiceClient(InstanceContext callbackInstance, 
                string endpointConfigurationName) : 
                    base(callbackInstance, endpointConfigurationName) {
            public GreetingServiceClient(InstanceContext callbackInstance, 
                string endpointConfigurationName, string remoteAddress) : 
                base(callbackInstance, endpointConfigurationName, remoteAddress) {
            public GreetingServiceClient(InstanceContext callbackInstance, 
                string endpointConfigurationName,  EndpointAddress remoteAddress) : 
                base(callbackInstance, endpointConfigurationName, remoteAddress) {
            public GreetingServiceClient(InstanceContext callbackInstance, 
                System.ServiceModel.Channels.Binding binding, 
                System.ServiceModel.EndpointAddress remoteAddress) : 
                    base(callbackInstance, binding, remoteAddress) {
            public void SendGreeting(string message) {

    Step 6: Modify client configuration to include client base address

    If the client base address is not explicitly specified WCF would start using address similar to http://+:80/Temporary_Listen_Addresses/634f73f6-c612-4441-acf8-79ddd5c62f98/

    Port 80 is usually occupied by the IIS. So the run time might throw an exception such as HTTP could not register URL … because TCP port 80 is being used by another application.

    It is a safe procedure to provide the client base address ourselves while designing duplex channel. Client base address can be provided in the binding configuration as follows.

            <binding name="WSDualHttpBinding_IGreetingService"
              <security mode="Message">
                <message clientCredentialType="Windows"
                         algorithmSuite="Default" />
          <endpoint address="http://localhost:54927/GreetingService.svc/ws"
              <userPrincipalName value="Saravanan-PC\Saravanan" />

    Step 7: Start using the proxy

    In the previous section we have noticed that for initializing a proxy class we need to pass an instance of a class as a parameter. This parameter has to be the callback object which implements the callback contract declared in the server side. In my example IGreetingCallback.

    So typical declaration of a proxy would look like this.

    InstanceContext context = new InstanceContext(this);

    client = new GreetingServiceClient(context);


    Step 8: Build the Service Agent

    Though it is optional, its always a good practice to build a service agent which would act as wrapper to the service related activities. Service agent provides an extra layer with which we can isolate all the technical/formal tasks such as initializing proxy, providing callbacks, making asynchronous calls, closing proxies etc. This helps the client application to consider calling a service as easy of calling a simple C# method.

    Here is the Service agent I have written to handle both IGreetingService and IGreetingCallback.

        public class GreetingServiceAgent
            : IGreetingService,
            GreetingServiceClient client;
            public delegate void GreetingHandler(string message);
            public GreetingServiceAgent()
                    InstanceContext context = new InstanceContext(this);
                    client = new GreetingServiceClient(context,
                { client = null; }
            public GreetingHandler GreetingRecievedHandler
            public void SendGreeting(string message)
                if (client != null)
            public void GreetingReceived(string message)
            public void Dispose()
                if (client != null)

    Note that the GreetingServiceAgent implements both the IGreetingService and IGreetingServiceCallback.

    Since the ServiceAgent has implemented IGreetingServiceCallback, an instance of it becomes eligible candidate for the constructor of InsanceContext. That’s the reason we use ‘”this” object as the constructor parameter to InstanceContext. This instance context should be passed as a parameter to proxy initialization.

    It is also possible to create a different class for callback. In such a case the InstanceContext would be initiated with an instance of the callback class.

    Another thing is that GreetingReceivedHandler is provided as a public property which can be set as a delegate to any method that the client prefers.

    Client application has to write a method and set its delegate as GreetingReceivedHandler. When the service completes its operation, this delegate would be retrieved by the server and the server call this method as a callback.


    Step 9: Build the client application to call the service

    As a final step I have created a simple WPF application with a text block, text box and a send button. The text box would take the input message and text block would display the received message. The button would help calling the service with the message entered in the text box.

        public partial class MainWindow : Window
            public MainWindow()
            private void Send_Click(object sender, RoutedEventArgs e)
                if (!string.IsNullOrWhiteSpace(SendMessageTextBox.Text))
                    GreetingServiceAgent agent = new GreetingServiceAgent();
                    agent.GreetingRecievedHandler += GreetingReceived;
            void GreetingReceived(string message)
                ReceivedMessageTextBlock.Text = message;


  • 70-503:Microsoft .Net framework 3.5 – Windows Communication Foundation–Tips

    Yesterday I have completed my exam on Windows Communication Foundation. This is the second exam towards my preparation to MCPD on Enterprise Application Developer 3.5. Next in my list is application development. I thank my guru Robert Seder who has guided me all the way through my preparation.

    It took me 3 attempts to clear this exam. So I hope I have handful of experience to share. In this paper I am planning to share some of the interesting things I found during my exam preparation and in the exam itself.

    • The exam spans for 2 hours with 45 questions.
    • I used 2 books for preparation.
    • First one is Self-Paced Training Kit from Microsoft press (Authors: Bruce Johnson, Peter Madziac and Sara Morgan). I found this book well organized and covers at least 95% of the examination syllabus.
    • The other book I book that helped me a lot was Pro WCF Practical Microsoft SOA implementation written by Chris Peiris and Dennis Mulder.
    • One important thing I found during my preparation is, only after having a hands on practicals (the least is to do the practicals given in the lab section of the each chapter) our study gets fulfilled.
    • Having said the above point I found it was difficult to completely understand the security related chapters since I couldn’t try all of them at my home machine. Everything else is doable from home.
    • The exam syllabus is categorized in the following titles.
        1. Creating Services
        2. Exposing and Deploying Services
        3. Instrumenting and Administering Services
        4. Consuming Services
        5. Securing Services
        6. Managing the Service Life Cycle
    • Even though the training materials guide us through chapter by chapter, we can’t expect any question to be from a single chapter. In other words, every single question is a combination of multiple chapters. For example a question might be asked on duplex communication where the answers might carry different combination of session modes and concurrencies applicable to it. It essence, we can’t ignore any chapter during our study, because it might certainly impact the exam attempt.

    Following are a few tips and areas of concentration that might help the people preparing for this exam.

    Wring of regular contracts, writing one way operations.

    Writing Message and data contracts keeping in mind the opt in mechanism.

    Writing duplex MEP contracts, initializing the proxy of duplex services.

    Concurrency mode to be used on duplex services. Single concurrency is not applicable to duplex is the key to keep in mind. For thread safety we opt the Reentrant concurrency otherwise Multiple is the choice.

    Asynchronous consumption of services.

    Consuming com+ operations in WCF.

    Representational state transfer style of programming. WebGetAttribute and its template styles.

    Quota specifications and throttling.

    Handling the Session lifecycle manually.

    Configuration of the system.diagnostics node for instrumentation.

    Introduction of Parameter Inspector and Message Inspectors in WCF pipeline.

    Understanding of use of Reliable sessions.

    Controlling transactions including Transaction flow.

    Controlling the lifecycle of the service using the Instance Contexts, Sessions and Transaction.

    Programming Host factories.

    Programming Behavior extensions.

    Use of Message object, extracting the body and header from it and Message object’s state cycle.

    Imperative configuration of service without a config file.

    Serialization of contracts (mainly the way they are serialized, i.e, nodes, attributes and node text).

    Various modes of consuming a service.


    Of course, there a lot more to study during the preparation. But this paper can serve as a checklist before heading to the examination hall.