Tuesday, March 29, 2011

Out Of Browser (OOB) - Part II : Silverlight

This post is the Part II of Out of Browser (OOB). The part I can be found here

In part I, we saw what is OOB, what are the ways to take the application offline and how the application gets the update from the server. In this part we will see an example. The example is simple one, we create an application that will tell us whether it is running in browser or out of browser, whether it is connected to internet or not.

This example will demonstrate how to:

1.      Configure the Silverlight application to enable OOB feature.
2.      Detect Network changes.
a.       Detect network availability and save the data in IsolatedStorage if network is not available at the client side (i.e., if the application is running offline).
b.      Update the data when the network becomes available.
3.      Detect whether the application has been changed since its last OOB run.

Creating the Silverlight application
The steps involved in the implementation of multi-lingual UI in Silverlight are as follows:
1.    Open Visual Studio 2008. Go to File | New | Project. Type the name of the application and click OK.

2.      After clicking on Ok select the web application and click on Ok.


Configuring the Silverlight application to enable OOB feature
3.    Right click on the Silverlight project (“OOBOffline”) | Properties. Open the file “AppManifest.xml”, found in the Properties folder, and add the following code (this is to enable the OOB feature for this application):
<Deployment xmlns="http://schemas.microsoft.com/client/2007/deployment" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <Deployment.Parts></Deployment.Parts>

    <Deployment.ApplicationIdentity>
        <ApplicationIdentity Title="MyTasks - Task Management" 
            ShortName="MyTasks">
            <ApplicationIdentity.Blurb>
                This is the corporate task management application.
            </ApplicationIdentity.Blurb>
            <ApplicationIdentity.Icons>
                <Icon Size="16x16">Icons/task16.png</Icon>
                <Icon Size="32x32">Icons/task32.png</Icon>
                <Icon Size="48x48">Icons/task48.png</Icon>
                <Icon Size="128x128">Icons/task128.png</Icon>
            </ApplicationIdentity.Icons>
        </ApplicationIdentity>
    </Deployment.ApplicationIdentity>
</Deployment>

4.      Right click on the Silverlight project (“OOBOffline”) and create a new folder “Icons”. Add the icons (task16.png, task32.png, task48.png and task128.png) to this folder. These are the icons for the application. They are PNG images in different sizes (16x16, 32x32, 48x48 and 128x128), so that all scenarios are covered.
5.      Set the “Build action” to “Content” for each icon file from the properties tab.
6.      Add the following code to MainPage.xaml:
<UserControl x:Class="OutOfBrowser.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="LightBlue">
        <StackPanel Orientation="Vertical">
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="Instance Mode:" FontSize="24" />
                <TextBlock x:Name="InstanceMode" Foreground="Green" 
                    Text="mode" FontSize="24" />
            </StackPanel>
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="Connectivity:" FontSize="24" />
                <TextBlock x:Name="ConnectivityIndicator" 
                    Foreground="Green" Text="mode" FontSize="24" />
            </StackPanel>
            <Button x:Name="btnOffline" FontSize="24"
                    Content="Take Offline" Click=" btnOffline_Click" />
            <Button x:Name="btnSave" FontSize="24" 
                    Content="Save Data" Click="btnSave_Click" />
        </StackPanel>
    </Grid>
</UserControl>

7.      Next, in MainPage.xaml.cs, we need to enable the application to load and save data locally or remotely, depending on the state of the user's network connection. If the application is running with an active network connection, we load and save as we would normally. In the case where the application is running disconnected, there is an option, in order to give the users a seamless experience whether they're connected or not, is to use isolated storage to cache data. Caching data allows the application to load and save data using isolated storage when running disconnected. This option allows the user experience to remain seamless regardless of the connected or disconnected state of the application.
public partial class MainPage : UserControl
{
    public MainPage()
    {
        InitializeComponent();
        Loaded += new RoutedEventHandler(MainPage_Loaded);
        NetworkChange.NetworkAddressChanged += new NetworkAddressChangedEventHandler(NetworkChange_NetworkAddressChanged);
    }

    void MainPage_Loaded(object sender, RoutedEventArgs e)
    {
        if (App.Current.RunningOffline)
            InstanceMode.Text = "Out of Browser";
        else
            InstanceMode.Text = "In Browser";
    }

    void NetworkChange_NetworkAddressChanged(object sender,EventArgs e)
    {
        if (NetworkInterface.GetIsNetworkAvailable())
        {
            ConnectivityIndicator.Text = "Connected (online)";
            ConnectivityIndicator.Foreground = new SolidColorBrush(Colors.Green);

            // check for updates from IsolatedStorage
            // push updates via web services to keep in sync
        }
        else
        {
            ConnectivityIndicator.Text = "Disconnected (offline)";
            ConnectivityIndicator.Foreground = new SolidColorBrush(Colors.Red);

            // Save current data to IsolatedStorage for offline use
        }
    }

    private void btnOffline_Click(object sender, RoutedEventArgs e)
    {
        bool allowed = App.Current.Detach();
        if (allowed)
        {
            // do something here
        }
    }

    private void btnSave_Click(object sender, RoutedEventArgs e)
    {
        if (NetworkInterface.GetIsNetworkAvailable())
        {
            // save online using web service
        }
        else
        {
            // use IsolatedStorage because app is offline
        }
    }
}
8.      Now, on running the application in the browser, we can see the following context menu:



Note: If the application is not configured for offline use, the "Install onto this computer…" is disabled.

9.      On clicking the “Install…” option, the following dialog appears:






10.      We have the option to choose where to put shortcuts to the application. By clicking "OK", the Silverlight application is added as a standalone application.

11.      Once the application is installed, it can be removed. When the application is installed, the context menu changes to:




Clicking "Remove this application" and confirming removal uninstalls the application from wherever it is added, and also removes the shortcuts.

Detecting the Instance Mode of the application
You can check the instance mode of the application i.e. whether the application is running in OOB mode or inside the browser with the help of the following line of code:
if (App.Current.RunningOffline)

If the application is running in the OOB mode, it returns true; else false.


Detecting network changes
               OOB applications can run with or without an active network connection, so we need to check the state of the user's network connection before attempting to trigger any server-side action. We can do this by calling the NetworkInterface.GetIsNetworkAvailable() method. This is a check to perform before making any Web service calls, since they would fail without a valid network connection. In addition to the GetIsNetworkAvailable() method, we can also subscribe to the NetworkChange.NetworkAddressChanged event of the class. This event will fire every time there is a change in a network connection's status.
public Page()
{
    InitializeComponent();
    NetworkChange.NetworkAddressChanged += new NetworkAddressChangedEventHandler(NetworkChange_NetworkAddressChanged);
}

void NetworkChange_NetworkAddressChanged(object sender,EventArgs e)
{
    if (NetworkInterface.GetIsNetworkAvailable())
    {
        // do something here
    }
    else
    {
        // do something else here
    }
}
               The return type of this method is bool. If network is available it returns true, else false. So when the network is not available, we can store the data in IsolatedStorage and when the application detects that the network is available, we can push the updates to the server.

Output
This is the screenshot of the page in in-browser mode

This is the screenshot of the page in OOB mode


Hope this helps. Happy Coding ! ! !

Breaking Out of the Web Browser with Adobe AIR    Nokia N900 Unlocked Phone/Mobile Computer with 3.5-Inch Touchscreen, QWERTY, 5 MP Camera, Maemo Browser, 32 GB--U.S. Version with Full Warranty   Adobe Dreamweaver CS5    Mario & Luigi Bowser's Inside Story    Multi-Function Wireless Presenter w/Laser Pointer & Wireless Mouse (Style V820 - 1GB Flash Memory)

0 comments: