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.

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 :D

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.

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 ;)

– 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:publicstaticclass Utility

4: {

5:publicstatic List<string>

6: Filter(thisstring[] names,

7: Func<string, bool> customFilter)

8: {

9: List<string> NamesList = new List<string>();

10:

11:foreach (string name in names)

12: {

13:if (customFilter(name))

14: NamesList.Add(name);

15: }

16:

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:publicstatic List<string>

2: Filter(thisstring[] 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:publicpartialclass MyPartialClass

2: {

3:partialvoid MyPartialMethod();

4:

5:publicvoid NotPartial()

6: {

7: Console.WriteLine("Ooops..Not Partial!");

8: }

9:

10:publicvoid 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:partialclass MyPartialClass

2: {

3:partialvoid 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.

We are going to create a sample application which is going to filter names that contains a character. It’s a very basic and simple example, but it’s really good to explain the things that we want to explore. We would be seeing on how we approach the same concept using Named Methods and Anonymous Methods and then come to Lambda Expressions.

We have a small class called Utility which looks like this,

It has got two static methods and a delegate called CustomFilter with an input parameter as string and bool as return type. So, the idea is to allow the developer or user to write their own custom filter function, but use this Utility to filter. This is done with the help of delegates.

Using Named Methods

So, if we take our Named Method approach, we would end up doing like this,

static void UsingNamedMethods()

{

List<string> FilteredNames =

Utility.FilterNames(names, MyFilter);

foreach (string name in FilteredNames)

Console.WriteLine(name);

}

static bool MyFilter(string name)

{

if (name.Contains(‘c’))

return true;

return false;

}

We have a method called MyFilter which is where we define our custom filter logic and instantiate the delegate CustomFilter with this method using the Utility.FilterNames function

And here is our Utility.FilterNames function

public delegate bool CustomFilter(string name);

public static List<string>

FilterNames(string[] names,CustomFilter customFilter)

{

List<string> NamesList = new List<string>();

foreach(string name in names)

{

if (customFilter(name))

NamesList.Add(name);

}

return NamesList;

}

It’s fairly simple and straight forward. Now we really have something useful which makes use of Named Methods. This sample will help the Customer who is going to use our Utility to write his own Filter and use the generic FilterNames function to filter it.

Look into our filter method which is Myfilter – It’s fairly simple, just checking whether the name contains a character and returns true if so. Do we really need to write a method for this? Why can’t we specify a code block instead and make use of it? Anonymous Methods comes to our rescue!

Anonymous Methods

Anonymous methods can be used to pass a code block to a delegate, using the delegate parameter, and can be used in places where creating a method is really not necessary, like in our example.

Using the Anonymous method, our code changes to,

static void UsingAnonymousMethods()

{

List<string> FilteredNames;

FilteredNames =

Utility.FilterNames(names,

delegate(string name)

{

return (name.Contains(‘c’));

} );

foreach (string name in FilteredNames)

Console.WriteLine(name);

}

So, now we have a code block which checks for a character in the name and it is passed as our CustomFilter delegate

Note that our FilterNames Utility function remains unchanged.

However, Anonymous methods do have one drawback in regard to readability. It’s more verbose and the code block sometimes becomes really hard to read!

So, do we really have anything which is easy to read and also simple to use? – Yes, and Lambda Expressions comes to our rescue!

Revisiting Lambda Expressions

As I said earlier – Lambda Expression is an anonymous function that can contain an expression or statement or can also be used to create a delegate

The structure of a lambda expression looks like this,

(param1,param2..paramN)=>expression

Basically we have some input parameters delimited with comma on the left and a corresponding expression on the right

The simplest lambda expression is,

x=>x

This is nothing but assigning x to x

Moving forward, our sample’s expression to find a character in the name would now become,

n=>n.Contains(‘c’)

How is the type of ‘n’ inferred? Remember our delegate? Here it is again,

public delegate bool CustomFilter(string name);

If you translate in pure English – Here is a delegate called CustomFilter which accepts one input parameter of type string and returns a value of type bool

So, when we actually make use of lambda expressions, this gets inferred and thus our ‘n’ in the above lambda expression gets inferred that it is of type string and has to return bool. But when inferring types is not possible, you could always do,

(string n)=>n.Contains(‘c’)

This would explicitly specify the type of ‘n’

Coming back to our sample application, now with the use of lambda expressions, we could write,

static void UsingLambdaExpressions()

{

List<string> FilteredNames;

FilteredNames = Utility.FilterNames(names, n => n.Contains(‘c’));

foreach (string name in FilteredNames)

Console.WriteLine(name);

}

Note that our FilterNames Utility function still remains unchanged.

Statement Lambdas

Again, revisiting our lambda expression definition – Lambda Expression is an anonymous function that can contain an expression or statement or can also be used to create a delegate

We did see that lambda expression that has an expression. What about a statement?

Statement lambdas look like,

(param1,param2..paramN)=>{ statement; }

The statement body can contain many statements instead of a single expression. Something like,

FilteredNames =

Utility.FilterNames(

names,

n =>{

bool blnVal;

/*… something here …*/

blnVal = n.Contains(‘c’);

return blnVal;

} );

Lambdas with Func<T,TResult> delegates

Again, revisiting our lambda expression definition – Lambda Expression is an anonymous function that can contain an expression or statement or can also be used to create a delegate

We did see that lambda expression that has an expression, a statement. What about the last one which can be used to create a delegate?

With the Func<T,TResult> family of generic delegates, we can use lambda expressions to create a delegate and invoke it.

Before getting into an example, let us explore the Func<T,TResult> family. We currently have,

A Simple example would be,

Func<string, bool> SampleFunction = n =>n.Contains(‘c’);

SampleFunction(“Chirstchurch”);

The above code block looks fairly simple and actually we see that we can eliminate Named Methods and Anonymous Methods now and directly make use of lambda expressions!

Coming back to our example, we can now simplify our FilterNames Utility function to something like this,

public static List<string> FilterNamesUsingFuncDelegates

(string[] names,Func<string,bool> customFilter)

{

List<string> NamesList = new List<string>();

foreach (string name in names)

{

if (customFilter(name))

NamesList.Add(name);

}

return NamesList;

}

Yes, you are right; we no need to declare any delegate now and make use of the available function delegates as Predicates!

Predicates were introduced in .NET 2.0 and are defined as (from MSDN),

Represents the method that defines a set of criteria and determines whether the specified object meets those criteria

We have always had problems when we want to execute some operation that might take long time in a separate thread and at the same time updating UI components.

With BackgroundWorker class, we can simplify this process and makes it very simple for us to do asynchronous operations.

We initialize the BackgroundWorker and register for their events and run it asynchronously. So, when those events like WorkCompleted, ProgressChanged occurs, you are taken to your callback which is in the thread that started the BackgroundWorker.

BackgroundWorker LoginWorker = new BackgroundWorker();

LoginWorker.DoWork += new DoWorkEventHandler(worker_DoWork);

LoginWorker.RunWorkerCompleted +=new

RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);

LoginWorker.WorkerSupportsCancellation = true;

I have developed a small (very) basic Twitter client to demonstrate the BackgroundWorker class