Skip to content


Silverlight Masterclass – Discounts for NxtGenUG Members

Introduction

Shawn Wildermuth’s “Silverlight Tour” is coming to the UK, in the guise of the Silverlight Masterclass, and NxtGenUG members can receive £50 off the course price (in addition to the current “early bird” offer if you qualify for that).

The 3 day developer course looks quite comprehensive, starting with Silverlight, XAML and Blend basics on day one, working with data on day two, and finishing off with more advanced topics like MVVM, MEF and PRISM on day three. It’s great to see some patterns and practices coverage in a Silverlight course, especially given my recent experience trying to recruit Silverlight developers!

In addition to the discounts you can also win a free ticket to one of the courses by blogging about it yourself using the text from the “pitch” below. For more details on the competition take a look at Ian Blackburn’s blog entry.

The Pitch

The Silverlight Tour comes to the UK – and it’s called the Masterclass!

This 3 day hands-on training with both designer and developer tracks looks awesome and (uniquely) has two expert trainers per course.

Currently scheduled in London, Manchester, and the Midlands for June, all courses also come with the chance to win an xbox 360, and Silverlight Spy licences!

Early bird discount of £100 if you book in May, and if you are a member of #SLUGUK or #nxtgenug there are additional discounts to be had.

Full Details are here: http://silverlightmasterclass.net

In addition bbits are holding a raffle for a free ticket for the masterclass. To be eligible to win the ticket (worth £1095!) you MUST paste this text, including all links, into your blog and email Ian@bbits.co.uk with the url to the blog entry.  The draw will be made on June 1st and the winner informed by email and on http://silverlightmasterclass.net

Share:
  • Twitter
  • DotNetKicks
  • DotNetShoutout
  • Google Bookmarks
  • Digg
  • del.icio.us
  • Live
  • Technorati
  • StumbleUpon
  • email
  • Netvibes
  • Ping.fm
  • Print
  • Reddit

Technorati Tags: , , , , ,

Posted in .Net, Silverlight.

Tagged with , , , , , .


Optional Parameters in C#4, C#3 and VB.Net, With a Side Order of IL Quirks

Introduction

One of the features C# has gained in it’s latest V4 incarnation is the ability to work with optional parameters. Now VB.Net (and the underlying IL) has had this ability for sometime, but as it’s new to C# folks, and causing a little confusion; I’m going to attempt to explain how it works, when it works and the potential gotchas. I’ll also cover a strange inconsistency between the the VB and C# compilers when it comes to named parameters.

Warning: This post contains IL, but don’t let that put you off – you don’t actually need to understand it to get the point of the post!

So It’s C#4 Only, Right?

Sort of :-) Just to confuse things, optional parameters, from both a definition and consumption perspective, are really the concern of the compiler. As other posts have correctly pointed out, as long as you’re using Visual Studio 2010 you can define and consume optional parameters while targeting an older framework version:

public void DoThings(int intParameter = 22, string stringParameter = "Default")
{
    // Do things
}

// ...

DoThings(); // Uses the default values

This will work whether you’re in the same assembly, or consuming a library that already exposes methods with optional parameters.

You can also happily consume C# libraries containing optional parameters with VB.Net; even if the VB.Net project is still running under VS2008. The reason this works it that the IL that the new C# compiler is emitting is nothing new, and VB.Net has been able to define and consume optional parameters for some time. You can see the IL that is generated for the above method in the ILDASM output below (interesting parts highlighted in yellow):

OptionalParamsIL

The one thing you *cannot* do is consume optional parameters using C# in Visual Studio 2008; even if you’ve built the library in VS2010 and targeted the older framework. The C#3 compiler just doesn’t understand (or more to the point doesn’t care about) optional parameters. If you try and build the code above using Visual Studio 2008 you will get the following error:

OptionalParameters2008

Definitely something for library authors to consider – we’re not quite out of “overload hell” yet unfortunately.

Gotchas?

Now you may well think that when you consume an optional parameter, the compiler is emitting code that pulls the default value from the method information at runtime – but that isn’t the case. In a similar fashion to the way the compiler handles consuming consts, the default values are “baked into” the calling code. This is true whether the calling code is in the same assembly as the definition, or a separate assembly . The following ILDASM screenshot shows the IL generated for the DoThings() call above (interesting parts highlighted in yellow again):

