/Expression/ Silverlight Tutorial: Building a Network-Aware Desktop Application
02/09/2009 | Filed under Discover > Expression

Mike Taulty from Microsoft’s Developer and Platform Group explains how to create a simple newsfeed application that runs both in and outside of the browser and knows whether the network cable is plugged in or not
What You’ll Need
In order to work through these tutorials you will need to have installed the Silverlight Version 3 SDK (download here) and either a full version or the trial version of Expression Blend 3 (download here).
Tutorial
One of the exciting things about Silverlight 3 is its ability to let applications perform a lightweight local installation so that the user can run them “from the desktop” without seeing the usual browser chrome. A key advantage is that the application runs in the same security sandbox as it would when running in the browser so there is no additional risk to the user. Additionally, an application can detect whether the user is online or offline and so can take appropriate action around the use of network services when the user lacks connectivity.
In this tutorial we’ll put together a simple application that displays a newsfeed and runs both in and outside of the browser and is additionally aware of whether the network cable is plugged in or not.
1 – Create the Silverlight Project
In Expression Blend, use the File|New Project... menu option to raise the New Project Dialog;

Select to create a “Silverlight 3 Application + Website” and choose a suitable name and location for your project along with the implementation language ( Visual C# or Visual Basic ) and hit OK to create the project. Note that the remaining code in this tutorial assumes the Visual C# language.
2 – Create a Basic User Interface
Expression Blend will open to display the blank user interface of your project;

the white user interface area is a grid. Click in the shaded border to the left of the grid to create a new row approximately 20% from the bottom of the grid as below;

with the Grid divided into 2 rows, use the Assets panel to select a ListBox control and then draw a ListBox into the top row of the Grid. Red margins will provide a useful guide as you approach the bounds of the Grid row as below;

Use the Properties panel to give the ListBox a name lstNews as below;

Again, use the Assets panel to select a Button and then draw the Button into the bottom row of the Grid. Use the properties panel to change the Content of the Button to read “Get News...” as below and name the Button btnNews;

You should now have a very basic user interface looking something like;

3 – Write Code to Load Data
We’ll write some simple code that runs when the button is clicked in order to read a web-based RSS feed and populate our ListBox. You can use your own feed but one that I’ve chosen here is from the Guardian Newspaper’s website and resides at http://feeds.guardian.co.uk/theguardian/rss.
Ensure that the Button is selected in the user interface;


And then use the Properties panel to select the event handlers for the button;

Double click on the Click handler as below to launch the code editor inside of Expression Blend;

We’re ready to write a little code that reads an RSS feed from the Guardian website. In order to make this easier we will need to have access to some classes in an additional .NET assembly, System.ServiceModel.Syndication.dll. Within the Projects panel use the right mouse menu on the References folder to add a reference;

Use the file dialog to navigation to the equivalent of C:\Program Files\Microsoft SDKs\Silverlight\v3.0\Libraries\Client and select the System.ServiceModel.Syndication.dll.
At the top of the code file add these ‘using’ statements to make it easier to work with Framework classes;
using System.ComponentModel;using System.IO;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.ServiceModel.Syndication;
using System.Xml;
now, we will write a function that begins the asynchronous download of the RSS feed from the web in response to the Button click. Note that the skeleton of this function should already be present in the code file;
private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
{
lstNews.ItemsSource = null;
// Create an object to do the download of the feed for us.
WebClient webClient = new WebClient();
// Give it a callback to call when the operation is completed.
webClient.DownloadStringCompleted += OnDownloadCompleted;
// Ask it to do the download for us.
webClient.DownloadStringAsync(new Uri(
“http://feeds.guardian.co.uk/theguardian/rss”));
}
The code uses a class WebClient to perform an asynchronous download of the RSS feed. When the download is complete, we have another function called OnDownloadCompleted to add as below to complete the work;
void OnDownloadCompleted(object sender, DownloadStringCompletedEventArgs args){
// Did it seem to work?
if (args.Error == null)
{
// Parse the string result as an RSS Feed.
SyndicationFeed feed = SyndicationFeed.Load(XmlReader.Create(new
StringReader(args.Result)));
// Pull out the titles for our ListBox.
lstNews.ItemsSource =
from item in feed.Items select item.Title.Text;
}
}
we attempt to do the smallest amount of work possible in order to get a list of the titles of news items into the ListBox.
4 – Test the Code
Press the F5 key in Expression Blend – you should have a user interface that looks something like;

Use the right mouse menu over the user interface and notice that there is only one option displayed for “Silverlight” information.
5 – Making the Application Available to Install Locally
With the application working in the browser, we can focus on making it available to install on the desktop as well.
This requires a simple metadata change to add some XML information to a file already present in your project.
Use the Projects panel to open the AppManifest.xaml file within the Properties folder;

edit the AppManifest.xaml file to include the section indicated by the comment below;
<Deployment xmlns="http://schemas.microsoft.com/client/2007/deployment"xmlns:x=“http://schemas.microsoft.com/winfx/2006/xaml”>
<Deployment.Parts>
</Deployment.Parts>
<!-- Added this section -->
<Deployment.OutOfBrowserSettings>
<OutOfBrowserSettings
ShortName=“News Reader” >
<OutOfBrowserSettings.Blurb>News Reader Example</OutOfBrowserSettings.Blurb>
<OutOfBrowserSettings.WindowSettings>
<WindowSettings Title=“News Reader Example” />
</OutOfBrowserSettings.WindowSettings>
</OutOfBrowserSettings>
</Deployment.OutOfBrowserSettings>
</Deployment>
Note that this is a minimal configuration and more options around custom icons and window appearance can be set in this configuration file.
With that change in place, re-run the application by pressing F5 in Expression Blend. When displayed in the browser you should see a new menu option on the right mouse menu;

Choosing that menu option will install the application locally onto the machine with options;

Once installed, verify that you can run the application from the desktop;

And that it continues to function and call the web service for RSS data;

You can then remove the application by using the right mouse menu to uninstall;

6 – Adding Network Status Detection
At its simplest, detecting the status of the network in Silverlight 3 involves checking a simple property and, optionally, handling an event that fires when the status changes. We will update our code in order to enable/disable the “Get News” Button based upon whether the application has network connectivity or not.
Note that this kind of status change would usually be done with data-binding or behaviours in Silverlight but we will write explicit code here for brevity.
Revisit your code in the MainPage.xaml.cs file. Add this one line function which enables/disables the btnNews Button based on network status;
void EnableDisableButton(){
btnNews.IsEnabled = NetworkInterface.GetIsNetworkAvailable();
}
You now just need to ensure that this function is called when the application first runs and whenever the network status changes. Modify the constructor of your MainPage class to do this as below;
public MainPage(){
// Required to initialize variables
InitializeComponent();
EnableDisableButton();
NetworkChange.NetworkAddressChanged += (s,e) =>
{
EnableDisableButton();
};
}
With these changes in place, run the application in Expression Blend by hitting F5. When the application is running ( inside the browser or from the desktop ) test that the application correctly enables/disables the button as you toggle the state of your network by turning on/off wireless connections or disconnecting your network cable.
About the Author
Mike Taulty works for Microsoft’s Developer and Platform Group in the UK where he promotes and educates around the Microsoft platform and tools to the broad UK community of developers and architects. You can find Mike at http://mtaulty.com
Bookmark with:


