다음을 통해 공유


How to: Implement Offline Support for Out-of-Browser Applications

Microsoft Silverlight will reach end of support after October 2021. Learn more.

This topic demonstrates how to implement the following common scenarios for Silverlight out-of-browser applications:

  • Determining whether an application has been installed or is running outside the browser. This enables you to do things like display branding that is normally displayed by using HTML. The example in this topic uses this information to hide an install button or display a network status indicator.

  • Determining whether a network connection is available. This enables you to disable network-dependent functionality, or provide alternatives to network or browser-based resources. The example in this topic uses this information to update a network connectivity indicator and to show or hide an update button.

  • Determining whether application updates are available. If a connection is available, you can check for and download new versions of your application, and alert users to restart. The example in this topic provides a basic demonstration of this capability.

You can make arbitrary changes to the appearance and behavior for an application when it runs outside the browser. However, in most cases, you should change your application as little as possible. This ensures that users will not have to learn a new user interface. If your application uses network resources, however, you should always display the network connectivity status in your user interface.

In the example, the XAML specifies a user interface that displays a network status indicator, an install button, an update button, and several TextBlock controls. The text blocks are bound to the out-of-browser configuration settings, which are shown in the XML at the end of this topic. You can copy these settings into the Out-of-Browser Settings dialog box in Visual Studio. Alternately, you can enable out-of-browser support in Visual Studio and then copy the XML into your project's OutOfBrowserSettings.xml file. For more information, see How to: Configure an Application for Out-of-Browser Support.

The code-behind sets the DataContext used by the bindings, and handles the various events required to update the user interface.

When you run this sample, click the install button or use the right-click menu option to install. Note that the install button disappears after installation. You can right-click the out-of-browser application or the Web-based application to uninstall. However, the install button will reappear only if you uninstall from the Web-based application. This is because the out-of-browser application no longer has any connection to the Web-based version. If you uninstall from the out-of-browser application, the install button will not reappear until you refresh the Web page.

You can test the network connectivity indicator in the out-of-browser application by disconnecting and reconnecting from the network. Note that the update button disappears when the connection is unavailable.

To test the update button, you should include a Web application project in your Silverlight solution. After you install the application, modify and rebuild the solution in Visual Studio, and then click the install button to download the update.

NoteNote:

Silverlight for Windows Phone In Silverlight for Windows Phone, the desktop out-of-browser feature does not apply.

Run this sample

Example

<UserControl x:Class="OutOfBrowser.MainPage"
  xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation" 
  xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml">
  <StackPanel x:Name="LayoutRoot" Background="White" Margin="20">

    <TextBlock x:Name="networkIndicator" FontWeight="Bold" FontSize="20"/>

    <Button x:Name="installButton" Content="install" 
      HorizontalAlignment="Left" Margin="0,10" Padding="10,5" 
      Click="installButton_Click"/>
    <Button x:Name="updateButton" Content="check for update"
      HorizontalAlignment="Left" Margin="0,10" Padding="10,5"  
      Click="updateButton_Click"/>

    <StackPanel Orientation="Horizontal">
      <TextBlock Text="ShortName = " FontWeight="Bold"/>
      <TextBlock Text="{Binding ShortName}"/>
    </StackPanel>

    <StackPanel Orientation="Horizontal">
      <TextBlock Text="Blurb = " FontWeight="Bold"/>
      <TextBlock Text="{Binding Blurb}"/>
    </StackPanel>

    <StackPanel Orientation="Horizontal">
      <TextBlock Text="WindowSettings.Title = " FontWeight="Bold"/>
      <TextBlock Text="{Binding WindowSettings.Title}"/>
    </StackPanel>

    <StackPanel Orientation="Horizontal">
      <TextBlock Text="WindowSettings.Height = " FontWeight="Bold"/>
      <TextBlock Text="{Binding WindowSettings.Height}"/>
    </StackPanel>

    <StackPanel Orientation="Horizontal">
      <TextBlock Text="WindowSettings.Width = " FontWeight="Bold"/>
      <TextBlock Text="{Binding WindowSettings.Width}"/>
    </StackPanel>

    <StackPanel Orientation="Horizontal">
        <TextBlock Text="IsRunningOutOfBrowser = " FontWeight="Bold"/>
        <TextBlock x:Name="isRunningOutOfBrowserTextBlock"/>
    </StackPanel>

    <StackPanel Orientation="Horizontal">
        <TextBlock Text="InstallState = " FontWeight="Bold"/>
        <TextBlock x:Name="installStateTextBlock"/>
    </StackPanel>

  </StackPanel>
</UserControl>
Imports System
Imports System.Net.NetworkInformation
Imports System.Windows
Imports System.Windows.Controls

