Generating WCF Proxy using SvcUtil.exe

7 08 2008

Visual Studio 2008 has made our WCF life a lot easier with the ability to self-host the services and also allow debugging in our service.

What if we were pushed to a situation wherein we need to use the tool svcutil.exe to create our proxy for the client…hmm… 🙂

To do so, we need to have our service running. Once the service is up and running, we could generate the proxy by the following command (replace the tags correspondingly) :

   1: svcutil /t:code http://<service_url> 
   2:       /out:<file_name>.cs /config:<file_name>.config

Here is my example :

   1: C:\Users\Chaks\Documents\Visual Studio 2008\Projects\MyService\MyServiceHost>
   2: svcutil /t:code http://localhost:8731/Design_Time_Addresses/MyService/WcfService/ 
   3: /out:MyServiceProxy.cs /config:MyServiceProxy.config
   4: Microsoft (R) Service Model Metadata Tool
   5: [Microsoft (R) Windows (R) Communication Foundation, Version 3.0.4506.648]
   6: Copyright (c) Microsoft Corporation.  All rights reserved.
   8: Attempting to download metadata from 'http://localhost:8731/Design_Time_Addresse
   9: s/MyService/WcfService/' using WS-Metadata Exchange or DISCO.
  10: Generating files...
  11: C:\Users\Chaks\Documents\Visual Studio 2008\Projects\MyService\MyServiceHost\MyS
  12: erviceProxy.cs
  13: C:\Users\Chaks\Documents\Visual Studio 2008\Projects\MyService\MyServiceHost\MyS
  14: erviceProxy.config

Now we can add this .cs file to the Client project and copy the .config file contents to the Client’s app.config file and execute the client 8)

We can also instruct svcutil to generate the proxy in the preferred language we want :

   1: svcutil /t:code /language=VB 
   2:      http://localhost:8731/Design_Time_Addresses/MyService/WcfService/ 
   3:          /out:MyServiceProxy.vb /config:MyServiceProxy.config

But svcutil already identifies the language with the extension of our output file name 8)

ASP.NET Ajax CalendarExtender and Validation

1 08 2008

ASP.NET Ajax toolkit has a CalendarExtender control which is very cool as you can associate the CalendarExtender to a a TextBox and also to a Button/ImageButton so that you can popup the calendar.

Below is the code to get started with CalendarExtender:

    width="300pt" />
    Width="16" Height="16" 
    CausesValidation="False" />
    Format="dd/MM/yyyy" />

And here is the output:




Wait! What’s that grayed text in the textbox that says – Enter the Date of Birth (dd/mm/yyyy)

Certainly that’s not the part of CalendarExtender 🙂 , but part of ASP.NET Ajax Toolkit 8) . We can use the TextBoxWatermarkExtender which can display watermarked (grayed) texts on controls. Below is the code for our CalendarExtender :

   WatermarkText="Enter the Date of Birth (dd/mm/yyyy)" />

And below is the CSS style that’s used with this watermark extender :

    color: #C0C0C0;
    font-style: italic;

All looks good now and the user is happy the way Calendar pops up, choosing the date and also the fact that he can type in the date in the textbox in the desired format. Now comes the problem – Date Validation! – How are we going to validate the entered date? – I had to validate that the date entered is not more than today’s date.

There are two ways to do it :

1) Using Javascript (with our CalendarExtender)

2) Using RangeValidators for our textbox

Using Javascript:

The CalendarExtender has a property called OnClientDateSelectionChanged which can be set to a piece of javascript which can do the job for us. Below is the code:

    Format="dd/MM/yyyy" />

and below is the javascript:

<script type="text/javascript">
function checkDate(sender,args)
    var dt = new Date();        
    if(sender._selectedDate > dt)

Using RangeValidator:

Since we use a TextBox control to display our date once we choose from the calendar or to manually input the date, RangeValidators can be used to check whether the date is within a given range (minimum & maximum). Below is the code for RangeValidator :

    ErrorMessage="*Please enter proper date" 
    Type="Date" Display="Dynamic" />

