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( );
      }
   }
}

About Jesse Liberty

Jesse Liberty has three decades of experience writing and delivering software projects and is the author of 2 dozen books and a couple dozen online courses. His latest book, Building APIs with .NET will be released early in 2025. Liberty is a Senior SW Engineer for CNH and he was 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 Microsoft MVP.
This entry was posted in Essentials, Mini-Tutorial, WindowsPhone and tagged , , . Bookmark the permalink.

3 Responses to Testing Network Availability

Comments are closed.