Testing Network Availability

Windows Phone From Scratch #42

 

We would like to live in a world in which any time you turn  your phone on the helloworld network is there, full strength.  We’d also like to live in a world of peace and harmony.

Until all of this is accomplished, however, you will need to test for network availability and handle those unfortunate moments when the network is not available.

To do so, you can call upon two useful features of the NetworkInformation namespace: the NetworkAddressChanged event and the GetIsNetworkAvailable method.

To see these at work, create a new application that will consist of a TextBox centered in the content panel. Here’s the Xaml,

<phone:PhoneApplicationPage
   x:Class="NetowrkAvailability.MainPage"
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
   xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
   xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
   xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
   mc:Ignorable="d"
   d:DesignWidth="480"
   d:DesignHeight="768"
   FontFamily="{StaticResource PhoneFontFamilyNormal}"
   FontSize="{StaticResource PhoneFontSizeNormal}"
   Foreground="{StaticResource PhoneForegroundBrush}"
   SupportedOrientations="Portrait"
   Orientation="Portrait"
   shell:SystemTray.IsVisible="True">

  <Grid
      x:Name="LayoutRoot"
      Background="Transparent">
      <Grid.RowDefinitions>
         <RowDefinition
            Height="Auto" />
         <RowDefinition
            Height="*" />
      </Grid.RowDefinitions>

      <StackPanel
         x:Name="TitlePanel"
         Grid.Row="0"
         Margin="12,17,0,28">
         <TextBlock
            x:Name="ApplicationTitle"
            Text="Network Availability"
            Style="{StaticResource PhoneTextNormalStyle}" />
         <TextBlock
            x:Name="PageTitle"
            Text="Hello, World?"
            Margin="9,-7,0,0"
            Style="{StaticResource PhoneTextTitle1Style}" />
      </StackPanel>

       <Grid
         x:Name="ContentPanel"
         Grid.Row="1"
         Margin="12,0,12,0">

         <TextBox
            Name="Message"
            Background="Yellow"
            Text="Unknown"
            VerticalAlignment="Center"
            HorizontalAlignment="Center" />

      </Grid>
   </Grid>
</phone:PhoneApplicationPage>

 

Our goal, of course, is to change the text and background color of the Textbox when the network status changes.  We’ve initialized it to yellow in case we can’t determine the status, but in the constructor we’ll immediately test whether or not we’re on line and set it accordingly.

We begin by setting up an event handler which will respond every time the network status changes,

public MainPage( )
{
   InitializeComponent( );
   NetworkChange.NetworkAddressChanged +=
      new NetworkAddressChangedEventHandler(
           NetworkChange_NetworkAddressChanged );

}

private void NetworkChange_NetworkAddressChanged(
    object sender, EventArgs e )
{
   CheckNetworkAvailability( );
}

We then create a method to check whether or not the network is available

 private void CheckNetworkAvailability( )
 {
    networkIsAvailable =
       Microsoft.Phone.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable( );
    SetNetworkIndication( );
 }

Finally, we set the background color and the message on the TextBox to correspond to the current state.

 private void SetNetworkIndication( )
 {
    if ( networkIsAvailable )
    {
       Message.Text = "Online";
       Message.Background =
          new SolidColorBrush( Colors.Green );
    }
    else
    {
       Message.Text = "Offline";
       Message.Background =
         new SolidColorBrush( Colors.Red );
    }
 }

 

Here is the complete source code, for context:

using System;
using System.Net.NetworkInformation;
using System.Windows.Media;
using Microsoft.Phone.Controls;

namespace NetowrkAvailability
{
   public partial class MainPage : PhoneApplicationPage
   {
      private bool networkIsAvailable;

      public MainPage( )
      {
         InitializeComponent( );
         NetworkChange.NetworkAddressChanged +=
            new NetworkAddressChangedEventHandler( NetworkChange_NetworkAddressChanged );
         CheckNetworkAvailability( );
      }

      private void NetworkChange_NetworkAddressChanged( object sender, EventArgs e )
      {
         CheckNetworkAvailability( );
      }

      private void SetNetworkIndication( )
      {
         if ( networkIsAvailable )
         {
            Message.Text = "Online";
            Message.Background = new SolidColorBrush( Colors.Green );
         }
         else
         {
            Message.Text = "Offline";
            Message.Background = new SolidColorBrush( Colors.Red );
         }
      }

      private void CheckNetworkAvailability( )
      {
         networkIsAvailable =
            Microsoft.Phone.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable( );
         SetNetworkIndication( );
      }
   }
}
Share

About Jesse Liberty

Jesse Liberty is an independent consultant and programmer with three decades of experience writing and delivering software projects. He is the author of 2 dozen books and multiple Pluralsight courses, and has been a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a Xamarin Certified Mobile Developer and a Xamarin MVP, Microsoft MVP and Telerik MVP.
This entry was posted in Essentials, Mini-Tutorial, WindowsPhone and tagged , , . Bookmark the permalink.

5 Responses to Testing Network Availability

  1. Pingback: Apadmi’s success is in the genes | Twiddle Geek

  2. Dina Berry says:

    How do you know, from this code, that the actual network address changed? Or is that an assumption that you never have the same address twice?

  3. Ben Isak says:

    Hi Jesse,

    in addition I would mention that one should use a seperate thread for checking the network-availability, because it`s not guaranteed how long the checking takes. In that time the UI is blocked.

    Regards,
    Ben

  4. Sri says:

    Hi Jesse,

    What are your thoughts on the eggPlant mobile solution from TestPlant . http://www.testplant.com/mobile.

    Thanks
    Sri

  5. Pingback: Windows Phone 7 – Testing Network Availability | www.nalli.net

Leave a Reply

Your email address will not be published.