Powered by

US - English
NEW! Silverlight 5 is available Learn More

Advanced Silverlight Out of Browser- Introduction

By Microsoft Silverlight Team|December 1, 2010|Level 300 : Intermediate

Contents

Overview

Estimated Time 45 Minutes

Silverlight out-of-browser enables you to create desktop applications. Using elevated trust further opens the possibilities of what your application can do. This lab is designed to further explore what can be down with an out-of-browser Silverlight application.

In the lab you'll create an application that imports data directly from Excel. Along the way you'll learn how to interact with the hard drive, check for updates, and work with Excel from Silverlight.

You'll start by dragging and dropping Excel files onto the application. Next, you’ll call Excel through the AutomationFactory and process the data. You’ll create files and directories on the hard drive to store temporary data. Finally, you’ll learn how to check for application updates. The Silverlight application that you'll create is shown next:

You Will Benefit from this Lab if:

  • You are looking for a deeper understanding on how Silverlight interacts with the hard drive.
  • Want to integrate Silverlight and Excel
  • Looking for guidance on how to deploy updates to applications

You Will Learn:

  • How to work with the local file system from an Out-of-Browser Trusted application
  • Further explore how to use the AutomationFactory, by importing data from Excel into Silverlight
  • Check for updates to your application

Business Requirements for the Silverlight application include:

  • Drop files onto the application to be imported
  • Open a file from anywhere on the hard drive
  • Save a file to a temporary directory and file on the hard drive
  • Loop through an Excel to extract data
  • Enable the user to check for a new version of the application

Exercise 1: Enabling a drop zone

Watch Video

This first section shows how to enable a drop area where an Excel file will be dropped. The next section shows how to open the dropped Excel file and read its data.

Before getting started, copy and paste the four excel files found in the zip file in to your My Documents folder. Since Silverlight has limited file access you’ll need to put these files in a place where Silverlight can work with them. Later in this lab you’ll learn how to overcome this limitation by creating a temp directory and file from Silverlight.

  1. Open the starter solution, DesktopDashboard.sln, and then open DataWidget.xaml.cs or DataWidget.xaml.vb. This UserControl is where we’re going to handle both the drop off files and rendering of the Excel content. Last bit of set up, ensure the Silverlight project is set as the Startup project.
  2. To handle the dropping of files, the Drop event needs to be handled. Register the Drop event for the Panel called ImportPanel. Additionally set the AllowDrop property to True.

    C#

    public DataWidget()
    {
            // Required to initialize variables
            InitializeComponent();
    
            this.Data = new ObservableCollection<YearValueData>();
    
            this.ImportPanel.AllowDrop = true;
            this.ImportPanel.Drop += new DragEventHandler(ImportPanel_Drop);
    }
    

    Visual Basic

    Public Sub New()
            ' Required to initialize variables
            InitializeComponent()
    
            Me.Data = New ObservableCollection(Of YearValueData)()
            AddHandler ImportPanel.Drop, AddressOf ImportPanel_Drop
    End Sub
    
  3. The DropEventArgs contains file information for dropped files. Copy and paste the below event handler below the DataWidet constructor.

    C#

    void ImportPanel_Drop(object sender, DragEventArgs e) { if (e.Data != null) { FileInfo[] files = e.Data.GetData(DataFormats.FileDrop) as FileInfo[]; } }

    Visual Basic

    Private Sub ImportPanel_Drop(ByVal sender As Object, ByVal e As DragEventArgs)
            If e.Data IsNot Nothing Then
                    Dim files() As FileInfo = TryCast(e.Data.GetData(DataFormats.FileDrop), FileInfo())
            End If
    End Sub
    
  4. Run the project. Drag and drop the GasolinePrices.xls, from My Documents, onto the application (as seen in the below figure). Visually nothing will happen, however putting a breakpoint in the Drop event handler will show the files are coming back.

Exercise 2: Importing Excel data

As a developer it’s imperative to know how to work with tools that businesses rely on. Microsoft Excel is a tool frequently requested to have applications integrated with. With the out-of-browser feature in Silverlight, you’re able to call Excel methods, which include working with data contained inside.