And in your page load event we can set our maximum and minimum date values :

      = new DateTime(1600, 01, 01).ToString("dd/MM/yyyy");
     = DateTime.Now.ToString("dd/MM/yyyy");

With these two methods you can easily validate the date. And yes, using both would sometimes lead you to race conditions where choosing a date from the calendar might be an invalid date and the RangeValidators would immediately come to the focus.

Random Post : LINQ to XML

14 07 2008

Thought of refreshing my LINQ to XML skills and here is the outcome – another blog post today! 8)

Here is our sample XML file (never mind where it came from or why it is complex)

<?xml version="1.0" encoding="utf-8" ?>

I am going to query each element (as listed below) and display their values

  • Persons_Current_Name
  • Persons_Name_At_Birth, and
  • DateOfBirth

Our first step would be to load this XML file. We can make use of XDocument to load the whole XML file.

XDocument mainXMLDoc
         = XDocument.Load("Input.xml");

To start with, let us traverse all the nodes and display their values

//Traversing the whole XML
Console.WriteLine("XML Traverse");
foreach (XElement xelement in
    Console.WriteLine("{0} : {0}",
              xelement.Name, xelement.Value);

Looks simple, isn’t it 🙂

Next, let us get the value of Persons_Current_Name. I already have a class called Name, which is shown below:

public class Name
    public String Surname { get; set; }
    public String GivenName { get; set; }

How do we directly query Persons_Current_Name element? Below is the very straight forward (ugly) code 😀

//Persons Current Name
// The Ugly Way
XElement current_name =
Name persons_current_name = new Name
             Surname =
             GivenName =

Well, I really don’t like to code this way. Do we have any another option? Yes, we do! 8)

