One of the cool features of the full .NET Framework is that it easily allows applications to determine whether the network cable is detected or not so that they can try and make smart choices up-front as to whether to try a network operation.
In Silverlight 3, an application can do the same thing so I can write a UI like this one;
<UserControl x:Class="SilverlightApplication11.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300">
<Grid x:Name="LayoutRoot" Background="White">
<TextBlock
HorizontalAlignment="Center"
VerticalAlignment="Center"
FontSize="36"
x:Name="txtStatus"
Text="Not Set" />
</Grid>
</UserControl>
and then I can write a little bit of code which tries to spot changes in the network interface;
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using System.Net.NetworkInformation; namespace SilverlightApplication11 { public partial class MainPage : UserControl { public MainPage() { InitializeComponent(); this.Loaded += new RoutedEventHandler(MainPage_Loaded); } void MainPage_Loaded(object sender, RoutedEventArgs e) { NetworkStatusChanged(); NetworkChange.NetworkAddressChanged += OnNetworkStatusChanged; } private void NetworkStatusChanged() { txtStatus.Text = NetworkInterface.GetIsNetworkAvailable() ? "Network there" : "Network down"; } void OnNetworkStatusChanged(object sender, EventArgs e) { Dispatcher.BeginInvoke(() => { NetworkStatusChanged(); }); } } }
and then I’m in business in that as I plug/un-plug my network cable my Silverlight application is aware of what’s going on and the UI (in this example) changes accordingly.
Cool – very handy for those detached applications too as I talked about in my previous post.
You can download the code for this post from here.
This is one of a series of posts taking a quick look at Silverlight 3 – expect them to be a little “rough and ready” and that they’ll get expanded on as I’ve had more time to work with Silverlight 3.