Posted by: Mark Wilkinson | August 5, 2009

Embracing Lambda Expressions

I’ve put off using a lot (or really most of the features) in C# 3. Lambdas being one of them.

I originally started programming in .NET 2.0 and C# 2. Although the way I originally learned how to use delegates and invoke was from C# 1.

Dan Vanderbloom’s blog has the best example of this transition.

Here was my progression and the way I inovked a delegate to post back to a control on another thread.

First, we declare the delegate, then in a method you need to create an instance of the delegate, and invoke it:

untitled

You test if this.invokeRequired(), which will be yes if you’re on a different thread than what the control you’re invoking is on.

If this is the case you’ll go back into the function through the delegate method who’s target is the same method (a shortcut really, most have this outside the target method).

Not really all that complicated, but I had to make a target function and delegate for each type of input parameter.

Now with Lambdas, it’s this simple (to do the same as above):

You do need this function inside the same namespace of your class (not required within the class though).

untitled2

with this function you can now use this lambda expression:

invokeWithLambda

pretty Rad. ;)

Posted by: Mark Wilkinson | July 8, 2009

Dynamic Connection String to WCF Host

Another issue I came across was needing a way to dynamically connect to a WCF host without using the app.config file (which in all examples I see, they put the connection string in the app.config).

In code you can specify the endpoint address like so, with the “localhost:8008″ being the tcp address you want:

InstanceContext instanceContext = new InstanceContext(this);
client = new Service1Client(instanceContext);

client.Endpoint.Address = new EndpointAddress(“net.tcp://localhost:8008/Service1″);

Posted by: Mark Wilkinson | July 8, 2009

First post

Something I’ve come across using WCF.

A co-worker said he was getting exceptions when a network connection was dropped, and his proxy client state would drop (thus throwing an exception).

My solution that I’ve been using when trying to invoke any WCF client method is to do the following, thus preventing an exception from occuring:

if (client != null && client.State == CommunicationState.Opened)
{
    client.Method();
}
else
    this.ConnectToWCFHost();

If it’s null, try reconnecting and instantiating the client instance.  You might want to count the number of attempts to connect and then notify the system (through an event viewer for instance) that the connection cannot be established.

Categories