CallingOptionalIL

Even if you don’t fully understand the IL you can clearly see the constant values in the code are “baked into” the TestStuff() method.

The issue this can cause is the same for exposing public consts – if you change the default values in a library, but don’t recompile the calling code, then the calling code will still call your method(s) with the old default values. This is definitely something you need to consider when designing APIs using optional parameters.

One potential way to “work around” this issue and avoid “locking yourself in” to a particular set of defaults would be to follow the following pattern:

public void DoThings(int? intParameter = null, string stringParameter = null)
{
    if (intParameter == null)
        intParameter = 22;

    if (stringParameter == null)
        stringParameter = "Default";

    // Do Stuff
}

In the code above we still get the benefits of having optional parameters; but because we use “marker” values for defaults (nulls in this case), and set the *real* defaults inside the method, we are free to change the real defaults at a later date. This technique does require more code, and doesn’t look quite as elegant as the previous example, but in my opinion the benefits outweigh the drawbacks, especially for public APIs.

A VB/C# Named Parameters Quirk

As I was pulling together the IL for this post I discovered a small “quirk” when comparing the IL output by the VB.Net compiler to the output of the C’# compiler when dealing with named parameters. If we call the DoThings() method above and specify just the stringParameter the IL produced by the VB.Net compiler looks as I would expect:

vb-named

The default value for the intParameter is pushed onto the stack, followed by our “Nondefault” string value and the method is called. The IL produced by the C# compiler is slightly different though, as shown by the highlighted sections below:

cs-named

In the C# version the “Nondefault” string is pushed onto the stack *first*, then pops it off into a local variable (stloc.3), the default value for intParameter is then pushed, followed by the contents of the local variable (ldloc.3).

Not a massive difference, and I’m sure there’s a good reason for it, but the C# version does look decidedly “odd” to me. I’m no expert in IL performance, but this may be conclusive proof that VB is faster than C# ;-) *

Update: Marc Gravell was kind enough to review this post for me and correctly pointed out that I should really be comparing IL for *optimised* builds, not debug builds (which have optimisation turned off). Marc has done this for himself and confirmed the stloc and ldloc are still present, so my point is still valid (*phew*)

* Note: This is a joke.. I got some abuse on Twitter for “VB bashing” recently, hopefully this will appease the VB heads! :-)

Share:
  • Twitter
  • DotNetKicks
  • DotNetShoutout
  • Google Bookmarks
  • Digg
  • del.icio.us
  • Live
  • Technorati
  • StumbleUpon
  • email
  • Netvibes
  • Ping.fm
  • Print
  • Reddit

Technorati Tags: , , , , , , , , ,

Posted in .Net, CSharp.

Tagged with , , , , , , , , , .


Locating Network Services on the iPhone/iPad with MonoTouch

Introduction

For one of the little iPhone projects I’m working I need to communicate with with a server on the local network. That all sounds very simple, but what I *really* want to be able to do is detect all instances of this service on the local network, and give the user the option of which one to connect to at runtime.

In WCF land we could leverage WCF Discovery, but in the world of MonoTouch, and even in .NET 3.5, we don’t have that luxury, so it’s time to roll our own service discovery!

Ping! Pong!

To build our service discovery system we will be dropping down to the socket level; but don’t worry! We’re only using sockets to discover the services – after that you are free to use your normal HttpClient to actually access them :-)

The basic idea is our client will send out a “ping” containing the IP and port to respond back on. Each server that picks up the ping will send a response back containing some metadata (in this instance a “service name” and a “service endpoint address”). The two classes we will use as “payload” are as follows:

[Serializable]
/// <summary>
/// Our initial ping "payload"
/// </summary>
public class ServiceClientInfo
{
    /// <summary>
    /// IP address of the client that sent the ping
    /// </summary>
    public string IPAddress { get; private set; }

    /// <summary>
    /// UDP port to send a response to
    /// </summary>
    public int Port { get; private set; }

    public ServiceClientInfo(string iPAddress, int port)
    {
        IPAddress = iPAddress;
        Port = port;
    }
}

[Serializable]
/// <summary>
/// Server response "payload" - could be anything
/// </summary>
public class ServiceInfo
{
    /// <summary>
    /// Standard port servers listen on
    /// </summary>
    public static readonly int UDPPort = 3512;

    /// <summary>
    /// Name of the service
    /// </summary>
    public string ServiceName { get; private set; }

    /// <summary>
    /// Endpoint address
    /// </summary>
    public string EndpointAddress { get; private set; }

    public ServiceInfo(string serviceName, string endpointAddress)
    {
        ServiceName = serviceName;
        EndpointAddress = endpointAddress;
    }
}

For our test app we will have a simple UITableView to display server responses, and a single button for sending our out ping. It looks a little something like this:

iPhoneServiceLocatorSS

We will also verify that we have a working WiFi connection before we do anything. We do this using Miguel’s MonoTouch “reachability” sample code.

Step 1 – Firing the Ping from the iPhone

First things first, we need to fire off the initial ping from our phone by sending a UDP broadcast containing our “payload”. UDP is ideal for our application as it gives us a lightweight, connectionless transmission model which allows us to send a single message to every machine on the network using a broadcast. UDP is considered an “unreliable” protocol (i.e. it has no guarantees of delivery), but for our purposes that isn’t a problem. For more information on TCP/UDP and broadcasting you can take a look at the wikipedia pages: TCP, UDP, Broadcasting.

From a .NET code point of view this is pretty straightforward. We create an IPv4 UDP Socket, a UDP broadcast IPEndPoint, set some options and then use our Socket to send a serialised version of our “payload” to the network.

In this instance we are using the BinaryFormatter to serialise our payload (using a generic helper class in Helpers.cs), but you could serialise using any mechanism you like.

The code for this is as follows:

/// <summary>
/// Send our our server ping
/// </summary>
private void SendServerPing ()
{
    // Create a socket udp ipv4 socket
    using (Socket sock = new Socket (AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) {
        // Create our endpoint using the IP broadcast address and our port
        IPEndPoint endPoint = new IPEndPoint (IPAddress.Broadcast, Discovery.Core.ServiceInfo.UDPPort);

        // Serialize our ping "payload"
        byte[] data = Discovery.Core.Helpers.SerializeObject<ServiceClientInfo> (new ServiceClientInfo (GetCurrentIPAddress ().ToString (), 8762));

        // Tell our socket to reuse the address so we can send and
        // receive on the same port.
        sock.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);

        // Tell the socket we want to broadcast - if we don't do this it
        // won't let us send.
        sock.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);

        // Send the ping and close the socket.
        sock.SendTo (data, endPoint);
        sock.Close ();
    }
}

Step 2 – Listening for Responses

Next up we need to listen for server responses. We actually start listening *before* we send the ping (to make sure we don’t miss anything), but it makes more sense to think of it as a second step.

There are two ways to listen to responses: synchronously, where we sit there and wait for a response to come back, or asynchronously, where we provide a callback method that will respond to data as it comes in. We obviously don’t want our UI to stop responding while we’re waiting, and we certainly don’t want the iPhone to kill our application for being unresponsive, so we will opt for the asynchronous model.

The steps for setting up a listener are, again, very simple. We first create an IPEndpoint, this time using the IP address and port we included in our initial ping, and create a UDPClient bound to it. Finally we call BeginReceive to tell the client we want to receive data asynchronously, providing our callback method, and start a timer to stop listening after 2 seconds. We pass in a simple “state” object to our callback, so it has access to our endpoint and client, but you could also store those as fields if you prefer.

While we are listening for responses we also disable our Ping button and re-enable it again, making sure to do so on the UI thread, once the timer has elapsed:

private void StartListeningForServerPingBacks ()
{
    // Disable our ping button
    PingButton.Enabled = false;

    // Listen on our IP addresses on our port
    // In a real scenario you'd probably want to make sure the port
    // was available and fallback to an alternative if not.
    var endPoint = new IPEndPoint (GetCurrentIPAddress(), 8762);

    // Make sure we don't grab exclusive "rights" to our address
    // so we can use the same port for send and receive.
    var udpClient = new UdpClient ();
    udpClient.Client.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
    udpClient.ExclusiveAddressUse = false;
    udpClient.Client.Bind (endPoint);

    // Setup our "state" object so the callback has access to the client and endpoint
    UdpState state = new UdpState (endPoint, udpClient);

    // Setup our async receive
    // Our callback will be called if and when data comes in
    udpClient.BeginReceive (new AsyncCallback (this.ReceiveServerPingCallback), state);

    // Setup a timeout timer.
    // When the timer elapses we enable our ping button again and
    // close our udpclient.
    var enableTimer = new Timer (2000);
    enableTimer.AutoReset = false;
    enableTimer.Elapsed += delegate(object sender, ElapsedEventArgs e) {
        InvokeOnMainThread (delegate { PingButton.Enabled = true; });
        udpClient.Close ();
    };
    enableTimer.Enabled = true;
}

Step 3 – The Callback

Our callback method is rather simple (are you seeing a trend? :-) ). We first grab the state object, call EndReceive to grab the data, deserialise it to our ServiceInfo object, add it to the UITableView, and then call BeginReceive again. That last part is the most important – every call to BeginReceive, which starts an asynchronous receive, must match a call to EndReceive, which ends the asynchronous receive. If we didn’t call BeginReceive at the end of our callback we would only ever get one server response – which obviously isn’t what we want!

As our timer may close the connection, and because we may get bad data sent to our listening port, we wrap the whole callback in a try/catch to make sure we don’t crash the app:

/// <summary>
/// Our callback that receives the pings back from the server(s)
/// </summary>
private void ReceiveServerPingCallback (IAsyncResult ar)
{
    try {
        // Grab the state object and split it up
        UdpState state = (UdpState)(ar.AsyncState);
        UdpClient client = state.client;
        IPEndPoint endPoint = state.endPoint;

        // Grab all the data we received
        Byte[] receiveBytes = client.EndReceive (ar, ref endPoint);

        // Deserialize it to our ServiceInfo object
        var data = Discovery.Core.Helpers.DeserializeObject<ServiceInfo> (receiveBytes);

        // Using the UI thread, update the server list
        InvokeOnMainThread (delegate { AddItemToList (String.Format ("Name: {0} Endpoint: {1}", data.ServiceName, data.EndpointAddress)); });

        // Start listening again
        client.BeginReceive (new AsyncCallback (this.ReceiveServerPingCallback), state);
    } catch (Exception) {
        // Just in case we have any network issues, or we've closed the socket, we catch everything.
        // Rather a horrible catch all than an app crash in this instance.
    }
}

The Code

And that’s that. The full application source is available below. The solution contains the iPhone app, a WinForms “server” that you can run multiple times on your Mac/PC, and a shared library with the common data types in.

I’ve successfully tested this code with 10 servers, spread across multiple machines, without any issues but if your app needs responses from a large amount of servers then your mileage may vary :-)

ServiceLocation.zip

Share:
  • Twitter
  • DotNetKicks
  • DotNetShoutout
  • Google Bookmarks
  • Digg
  • del.icio.us
  • Live
  • Technorati
  • StumbleUpon
  • email
  • Netvibes
  • Ping.fm
  • Print
  • Reddit

Technorati Tags: , , , ,

Posted in MonoTouch, Software, iPhone.

Tagged with , , , , .


Announcing: TinyMessenger

Introduction

Just a small post to announce I have added, and finally documented, TinyMessenger to the TinyIoC project.

Tiny What-Now?

TinyMessenger provides an event aggregator/messenger for loosely coupled communication. Some scenarios where this may prove useful :

  • Communication between Controllers/ViewModels.
  • Service classes raising “events”.
  • Removing responsibilities from classes that receive external events (such as the AppDelegate in an iPhone application).
  • Decoupling communication between classes.

TinyMessenger uses a Publish/Subscribe model and is orderless, so you can subscribe to a message even if there’s nobody publishing, and you can publish one even if nobody is subscribed. It is also loosely coupled in that the publisher and subscriber know nothing of each other, all they both care about is the message itself. Some of the key features are:

  • Simple and orderless Publish/Subscribe API.
  • Messages either need to implement a simple “marker” interface, or they can build on the “base” classes that are in the box (TinyMessageBase and GenericTinyMessage<TContent>.
  • Subscriptions can supply an optional filter – only message that “pass” the filter are delivered.
  • Subscriptions can supply an optional “proxy”. A proxy can be used for marshalling to the ui thread, logging or many other purposes.
  • Subscriptions use weak references by default, but strong references can be specified if required.

TinyMessenger is part of the TinyIoC project, but it can be used completely independently – for more information take a look at the TinyMessenger Wiki page on the main TinyIoC site.

Share:
  • Twitter
  • DotNetKicks
  • DotNetShoutout
  • Google Bookmarks
  • Digg
  • del.icio.us
  • Live
  • Technorati
  • StumbleUpon
  • email
  • Netvibes
  • Ping.fm
  • Print
  • Reddit

Technorati Tags: , , ,

Posted in .Net, CSharp, Software, TinyIoC, TinyMessenger.

Tagged with , , , .


Why is Add Reference Still Horribly Broken in VS2010?

Introduction

We all know Add Reference is horribly broken in VS2008. We’ve all clicked it and had our hearts sink as we realised it was time to make a brew, grab lunch or take a weekend mini-break before even attempting to use Visual Studio again. Now VS2010 is in Release Candidate it’s obviously been fixed.. hasn’t it?!

Not All Change Is For the Better

The main issue with the VS2008 Add Reference dialog was that it took an age to load, mostly due to it enumerating all of the assemblies available to populate the .NET tab. If all  you wanted to do was add a project or file reference you still had to wait for it to finish building the .NET tab. Not good. In an attempt to fix the problem Microsoft has made two major changes to the dialog for VS2010:

  • The dialog now defaults to the Projects tab.
  • The .NET tab is now multi-threaded i.e. it loads types in the background.

The first of the two fixes is an excellent idea. If you want to use the Projects, Browse or Recent tabs then you don’t even need to look at that snail-paced .NET tab.

The second of the two fixes is horrible. Truly horrible. I’d even go as far as to say that if you actually want to use the .NET tab to add a reference then it’s actually *more broken than Visual Studio 2008*. Yes, I did say that. And I’ll say it again:

“If you actually want to use the .NET tab to add a reference then it’s actually more broken than Visual Studio 2008.”

To illustrate the point, lets say we want to add MEF, which sits in System.ComponentModel.Composition to our application, we’d probably do something similar to the following:

  1. Click Add Reference.
  2. Marvel at how quickly Add Reference Loaded.
  3. Click the .NET tab.
  4. Watch the first few items start to load up.
  5. Type “Sys” to jump down to System in the list.
  6. Go to select System.ComponentModel.Compo..oh no.. it’s moved.
  7. Scroll down, go to select Sys.. nope.. it’s moved again.
  8. Scroll down a bit more, click on.. nope, gone again.
  9. Swear.
  10. Wait until the thing has fully finished loading and then select what we want.

So what we have there is the same delay as it would have taken with VS2008, but with the added “fun” of playing a game of “chase the reference down the listbox” in a vain attempt to save yourself a few seconds.

Could It Be Done Better?

Now I’m no User Experience expert, or an Interface Designer with a fancy job title, but couldn’t this be improved immeasurably with a simple filter box?

Perhaps I work in a strange way, but I never start searching for a reference using the mouse – I *always* type the first few letters to skip to roughly where I want to go. If we had a simple filter box at the top of the dialog then the “chase the reference” game would be massively reduced, and probably eliminated all together if you’d typed in enough of the namespace name:

AddReference

Now we could get super fancy and support CamelCaseSearching like the QuickNav dialog in CodeRush, but I’d be quite happy with a basic filter.

Maybe I’m just picky.

Share:
  • Twitter
  • DotNetKicks
  • DotNetShoutout
  • Google Bookmarks
  • Digg
  • del.icio.us
  • Live
  • Technorati
  • StumbleUpon
  • email
  • Netvibes
  • Ping.fm
  • Print
  • Reddit

Technorati Tags: , , ,

Posted in Rambling, Software, Visual Studio.

Tagged with , , , .