In this exercise you’ll use the AutomationFactory to open an instance of Excel, open the first Worksheet, and loop through the content. The starter solution is already configured to make use of the AutomationFactory, however if you’re working on your own solution, you must first ensure the application has elevated trusted enabled. You can toggle this setting from the Out-of-browser settings in the Project’s Properties panel.

  1. Add the below code to the Drop event handler in DataWidget.xaml.cs or DataWidget.xaml.vb The code:
    1. a. gets a handle on the first file, files[0],
    2. b. opens Excel using AutomationFactory,
    3. c. loads the Excel document from MyDocuments (notice the use of Environment.SpecialFolder.MyDocuments),
    4. d. And loads the active sheet.

    C#

    // Get the first dropped file
    var fi = files[0];
    // Create the Excel object
    dynamic excel = AutomationFactory.CreateObject("Excel.Application");
    // Open the excel document. Must be located in "My Documents"
    dynamic excelWorkBook = excel.Workbooks.Open(string.Format("{0}\\{1}", 
            Environment.GetFolderPath(
            Environment.SpecialFolder.MyDocuments),fi.Name));
    // Read the Worksheet
    dynamic activeWorkSheet = excelWorkBook.ActiveSheet();
    

    Visual Basic

    Dim fi = files(0)
    Dim excel As Object
    Try
            ' Check to see if Excel is already running
            excel = AutomationFactory.GetObject("Excel.Application")
    Catch
            excel = AutomationFactory.CreateObject("Excel.Application")
    End Try
    ' Open the excel document
    Dim excelWorkBook As Object = excel.Workbooks.Open(String.Format("{0}\\{1}",
            Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), fi.Name))
    ' Read the Worksheet
    Dim activeWorkSheet As Object = excelWorkBook.ActiveSheet()
    
  2. At this point the active worksheet is open and you can access the data. Add the below code immediately following the above block to loop through content of the worksheet.

    C#

    // Cells to Read
    dynamic cell1, cell2;
    // Iterate through Cells
    for (int count = 3; count < 30; count++)
    {
            cell1 = activeWorkSheet.Cells[count, 1];
            cell2 = activeWorkSheet.Cells[count, 2];
    
            Data.Add(new YearValueData()
            {
                    Year = cell1.Value,
                    Value = cell2.Value
            });
    }
    

    Visual Basic

    ' Cells to Read
    Dim cell1, cell2 As Object
    ' Iterate through Cells
    For count As Integer = 3 To 29
            cell1 = activeWorkSheet.Cells(count, 1)
            cell2 = activeWorkSheet.Cells(count, 2)
            Data.Add(New YearValueData() With {.Year = cell1.Value, .Value = cell2.Value})
    Next count
    
  3. In the Excel sheet, at position A1 (as seen in Figure 2), is the name of the Worksheet. The following code gets that value (Cells[1,1]) and assigns the value to the Text property of Title TextBlock.

    C#

    // Title is a TextBlock in XAML, this sets the value
    Title.Text = activeWorkSheet.Cells[1, 1].Value;
    

    Visual Basic

    'Title is a TextBlock in XAML, this sets the value
    Title.Text = activeWorkSheet.Cells(1, 1).Value
    
  4. Add the below code to clean up the Excel object. This will close the Excel process and prevent any potential file locks

    C#

    // Close the workbook
    excelWorkBook.Close();
    // Close the Excel process
    excel.Quit();
    

    Visual Basic

    ' Close the workbook
    excelWorkBook.Close()
    ' Close the Excel process
    excel.Quit()
    
  5. Finally, now the data is loaded into the local variable Data, existing DataGrid and Chart’s ItemsSource can be set.

    C#

    // Populate the DataGrid
    ExcelDataGrid.ItemsSource = this.Data;
    // Create LineSeries
    LineSeries lineSeries = new LineSeries();
    lineSeries.ItemsSource = this.Data;
    lineSeries.IndependentValueBinding = new Binding("Year");
    lineSeries.DependentValueBinding = new Binding("Value");
    this.Chart.Series.Add(lineSeries);
    

    Visual Basic

    ' Populate the DataGrid
    ExcelDataGrid.ItemsSource = Me.Data
    ' Create LineSeries
    Dim lineSeries As New LineSeries()
            lineSeries.ItemsSource = Me.Data
            lineSeries.IndependentValueBinding = New Binding("Year")
            lineSeries.DependentValueBinding = New Binding("Value")
    Me.Chart.Series.Add(lineSeries)
    
  6. Putting this all together, here is what the ImportPanel’s Dropped event handler should look like.

    C#

    void ImportPanel_Drop(object sender, DragEventArgs e)
    {
            if (e.Data != null)
            {
                    FileInfo[] files = e.Data.GetData(DataFormats.FileDrop) as FileInfo[];
    
                    if (AutomationFactory.IsAvailable)
                    {
                    // Get the first file
                            var fi = files[0];
    
                    // Create the Excel object
                    dynamic excel = AutomationFactory.CreateObject("Excel.Application");
    
                    // Open the excel document. Must be located in "My Documents"
                    dynamic excelWorkBook = excel.Workbooks.Open(string.Format("{0}\\{1}",
                    Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),fi.Name));
    
                    // Read the Worksheet
                    dynamic activeWorkSheet = excelWorkBook.ActiveSheet();
    
                    // Cells to Read
                    dynamic cell1, cell2;
    
                    // Iterate through Cells
                    for (int count = 3; count < 30; count++)
                    {
                            cell1 = activeWorkSheet.Cells[count, 1];
                            cell2 = activeWorkSheet.Cells[count, 2];
    
                            Data.Add(new YearValueData()
                            {
                                    Year = cell1.Value,
                                    Value = cell2.Value
                            });
                    }
    
                    // Title is a TextBlock in XAML, this sets the value
                    Title.Text = activeWorkSheet.Cells[1, 1].Value;
    
                    // Close the workbook
                    excelWorkBook.Close();
    
                    // Close the Excel process
                    excel.Quit();
    
                    // Populate the DataGrid
                    ExcelDataGrid.ItemsSource = this.Data;
    
                    // Create LineSeries
                    LineSeries lineSeries = new LineSeries();
                    lineSeries.ItemsSource = this.Data;
                    lineSeries.IndependentValueBinding = new Binding("Year");
                    lineSeries.DependentValueBinding = new Binding("Value");
                    this.Chart.Series.Add(lineSeries);
                    }
            }
    }
    

    Visual Basic

    Private Sub ImportPanel_Drop(ByVal sender As Object, ByVal e As DragEventArgs)
            If e.Data IsNot Nothing Then
                    Dim files() As FileInfo = TryCast(e.Data.GetData(DataFormats.FileDrop), FileInfo())
                    Dim fi = files(0)
                    Dim excel As Object
                    Try
                    ' Check to see if Excel is already running
                            excel = AutomationFactory.GetObject("Excel.Application")
                    Catch
                            excel = AutomationFactory.CreateObject("Excel.Application")
                    End Try
    ' Open the excel document
            Dim excelWorkBook As Object = excel.Workbooks.Open(String.Format("{0}\\{1}", Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), fi.Name))
            ' Read the Worksheet
            Dim activeWorkSheet As Object = excelWorkBook.ActiveSheet()
            ' Cells to Read
            Dim cell1, cell2 As Object
            ' Iterate through Cells
                    For count As Integer = 3 To 29
                            cell1 = activeWorkSheet.Cells(count, 1)
                            cell2 = activeWorkSheet.Cells(count, 2)
                            Data.Add(New YearValueData() With {.Year = cell1.Value, .Value = cell2.Value})
                    Next count
                    'Title is a TextBlock in XAML, this sets the value
                    Title.Text = activeWorkSheet.Cells(1, 1).Value
                    ' Close the workbook
                    excelWorkBook.Close()
                    ' Close the Excel process
                    excel.Quit()
    
                    ' Populate the DataGrid
                    ExcelDataGrid.ItemsSource = Me.Data
                    ' Create LineSeries
                    Dim lineSeries As New LineSeries()
                    lineSeries.ItemsSource = Me.Data
                    lineSeries.IndependentValueBinding = New Binding("Year")
                    lineSeries.DependentValueBinding = New Binding("Value")
                    Me.Chart.Series.Add(lineSeries)
            End If
    End Sub
    

    Working with object via AutomationFactory, can be challenging. Unfortunately there is no intellisence helping out, so you must rely on documentation. Here are the coding documents that will help when working with Excel. Excel 2007 Developer Reference Excel 2010 Developer Reference

Exercise 3: Working with the hard drive

Watch Video

When running in a trusted environment, you can access only files in user folders, specifically the MyDocuments, MyMusic, MyPictures, and MyVideos folders. Although this makes sense from a security point of view, it’s limiting. You want to enable the user to drag their data from any location. As it stands right now, if you try to drop a file from a location other than stated above, Silverlight will throw a security error.

In this section we’re going to cover how to import an Excel file from anywhere on the hard drive, how to create and delete directories, and how to create and modify files. Before you begin it’s important to lay out exactly what needs to be done.

  • Read the bytes of the dropped file
  • Create a temporary directory in My Documents
  • Create a temporary file with the byte contents of the dropped file
  • Open the temporary file in Excel
  • Read the data
  • Finally delete both the temporary file and directory
  1. Create a new method, called CopyFileToTempDirectory. This method will copy the dropped file to into a temporary directory in My Documents.

    C#

    private bool CopyFileToTempDirectory(FileInfo fi, string tempDirectory, string fileName)
    {
            using (Stream stream = fi.OpenRead())
            {
                    try
                    {
                            byte[] buffer = new byte[Convert.ToInt32(stream.Length)];
                            stream.Read(buffer, 0, Convert.ToInt32(stream.Length));
                            stream.Close();
    
                            // Create a temporary directory in My Documents
                            Directory.CreateDirectory(tempDirectory);
    
                            // Write a new file to the temp directory
                            File.WriteAllBytes(string.Format("{0}\\{1}", tempDirectory, fileName), buffer);
    
                            return true;
                    }
                    catch (Exception e)
                    {
                            return false;
                    }
            }
    }
    

    Visual Basic

    Private Function CopyFileToTempDirectory(ByVal fi As FileInfo, ByVal tempDirectory As String, ByVal fileName As String) As Boolean
            Using stream_Renamed As Stream = fi.OpenRead()
                    Try
                            ' Copy file to My Documents. This ensures we can open it up in Excel
                            Dim buffer(Convert.ToInt32(stream_Renamed.Length) - 1) As Byte
                            stream_Renamed.Read(buffer, 0, Convert.ToInt32(stream_Renamed.Length))
                            stream_Renamed.Close()
                            ' Create a temporary directory in My Documents
                            Directory.CreateDirectory(tempDirectory)
                            ' Write a new file to the temp directory
                            File.WriteAllBytes(String.Format("{0}\{1}", tempDirectory, fileName), buffer)
                            Return True
                            Catch e As Exception
                                    Return False
                    End Try
            End Using
    End Function
    
  2. Back in the Drop event handler, call the newly created method, CopyFileToTempDirectory , and tell the Worksheet to open the temporary folder instead of the calling My Documents.

    C#

    void ImportPanel_Drop(object sender, DragEventArgs e)
    {
            // ...
        
            string myDocuments = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            string tempDirectory = string.Format("{0}\\temp", myDocuments);
            string tempFullPath = string.Format("{0}\\{1}", tempDirectory, fi.Name);
    
            // Copy the file to a temp directory in My Documents
            CopyFileToTempDirectory(fi, tempDirectory, fi.Name);
    
            // Create the Excel object
            dynamic excel = AutomationFactory.CreateObject("Excel.Application");
        
            dynamic excelWorkBook = excel.Workbooks.Open(tempFullPath); 
        
            // ...
    
    }
    

    Visual Basic

    Private Sub ImportPanel_Drop(ByVal sender As Object, ByVal e As DragEventArgs)
            '...
            Dim myDocuments As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
            Dim tempDirectory As String = String.Format("{0}\temp", myDocuments)
            Dim tempFullPath As String = String.Format("{0}\{1}", tempDirectory, fi.Name)
            ' Copy the file to a temp directory in My Documents
            CopyFileToTempDirectory(fi, tempDirectory, fi.Name)
            'Dim result = New ObservableCollection(Of YearValueData)()
            Dim excel As Object
            Try
            ' Check to see if Excel is already running
                    excel = AutomationFactory.GetObject("Excel.Application")
            Catch
                    excel = AutomationFactory.CreateObject("Excel.Application")
            End Try
    
            ' Open the excel document
                    Dim excelWorkBook As Object = excel.Workbooks.Open(tempFullPath)
            '...
    End Sub
    
  3. This screen shot shows the GasolinePrices.xls being dragged from C:\temp and the temporary directory created in My Document.
  4. Remove the temporary directory and file. Create a new method to delete both the temporary directory and temporary file.

    C#

    private void CleanUpFileSystem(string tempDirectory, string tempFullPath)
    {
            File.Delete(tempFullPath);
            // Remove temp directory
            Directory.Delete(tempDirectory + "\\", true);
    }
    

    Visual Basic

    Private Sub CleanUpFileSystem(ByVal tempDirectory As String, ByVal tempFullPath As String)
            File.Delete(tempFullPath)
            ' Remove temp directory
            Directory.Delete(tempDirectory & "\", True)
    End Sub
    
  5. Finally add the call to this method in the Drop event handler. CleanUpFileSystem(tempDirectory, tempFullPath); The final Drop event handler looks like this:

    C#

    void ImportPanel_Drop(object sender, DragEventArgs e)
    {
            if (e.Data != null)
            {
            FileInfo[] files = e.Data.GetData(DataFormats.FileDrop) as FileInfo[];
    
            if (AutomationFactory.IsAvailable)
            {
                    // Get the first file
                    var fi = files[0];
    
                    string myDocuments = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                    string tempDirectory = string.Format("{0}\\temp", myDocuments);
                    string tempFullPath = string.Format("{0}\\{1}", tempDirectory, fi.Name);
    
            // Copy the file to a temp directory in My Documents
            CopyFileToTempDirectory(fi, tempDirectory, fi.Name);
    
            // Create the Excel object
            dynamic excel = AutomationFactory.CreateObject("Excel.Application");
    
            // Open the excel document. Must be located in "My Documents"           
            dynamic excelWorkBook = excel.Workbooks.Open(tempFullPath); 
    
            // Read the Worksheet
            dynamic activeWorkSheet = excelWorkBook.ActiveSheet();
    
            // Cells to Read
            dynamic cell1, cell2;
    
            // Iterate through Cells
            for (int count = 3; count < 30; count++)
            {
                    cell1 = activeWorkSheet.Cells[count, 1];
                    cell2 = activeWorkSheet.Cells[count, 2];
    
                    Data.Add(new YearValueData(){
                    Year = cell1.Value,
                    Value = cell2.Value
                    });
            }
    
            // Title is a TextBlock in XAML, this sets the value
            Title.Text = activeWorkSheet.Cells[1, 1].Value;
    
            // Close the workbook
            excelWorkBook.Close();
    
            // Close the Excel process
            excel.Quit();
    
            CleanUpFileSystem(tempDirectory, tempFullPath);
    
            // Populate the DataGrid
            ExcelDataGrid.ItemsSource = this.Data;
    
            // Create LineSeries
            LineSeries lineSeries = new LineSeries();
            lineSeries.ItemsSource = this.Data;
            lineSeries.IndependentValueBinding = new Binding("Year");
            lineSeries.DependentValueBinding = new Binding("Value");
            this.Chart.Series.Add(lineSeries);
    
            // Hide the ImportPanel
            this.ImportPanel.Visibility = Visibility.Collapsed;
            }
            }
    }
    

    Visual Basic

    Private Sub ImportPanel_Drop(ByVal sender As Object, ByVal e As DragEventArgs)
            If e.Data IsNot Nothing Then
                    Dim files() As FileInfo = TryCast(e.Data.GetData(DataFormats.FileDrop), FileInfo())
            If files.Length > 0 Then
                    If AutomationFactory.IsAvailable Then
                            Dim fi = files(0)
                                    If fi.Name.ToLower().Contains(".xls") OrElse fi.Name.ToLower().Contains(".xlsx") Then
                                            VisualStateManager.GoToState(Me, "Loading", True)
                                            Dim myDocuments As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
                                            Dim tempDirectory As String = String.Format("{0}\temp", myDocuments)
                                            Dim tempFullPath As String = String.Format("{0}\{1}", tempDirectory, fi.Name)
                                            ' Copy the file to a temp directory in My Documents
                                            CopyFileToTempDirectory(fi, tempDirectory, fi.Name)
                                            'Dim result = New ObservableCollection(Of YearValueData)()
                                            Dim excel As Object
                                            Try
                                            ' Check to see if Excel is already running
                                            excel = AutomationFactory.GetObject("Excel.Application")
                                            Catch
                                                    excel = AutomationFactory.CreateObject("Excel.Application")
                                            End Try
    
                                            ' Open the excel document
                                            Dim excelWorkBook As Object = excel.Workbooks.Open(tempFullPath)
                                            ' Read the Worksheet
                                            Dim activeWorkSheet As Object = excelWorkBook.ActiveSheet()
                                            ' Cells to Read
                                            Dim cell1, cell2 As Object
                                            Title.Text = activeWorkSheet.Cells(1, 1).Value
                                            ' Iterate through Cells
    
                                            For count As Integer = 3 To 29
                                                    cell1 = activeWorkSheet.Cells(count, 1)
                                                    cell2 = activeWorkSheet.Cells(count, 2)
                                                    Me.Data.Add(New YearValueData() With {.Year = cell1.Value, .Value = cell2.Value})
                                            Next count
    
                                            ' Close the workbook
                                            excelWorkBook.Close()
                                            ' Close the Excel process
                                            excel.Quit()
                                            ' Clean up temp file
                                            CleanUpFileSystem(tempDirectory, tempFullPath)
                                            ' Populate the DataGrid
                                            ExcelDataGrid.ItemsSource = Me.Data
                                            ' Create LineSeries
                                            Dim lineSeries As New LineSeries()
                                            lineSeries.ItemsSource = Me.Data
                                            lineSeries.IndependentValueBinding = New Binding("Year")
                                            lineSeries.DependentValueBinding = New Binding("Value")
                                            Me.Chart.Series.Add(lineSeries)
                                            VisualStateManager.GoToState(Me, "DetailsState", True)
                                    Else
                                    ' Display  error: "Hey this isn't an Excel file, please select valid excel file"
                                    End If
                            End If
                    End If
            End If
    End Sub
    

Exercise 4: Checking for updates

At this point you’ve learned how to read Excel data, open files from anywhere in the hard drive, and work with the hard drive. Moving away working with data, a situation that needs consideration is how do you check for updates in an out-of-browser scenario. This exercise covers how to check if there are updates.

  1. In the starter solution is a button labeled “Check for update”, as seen in the below figure. This is located in MainPage.xaml.
  2. Open MainPage.xaml.cs and add a Click event handler for the CheckForUpdatesButton and for the Application’s CheckAndDownloadUpdateCompleted (this even gets fired after checking if there are updates).

    C#

    public MainPage()
    {
            InitializeComponent();
            this.CheckForUpdatesButton.Click += new RoutedEventHandler(CheckForUpdatesButton_Click);
    }
    

    Visual Basic

    Public Sub New()
            InitializeComponent()
            AddHandler CheckForUpdatesButton.Click, AddressOf CheckForUpdatesButton_Click
    End Sub
    
  3. Checking to see if there’s an update is fairly simple. In the CheckForUpdatesButton’s Click event call Application.Current.CheckAndDownloadUpdateAsync(). This method checks for and downloads an updated version of your application.

    C#

    void CheckForUpdatesButton_Click(object sender, RoutedEventArgs e)
    {
            Application.Current.CheckAndDownloadUpdateAsync();
            Application.Current.CheckAndDownloadUpdateCompleted += new CheckAndDownloadUpdateCompletedEventHandler(Current_CheckAndDownloadUpdateCompleted);
    }
    

    Visual Basic

    Private Sub CheckForUpdatesButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
            Application.Current.CheckAndDownloadUpdateAsync()
            AddHandler Application.Current.CheckAndDownloadUpdateCompleted, AddressOf Current_CheckAndDownloadUpdateCompleted
    
    End Sub
    
  4. After the application has finished checking if there was an update the CheckAndDownloadUpdateCompleted event is fired. Add the below event handler.

    C#

    void Current_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.");
            }
    }
    

    Visual Basic

    Private Sub Current_CheckAndDownloadUpdateCompleted(ByVal sender As Object, ByVal e As CheckAndDownloadUpdateCompletedEventArgs)
            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." & vbLf & "This can happen, for example, when the update 
                    requires" & vbLf & "a new version of Silverlight or requires         elevated trust." 
    & vbLf & "To install the update, visit the application home page.")
                              'LogErrorToServer(e.Error);
            Else
                    MessageBox.Show("There is no update available.")
            End If
    End Sub
    
  5. This Figure shows a message box that’s displayed if there is an update from the above CheckAndDownloadUpdateCompleted event.
  6. This Figure shows a message box that’s displayed if there is not an update from the above CheckAndDownloadUpdateCompleted event.

Summary

In this exercise you examined advanced features of Silverlight’s out-of-browser feature. You learned how to open an Excel file from anywhere on the hard drive by writing its content to a temporary directory. From there, Silverlight read the data from the worksheet and displayed it to a grid and chart. The application satisfied the following requirements:

  • Drop files onto the application to be imported
  • Open a file from anywhere on the hard drive
  • Save a file to a temporary directory and file on the hard drive
  • Loop through an Excel to extract data
  • Enable the user to check for a new version of the application

This lab provided the building blocks on how to out-of-browser in a business setting. By applying skills learned from previous labs, you should now be able to read in the data, create a WCF service, and send the imported data to be stored on the server.

Microsoft Silverlight Team

By Microsoft Silverlight Team, Silverlight is a powerful development platform for creating engaging, interactive user experiences for Web, desktop, and mobile applications when online or offline.

Comments (0)