//Persons Current Name
// The Neat Way
Name persons_current_name =
    (from c in mainXMLDoc.Descendants()
     where c.Name == "Persons_Current_Name"
     select new Name
                 Surname =
                 GivenName =

The above code certainly looks better than our previous code 🙂

Similarly for DateOfBirth,

//Date of Birth
String[] strDob =
    (from c in mainXMLDoc.Descendants()
     where c.Name == "DateOfBirth"
     select c.Value).FirstOrDefault().Split('-');
DateTime dob = new DateTime(Convert.ToInt32(strDob[0]),

All looks good, but wait! What to do if I have my XML in string format ? How do I load it? Dont panic, you can use the same XDocument to load the XML in the string format 🙂

XDocument mainXMLDoc =

Team System Unit Test and Output Directories

14 07 2008

I always use NUnit to write my unit tests but now at Intergen I also use Microsoft Visual Studio Team System Unit Tests. Today I was stuck by a very basic problem and here it is.

I have a XML file in my project which is added to the output directory when compiled.

When I was running my unit tests against this, Visual Studio threw me this error saying that it couldn’t find the file!

(click to enlarge)

I was really surprised as my XML file is said to copy to output directory and the test fails saying that there is no such file. Checked my Test Solution’s output directory and found that there is indeed the Templates folder and the XML file.

So, whats the problem? Why is my test failing?

Well, the VSTE has a separate directory where it stores all its test results. The directory can be found in your root directory of your solution under the name TestResults. The TestResults also have various folders for each test run you do. If you refer back to the error image that is attached above, you could get the exact directory name. So, the VSTE did not copy the Templates directory to this ‘dynamic’ (for each test run there will be a directory created : correct me if am wrong here) directory. How do we do this then?

The answer is with the Local Test Run Config’s Deployment settings. You can find the local test run config in your solution browser.

Double click the file to open the properties dialog and go to the Deployment section.

Specifying a file or directory here would be included along with the test results 🙂

My test doesnt fail now 8)

Another way to do this (if its a single file : if you know how to add for a directory, please do leave your comment 🙂 ) is to specify along with your test method,

[TestMethod, DeploymentItem(@”Templates\BirthInputTemplate.xml”)]

public void Test_BuildInputXML()

Silverlight and WCF

31 05 2008

With the release of Silverlight 2 beta 1, now developers can use .Net to create Silverlight applications To be more precise, developers can use XAML and VB.NET or C# as the back-end code language. To know more about Silverlight and what tools you need to start developing Silverlight applications, visit my post here.

This post focuses on how to make your Silverlight applications interact with Windows Communication Foundation(WCF) services. Visual Studio 2008 introduced several new WCF features. We will create a small calculator service which is going to add two numbers and return the result to the user.

First, let us create a Silverlight Web Application project.


Visual Studio creates the necessary files needed for your solution. Let us straight away start with adding our WCF service. Visual Studio creates two projects, one being the actual Silverlight control project and the other being the web application project where the Silverlight control is hosted. So, we would be able to add a WCF service to our web application project and then reference the service in our Silverlight control project. Right click the web application project and add a WCF service to the project.


Name the service as CalculatorService. Visual Studio adds the necessary files such as the SVC and code-behind files and also the service configuration to the web.config file.


I have modified the service to hold only function as shown below:

public interface ICalculatorService
    int AddTwoNumbers(int num1,int num2);

And here is the implementation:

#region ICalculatorService Members

public int AddTwoNumbers(int num1, int num2)
    return (num1 + num2);


Nothing complex, just simple addition and return the result 😉

Now comes the most important thing, at least for this beta 1 release – Silverlight supports only basicHttpBinding and thus our WCF service can only use basicHttpBinding if we are to interact with a Silverlight client. Let us check our CalcultorService’s binding in the web.config file under the system.servicemodel section.


Yes, you are right. WCF by default uses wsHttpBinding and thus we need to change the binding to basicHttpBinding. Below is the modified version:


How do we use this service in our Silverlight application? Below is a screenshot of our Silverlight application.


The interface is pretty simple accepting two numbers from the user and when Add is clicked, our service’s AddTwoNumbers is invoked to get the result.

How do we reference our WCF service now? We do the same way as we do in normal WPF or WinForms applications 😀

Right click on the Reference and select Add Service Reference


We will be presented with a dialog box to add a service reference.


We can use the Discover option to discover any WCF services in our solution. As our CalculatorService is hosted in the same solution, the Discover would be able to find our service.


Let us give a name to our service reference – CalculatorServiceProxy 🙂

Once we add our service, we can see that the Silverlight project now has the necessary files to interact with our WCF service.


Now we are ready to add our code to the button Click event handler. Below is the code snippet.

private void Button_Click(object sender, RoutedEventArgs e)
    int num1 = Convert.ToInt32(TxtNum1.Text);
    int num2 = Convert.ToInt32(TxtNum2.Text);

    CalculatorServiceClient calculator_proxy =
        new CalculatorServiceClient();

    calculator_proxy.AddTwoNumbersCompleted +=
        new EventHandler<AddTwoNumbersCompletedEventArgs>

    calculator_proxy.AddTwoNumbersAsync(num1, num2);


void calculator_proxy_AddTwoNumbersCompleted(object sender,
    AddTwoNumbersCompletedEventArgs e)

You guessed it right – WCF reference adds the asynchronous operations to our Silverlight project and it does makes more sense to use asynchronous operations in a Silverlight environment as we cant block the browser and make the user wait.

Let us build and execute our project 🙂

And here is the screenshot:


That’s it! Now we have a Silverlight application interacting with a WCF service 😉

Wasn’t it easy 8)

The sample can be downloaded here:

C# 3.0 Language Enhancements for LINQ – Part 3 – Expression Trees

14 04 2008

We saw more about Lambda Expression in our Part 1 of this series .Wonder how those were compiled or how those expressions parsed?

To do so, we need to get into Expression Trees!

So what is an Expression Tree?

