Using Silverlight 3 to Detect Network Changes

Posted by: Malcolm Sheridan , on 9/4/2009, in Category Silverlight 2, 3, 4 and 5
Views: 18910
Abstract: In part I of this article I’ll demonstrate how to use the networking features in Silverlight to detect network changes.
Using Silverlight 3 to Detect Network Changes
 
For business applications today, having a network connection is almost mandatory. In the past I have worked on applications that required data synchronization when the application was re-connected to the network. Silverlight 3 has some new features that will help you detect network changes and how to react to those changes. These features are wrapped up inside the NetworkChange and NetworkInterface classes. NetworkChange allows applications to receive notification when the Internet Protocol (IP) address of a network interface, also called a network card or adapter, changes. NetworkInterface provides availability information for a network interface. In part I of this article I’ll demonstrate how to use these classes to know when you’re application is online and offline. In part II I’ll showing you how to save data when your application is offline and synchronize the data back to a database when you’re online. Update: Part II of this article can be read over here Silverlight, Isolated Storage, RIA and Network Changes - Part II
To begin with open Visual Studio 2008 and choose File > New > Project > Silverlight > Silverlight Application. Open the MainPage.xaml file as we’ll be using this file only. In order to receive network change notifications, you need to subscribe to the NetworkAddressChanged event. This event passes two parameters to the delegate, but they’re not needed because the NetworkInterface has a method called GetIsNetworkAvailable which returns a Boolean value indicating network connectivity.
 
To get started add the following code to the MainPage constructor:
 
C#
 
public MainPage()
{
InitializeComponent();
      Loaded += new RoutedEventHandler(MainPage_Loaded);
}
 
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
GetNetworkStatus();
      NetworkChange.NetworkAddressChanged += new
           NetworkAddressChangedEventHandler(NetworkChange_NetworkAddressChanged);
} 
 
VB.NET
 
Public Sub New()
InitializeComponent()
       AddHandler Loaded, AddressOf MainPage_Loaded
End Sub
 
Private Sub MainPage_Loaded(ByVal sender As Object, ByVal e As RoutedEventArgs)
GetNetworkStatus()
       AddHandler NetworkChange.NetworkAddressChanged, AddressOf NetworkChange_NetworkAddressChanged
End Sub
 
In the code above I have created an event handler that will be raised each time the network status changes. I have also created a method, GetNetworkStatus that will be responsible for updating the UI with the current network status. Add the following code to complete the application:
 
C#
 
private bool Online { get; set; }
void NetworkChange_NetworkAddressChanged(object sender, EventArgs e)
{
GetNetworkStatus();
}
 
private void GetNetworkStatus()
{
Online = NetworkInterface.GetIsNetworkAvailable();
      txtNetwork.Text = Online ? "Online" : "Offline...";
SolidColorBrush scb = new SolidColorBrush(Online ? Colors.Yellow : Colors.Red);
      NetworkStatus.Background = scb;
}
 
VB.NET
 
Private privateOnline As Boolean
Private Property Online() As Boolean
      Get
            Return privateOnline
      End Get
      Set(ByVal value As Boolean)
            privateOnline = value
      End Set
End Property
Private Sub NetworkChange_NetworkAddressChanged(ByVal sender As Object, ByVal e As EventArgs)
GetNetworkStatus()
End Sub
 
Private Sub GetNetworkStatus()
Online = NetworkInterface.GetIsNetworkAvailable()
       txtNetwork.Text = If(Online, "Online", "Offline...")
Dim scb As New SolidColorBrush(If(Online, Colors.Yellow, Colors.Red))
       NetworkStatus.Background = scb
End Sub
 
The GetNetworkStatus method is called whenever the network changes. A call to NetworkInterface.GetIsNetworkAvailable indicates whether any network connection is available. If a network is available, the page will be updated to indicate this by display a yellow background with the word Online. If the network is not available, the background colour will be red with the word Offline. If you run the application, and you have a network connection as I do, you’ll see the result:

 

Online

 

However if you disconnect your computer from the network, you’ll see that the page automatically updates to the network change:
 
Offline
 
This is a nice feature and you should use it if you’re serious about business applications. In part II of this article I’ll show you how to save data when you’re offline and synchronize the data when you’re online. Update: Part II of this article can be read over here Silverlight, Isolated Storage, RIA and Network Changes - Part II

The entire source code of this article can be downloaded over here.

If you liked the article,  Subscribe to the RSS Feed or Subscribe Via Email

Malcolm Sheridan is an independent contractor who has been working with Microsoft technologies since VB4. Malcolm has worked with .NET since its inception and thoroughly enjoys ASP.NET.
 
Give a +1 to this article if you think it was well written. Thanks!
Recommended Articles
Malcolm Sheridan is a Microsoft awarded MVP in ASP.NET, a Telerik Insider and a regular presenter at conferences and user groups throughout Australia and New Zealand. Being an ASP.NET guy, his focus is on web technologies and has been for the past 10 years. He loves working with ASP.NET MVC these days and also loves getting his hands dirty with jQuery and JavaScript. He also writes technical articles on ASP.NET for SitePoint and other various websites. Follow him on twitter @malcolmsheridan


Page copy protected against web site content infringement by Copyscape


User Feedback
Comment posted by gauthamshetty86 on Wednesday, September 16, 2009 1:04 AM
Hello,
     dotNetCurryteam,


                 How can I get  encryption password to unzip  "network detection" source code. I have subscribe your News_letter.

       It will be help to me if I get the network password via above mentioned email.

                your's faithfully,
                Gautham.
Comment posted by Carol on Wednesday, September 16, 2009 3:39 AM
Gauthamshetty86 -- You need to confirm your subscription to get the password. Anyways the password has been mailed to you.
Comment posted by Peter Smith on Monday, November 9, 2009 6:14 PM
Take a look at this MIX video (T78M from the 2009 MIX) -- http://videos.visitmix.com/MIX09/T78M -- you can't rely just on the 'Connected' setting because lots of access points will lie.

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel