Detecting Network Status in Silverlight 3

I’m totally loving Silverlight 3, and wanted to dig into some of the new features that I learned about at MIX09 this past week.  I’ve already posted on the Silverlight 3 out-of-browser experience, and now I want to augment that with some information on network state detection. 

Silverlight applications run on the client – not on the server – but often require network resources.  With Silverlight 3 we can now detect when connectivity to the network has been lost or re-established with some simple events and properties.  This is important because our application might need to do something specific – say, store some information locally for future updates – and continue working with that local data until the connection is restored.  Luckily, working with these events and properties is totally easy – let’s take a look!

First, let’s build a simple UI for testing our connectivity.  I’ve created another Silverlight 3 application that has a simple Ellipse on it that we’ll fill in with green when the network is available, and red when the network is not (you can download the source for this application at the bottom of this post).  There is also a ListBox that we’ll use to display the events occurring within the system related to network status changes.

 

    1:  <UserControl x:Class="SL3NetworkStatus.MainPage"
    2:               xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    3:               xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml" 
    4:               Width="400" Height="300">
    5:      <Grid x:Name="LayoutRoot" Background="OldLace">
    6:          <Ellipse Width="50" Height="50"
    7:                   x:Name="StatusIcon"  
    8:                   Margin="0, 60, 300, 190"
    9:                   Stroke="Black" StrokeThickness="3"/>
   10:          <ListBox x:Name="AuditTrailListbox" 
   11:                   Margin="100 60 10 10"/>  
   12:          <TextBlock Text="Testing Network Status in SL3"
   13:                     FontSize="24"
   14:                     Margin="10 10 10 200"/>
   15:      </Grid>
   16:  </UserControl>

 

OK – now that the UI is done, let’s add some code to wire this thing up to the network status changes.

First, we need to add an event handler to our initialization routines to capture when the network gets disconnected.  That means we need to tap into the power of the NetworkChange.NetworkAddressChange event.  I’ve also wired up the Application.Current.ExecutionStateChanged event from the last post to also track when the app is disconnected from the browser and created my settings inside the AppManifest.xml file so that we can do some out-of-browser testing of this code as well.

 

    1:  Application.Current.ExecutionStateChanged +=
    2:      new EventHandler(Current_ExecutionStateChanged);
    3:  NetworkChange.NetworkAddressChanged +=
    4:      new NetworkAddressChangedEventHandler(NetworkChange_NetworkAddressChanged);
  

Inside the code for the NetworkAddressChanged event handler, we’ll make a check against the NetworkInterface class to see if we’re connected or disconnected from the local network:

 

    1:  private void ResetNetworkStatus()
    2:  {
    3:      if (NetworkInterface.GetIsNetworkAvailable())
    4:      {
    5:          StatusIcon.Fill = STATUS_GREEN;
    6:          Audit("Network: Online");
    7:      }
    8:      else
    9:      {
   10:          StatusIcon.Fill = STATUS_RED;
   11:          Audit("Network: Offline");
   12:      }
   13:  }

 

The NetworkInterface class has only one static method on it, and no instance methods.  Its only point in life seems to be around answering the question “GetNetworkIsAvailable” (which really isn’t a question, and I’m not sure why it’s not a property).  Anyway, we use this property method to determine whether or not the network is active or not.  Based on that, we set the Fill property of our Ellipse object to one of the two colors and send the appropriate audit message.

Running the application with the network enabled gives us the expected Silverlight application with a green circle:

image

When I disable my network connection, a curious thing happens:

image

Notice that the ellipse turns red as you’d expect, but I get 4 messages telling me that the application is currently running offline.  I spent a few minutes trying to track down exactly why the NetworkChange class decided that I needed to know about the disconnect 4 times, but wasn’t able to determine anything.  I’m hoping that future releases of this event handler will include a custom EventArgs object that gives us more information about what’s going on with the network.  So – for the time being, make sure that any code that runs inside this event handler in your code is idempotent.

I also checked this code running from a detached application (see previous post on how to run Silverlight 3 application out of the browser) and get exactly the same result.  In fact, when I run both an in-browser and out-of-browser version of this app at the same time, it responds exactly as I expect it would – both applications show exactly the same details.

Knowing whether or not you’re online or offline can be a real handy bit of information and be put to multiple uses.  For example – you can cache data locally using Isolated Storage while waiting for the network to reconnect.  Don’t forget that for out-of-browser experiences, you might also  need to check NetworkInterface.GetIsNetworkAvailable() when your application launches to see if your application is starting connected or disconnected, and handle interactions with the user accordingly.

I hope this post was valuable to you.  I’ve included the source code for the simple application that I wrote to play with these settings.  If you have any questions, please let me know.  If you’re not already subscribed to my blog, then subscribe already!  Lots more to talk about in future posts…

Technorati Tags: silvelright,silverlight3

Digg This