Partial Public Class MainPage
    Inherits UserControl

    Private WithEvents app As Application = Application.Current

    Public Sub New()

        InitializeComponent()
        LayoutRoot.DataContext = Deployment.Current.OutOfBrowserSettings
        UpdateUI()

        AddHandler NetworkChange.NetworkAddressChanged, _
            AddressOf UpdateNetworkIndicator

    End Sub

    Private Sub App_InstallStateChanged(ByVal sender As Object, _
        ByVal e As EventArgs) Handles app.InstallStateChanged

        UpdateUI()

    End Sub

    Private Sub UpdateUI()

        UpdateNetworkIndicator()

        installButton.Visibility = If(
            app.InstallState = InstallState.NotInstalled,
            Visibility.Visible, Visibility.Collapsed)

        updateButton.Visibility = If(app.IsRunningOutOfBrowser,
            Visibility.Visible, Visibility.Collapsed)

        isRunningOutOfBrowserTextBlock.Text = _
            app.IsRunningOutOfBrowser.ToString()

        installStateTextBlock.Text = app.InstallState.ToString()

    End Sub

    Private Sub UpdateNetworkIndicator()

        If app.IsRunningOutOfBrowser Then
            networkIndicator.Visibility = Visibility.Visible
        Else
            networkIndicator.Visibility = Visibility.Collapsed
        End If



        Dim online As Boolean = NetworkInterface.GetIsNetworkAvailable()


        If online Then
            networkIndicator.Text = "ONLINE" 

            updateButton.Visibility = Visibility.Visible
        Else
            networkIndicator.Text = "OFFLINE"
            updateButton.Visibility = Visibility.Collapsed
        End If

    End Sub

    Private Sub installButton_Click(ByVal sender As Object, _
        ByVal e As RoutedEventArgs)

        Try
            app.Install()
        Catch ex As InvalidOperationException
            MessageBox.Show("The application is already installed.")
        End Try

    End Sub

    Private Sub updateButton_Click(ByVal sender As Object, _
        ByVal e As RoutedEventArgs)

        app.CheckAndDownloadUpdateAsync()

    End Sub

    Private Sub App_CheckAndDownloadUpdateCompleted(ByVal sender As Object, _
        ByVal e As CheckAndDownloadUpdateCompletedEventArgs) _
        Handles app.CheckAndDownloadUpdateCompleted

        If e.UpdateAvailable Then

            MessageBox.Show("An application update has been downloaded. " & _
                "Restart the application to run the new version.")

        ElseIf e.Error IsNot Nothing Then
            MessageBox.Show( _
                "An application update is available, but an error has occurred.\n" & _
                "This can happen, for example, when the update requires\n" & _
                "a new version of Silverlight or requires elevated trust.\n" & _
                "To install the update, visit the application home page.")
            LogErrorToServer(e.Error)
        Else
            MessageBox.Show("There is no update available.")
        End If

    End Sub

    Private Sub LogErrorToServer(ByRef ex As Exception)
        ' Not implemented. Logging the exact error to the server can help
        ' diagnose any problems that are not resolved by the user reinstalling
        ' the application from its home page. 
    End Sub

End Class
using System;
using System.Net.NetworkInformation;
using System.Windows;
using System.Windows.Controls;

namespace OutOfBrowser
{
    public partial class MainPage : UserControl
    {
        Application app = Application.Current;
        public MainPage()
        {
            InitializeComponent();
            LayoutRoot.DataContext = Deployment.Current.OutOfBrowserSettings;
            UpdateUI();
            app.CheckAndDownloadUpdateCompleted += 
                App_CheckAndDownloadUpdateCompleted;
            app.InstallStateChanged += (s,e) => UpdateUI();
            NetworkChange.NetworkAddressChanged += 
                (s, e) => UpdateNetworkIndicator();

            MessageBox.Show(Deployment.Current.OutOfBrowserSettings
                .WindowSettings.WindowStyle.ToString());
        }

        private void UpdateUI()
        {
            UpdateNetworkIndicator();

            installButton.Visibility =
                app.InstallState == InstallState.NotInstalled ?
                Visibility.Visible : Visibility.Collapsed;

            updateButton.Visibility =
                app.IsRunningOutOfBrowser ? 
                Visibility.Visible : Visibility.Collapsed;

            isRunningOutOfBrowserTextBlock.Text = 
                app.IsRunningOutOfBrowser.ToString();

            installStateTextBlock.Text = app.InstallState.ToString();
        }

        private void UpdateNetworkIndicator()
        {
            networkIndicator.Visibility =
                app.IsRunningOutOfBrowser ?
                Visibility.Visible : Visibility.Collapsed;

            bool online = NetworkInterface.GetIsNetworkAvailable();

            networkIndicator.Text = online ?
                "ONLINE" : "OFFLINE";

            updateButton.Visibility = online ?
                Visibility.Visible : Visibility.Collapsed;
        }

        private void installButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                app.Install();
            }
            catch (InvalidOperationException)
            {
                MessageBox.Show("The application is already installed.");
            }
        }

        private void updateButton_Click(object sender, RoutedEventArgs e)
        {
            app.CheckAndDownloadUpdateAsync();
        }

        private void App_CheckAndDownloadUpdateCompleted(object sender,
            CheckAndDownloadUpdateCompletedEventArgs e)
        {
            if (e.UpdateAvailable)
            {
                MessageBox.Show("An application update has been downloaded. " +
                    "Restart the application to run the new version.");
            }
            else if (e.Error != null)
            {
                MessageBox.Show(
                    "An application update is available, but an error has occurred.\n" +  
                    "This can happen, for example, when the update requires\n" + 
                    "a new version of Silverlight or requires elevated trust.\n" + 
                    "To install the update, visit the application home page.");
                LogErrorToServer(e.Error);
            }
            else
            {
                MessageBox.Show("There is no update available.");
            }
        }

        private void LogErrorToServer(Exception ex)
        {
            // Not implemented. Logging the exact error to the server can help
            // diagnose any problems that are not resolved by the user reinstalling
            // the application from its home page. 
        }

    }
}
<OutOfBrowserSettings ShortName="Out-of-Browser Demo" 
  EnableGPUAcceleration="False" ShowInstallMenuItem="True">
  <OutOfBrowserSettings.Blurb>
    This application demonstrates Silverlight's out-of-browser support.
  </OutOfBrowserSettings.Blurb>
  <OutOfBrowserSettings.WindowSettings>
    <WindowSettings Title="Silverlight Out-of-Browser Demonstration" 
      Height="250" Width="500" />
  </OutOfBrowserSettings.WindowSettings>
  <OutOfBrowserSettings.Icons />
</OutOfBrowserSettings>