Expression trees are nothing but those which represent the query itself.

Let us take a simple example.

   1: Func<string, string> function = 
   2:              x => x.Contains("c");

· The compiler constructs a delegate which takes an input parameter of type string and returns a value of type string

But, how about this

   1: Expression<Func<string, string>> expression = 
   2:                             x => x.Contains("c");

· The compiler generates an Expression Tree which we can parse and do something with the data

(This post gives a small introduction to Expression Trees. Expression Trees itself is a big topic but this post will help us go through some of the basics with a simple example)

Say we have a class called Student which has only one property – Name

   1: public class Student
   2: {
   3:     private string name;
   5:     public string Name
   6:     {
   7:         get { return name; }
   8:         set { name = value; }
   9:     }
  10: }

And now we have a small function which is going to take an expression as its parameter and return the value for which the expression is queried for.

   1: public static string 
   2:          GetName(Expression<Func<Customer, bool>> predicate)

So, if we pass an expression,


We need to get back Chakkaradeep , as that’s what we queried. This isn’t a good example, but I would say its good to understand how Expressions are parsed J

Let me show you the function directly now,

   1: public static string GetName(Expression<Func<Student, bool>> predicate)
   2: {
   3:     BinaryExpression binaryExpr = (BinaryExpression)predicate.Body;
   5:     MemberExpression leftExpr = (MemberExpression)binaryExpr.Left;
   7:     string url = leftExpr.Member.Name;
   9:     if (binaryExpr.NodeType == ExpressionType.Equal)
  10:     {
  11:         url += "==";
  12:     }
  13:     else
  14:         throw new NotSupportedException("only = is supported");
  16:     ConstantExpression rightValue = (ConstantExpression)binaryExpr.Right;
  18:     url += rightValue.Value;
  20:     return url;
  21: }

That’s a bit confusing! Whats happening ?

Expression is being parsed 🙂

Yes, take our expression again,


Expressions always a Body property. In the above expression, we have a BinaryExpression


As you might have guessed by now, a BinaryExpression is something that has a binary operator

So lets take the Body and break it into two pieces


   1: BinaryExpression binaryExpr = 
   2:       (BinaryExpression)predicate.Body;

Now we have extracted our BinaryExpression body which has a Left property and Right property, as shown above in the diagram.

The Left property will hold n.Name

The Right Property will hold Chakkaradeep

And our Node Type or the Binary operator is == (Equality)

And that’s what we have done,

   1: string url = leftExpr.Member.Name;
   3: if (binaryExpr.NodeType == ExpressionType.Equal)
   4: {
   5:     url += "==";
   6: }
   7: else
   8:     throw new NotSupportedException("only = is supported");
  10: ConstantExpression rightValue = (ConstantExpression)binaryExpr.Left;
  12: url += rightValue.Value;

As now you have the values, you could do anything with them and parse them 🙂

But yes, it would be more complicated if we have multiple queries coming up, like,

n=>n.Name==”Chakkaradeep” && n.Name==”Chaks”

And our sample will not work for the above query as we havent dealt with it. I leave to the reader to explore more on how to recursively parse Expressions 🙂

What if we need to manually build Expressions?

You can 🙂

We just use the technique of how we parsed to build the expression manually.

First, we need to create a ParameterExpression of type Student and also tell that our paramter variable is x

   1: //construct the parameter which is x and it is of type Student
   2: ParameterExpression xParam = 
   3:   Expression.Parameter(typeof(Student), "x");

And now we need to build our BinaryExpression whose Left Property is a MemberExpression which has the Property Name and the Right Property a value

   1: //construct our MemberExpression whose
   2: //left property is x.Name, and
   3: //right property’s value "Chakkaradeep"
   4: Student student = new Student();
   5: student.Name = "Chakkaradeep";
   6: MemberExpression leftExpr = MemberExpression.Property(xParam, "Name");
   7: Expression rightExpr = Expression.Constant(student.Name);
   8: //construct our BinaryExpression which is x.Name=="Chakkaradeep"
   9: BinaryExpression myExpr = MemberExpression.Equal(leftExpr, rightExpr);

All good now to build our Expression. Remember, we haven’t yet built our Expression, but we do have the bits and pieces that we need to build our expression 


And now we build our Expression,

   1: //now build our Expression using the parameter and BinaryExpression
   2: //x=>x.Name=="Chakkaradeep"
   3: Expression<Func<Student, bool>> lambdaExpr =
   4:     Expression.Lambda<Func<Student, bool>>
   5:         (
   6:             myExpr,
   7:             new ParameterExpression[] { xParam }
   8:         );

There you go! We build it telling that we have a ParameterExpression of type Student and the parameter is x which is associated with the BinaryExpression

And now you can directly pass this lambdaExpr to our function


You can download the sample here

Useful Resources

1) Expression Trees

2) Expression Tree Visitor

3) System.Linq.Expressions Namespace

C# 3.0 Language Enhancements for LINQ – Part 2 – var Keyword, Extension Methods and Partial Methods

13 04 2008

The var Keyword

We come across this new keyword called var when we use LINQ, what does this var keyword do?

The var keyword is used to declare and initialize anonymous types

That’s really confusing! – What are these anonymous types?

To understand the var keyword, we need to understand what really anonymous types are, and to understand anonymous types we need to know about var keyword, lol! Both go hand in hand.

Let’s start with an example,

   1: var Student = new { Id = 1234, Name = "Chakkaradeep" };

Now we have an anonymous type which has the properties Id and Name declared and initialized using the var keyword. To illustrate what is happening here,


So we can come to a conclusion that the var keyword deduces the data type of an object with the initialization of that object.

Now you can do something like this,

   1: var query =
   2:       from name in names
   3:       select new
   4:       {
   5:             firstPart = name[0],
   6:             lastPart = name.Substring(1, (name.Length - 1))
   7:       };

And then used it this way,


But do not consider that var variable is loosely coupled and can change its type! Take an example,

   1: var FullName = "Chakkaradeep Chandran";
   2: FullName = 12;

When you compile the above code, it fails because the object FullName is initialized as a String and we are trying to assign an Integer value to it!

This brings up an important point – var variables must be initialized when they are being declared and that helps the var keyword to deduce its type

The introduction of anonymous types has also led to another change in the way objects and collections are initialized

Say, we have a Class Person

   1: public class Person
   2: {
   3:     public string Name;
   4:     public string Address;
   5:     public int Pincode;
   6: }

If you want to initialize an object of type Person and give default values to those properties, the normal way would be,

   1: Person person = new Person();
   2: person.Name = "Chakkaradeep";
   3: person.Address = "Dunedin";
   4: person.Pincode = 9016;

But now we could directly do this,

   1: Person person = new Person
   2: {
   3:     Name = "Chakkaradeep",
   4:     Address = "Dunedin",
   5:     Pincode = 9016
   6: };

That certainly looks easier and neat!

This doesn’t stop with only Classes; it’s even possible with Collections,

   1: List<string> persons = new List<string>
   2: {
   3:     "Wellington",
   4:     "Dunedin",
   5:     "Invercargill"
   6: };

Extension Methods

The best way to understand Extension Methods is from an example

Let’s take our previous post’s example of filtering names that contains a character. We did something like this,

   1: List<string> FilteredNames =
Utility.FilterNames(names, n => n.Contains('c'));

Wouldn’t it be really nice and useful to provide something like this?

   1: List<string> FilteredNames =
   2:       names.Filter(n => n.Contains('c'));

That’s what Extension Methods allows us to do!

What are we actually doing in our above code block?

– We have “added” a method called Filter to an existing type which is string[] (array of strings)

This has one advantage. It doesn’t require you modify anything in the type string[], we just extend it and add our method

So, how are these done?

Extension Methods are nothing but static methods in a static class that can be called by using instance method syntax

We need to do some changes to our Utilty class to make it ready for Extension Methods. We need to change the class to a static class and include a static method called Filter

   1: namespace LINQEnhancements
   2: {
   3:     public static class Utility
   4:     {
   5:         public static List<string>
   6:            Filter(this string[] names,
   7:                 Func<string, bool> customFilter)
   8:         {
   9:             List<string> NamesList = new List<string>();
  11:             foreach (string name in names)
  12:             {
  13:                 if (customFilter(name))
  14:                     NamesList.Add(name);
  15:             }
  17:             return NamesList;
  18:         }
  19:     }
  20: }

And now you can use the way we want it,

   1: List<string> FilteredNames;
   2: FilteredNames = names.Filter(n => n.Contains('c'));

The reason I have shown the Utility class along with namespace is that, if your extension methods are in a different namespace, you have to import that namespace to actually make use of those extension methods

   1: public static List<string>
   2:   Filter(this string[] names,
   3:       Func<string, bool> customFilter)

The above line is where our trick lies. We explicitly tell that Filter is a static method applied on a static variable of type string[] (array of strings)

Where are these used? Remember our Standard Query Operators in LINQ?

   1: IEnumerable<string> query = names
   2:                             .Where(n => n.Equals(matchName))
   3:                             .Select();

Yes, you got it right!

And all these Standard Query Operators are available to use by importing the namespace System.Linq

using System.Linq;

Partial Methods

A partial method has its signature defined in a partial type and its implementation defined in another part of the type. This sounds very similar to Partial Class. Yes, partial methods always reside inside partial classes so that they can be used in another part of the type.

Here is an example,

   1: public partial class MyPartialClass
   2: {
   3:     partial void MyPartialMethod();
   5:     public void NotPartial()
   6:     {
   7:         Console.WriteLine("Ooops..Not Partial!");
   8:     }
  10:     public void InvokePartialMethod()
  11:     {
  12:         MyPartialMethod();
  13:     }
  14: }

We have a partial class and a partial method called MyPartialMethod

Now, what happens if we do something like this?

   1: MyPartialClass partialClass = new MyPartialClass();
   2: partialClass.NotPartial();
   3: partialClass.InvokePartialMethod();

We do see that the method NotPartial gets invoked but nothing happens when we call the InvokePartialMethod

Now let us create another declaration for MyPartialClass and implement the partial method MyPartialMethod

   1: partial class MyPartialClass
   2: {
   3:     partial void MyPartialMethod()
   4:     {
   5:         Console.WriteLine("Hey, its a Partial Method!");
   6:     }
   7: }

And now do the same thing,

   1: MyPartialClass partialClass = new MyPartialClass();
   2: partialClass.NotPartial();
   3: partialClass.InvokePartialMethod();

We now see that our partial method too gets called as we have implemented it!

Well, there is lot of arguments going on in the community that why do we need Partial Methods when this can be achieved in many other ways. Partial methods are mostly used in design tools for use with auto-generated code. If you want to make use of those methods, you could write your own implementation and it’s going to be used, else the compiler just doesn’t execute them and moves on.

Partial Methods are heavily used by LINQ-to-SQL designer tools and that’s the reason I wanted to explain about them here.

There are some golden rules that we need to follow if we are writing partial methods,

· Partial method declarations must begin with the contextual keyword partial and the method must return void.

· Partial methods can have ref but not out parameters.

· Partial methods are implicitly private, and therefore they cannot be virtual.

· Partial methods cannot be extern, because the presence of the body determines whether they are defining or implementing.

· Partial methods can have static and unsafe modifiers.

· Partial methods can be generic. Constraints are put on the defining partial method declaration, and may optionally be repeated on the implementing one. Parameter and type parameter names do not have to be the same in the implementing declaration as in the defining one.

· You cannot make a delegate to a partial method.

Useful Resources

1) Standard Query Operators

2) LINQ-to-SQL