Visual Studio 2010!

Read now >

View Now
DevSource RSS FEEDS
XML Want an easy way to keep up with breaking tech news? And the Get DevSource headlines delivered to your desktop with RSS.
ADVERTISEMENT
ADVERTISEMENT

 

DevSource.com: Your Source for Visual Studio on Facebook
ADVERTISEMENT
VSTO's Data Caching Capabilities Extend Office Development
By Ty Anderson

Rate This Article: Add This Article To:

VSTO's Data Caching Capabilities Extend Office Development - ' Cache Data On The '
( Page 4 of 4 )

Server">

Cache Data on the Server and Send the Results to the Browser

The power of VSTO's data caching capabilities is best seen through code. This example shows how to access a data cache stored within Excel from an .ASPX web page.

This page inserts the same data as in the previous example, and the serves the file for viewing within the browser. For this example, you need to create another VSTO Excel project as well as a new Web Site project.

Build the SalesReport Workbook Project

First, let's create the VSTO project. Create another Excel Workbook project in Visual Studio and name it SalesReport. The SalesReport.xls file will contain a blank list object that will fill with data from an untyped data set.

To complete this VSTO project, perform the following steps:

  1. With the SalesReport.xls file open in Visual Studio, drag a ListObject control into cell A6. Click OK in the Add ListObject to Control dialog box. This step adds an unfilled list object containing a single column (Column1).
  2. Place the cursor within the list object created in Step 1 to display its properties in the property window. Change the list object's name to ReportList.
  3. Drag a NamedRange control to cell A2 and press OK when the Add NamedRange Control dialog displays.
  4. Select cell A2 to display the named range's properties. Change its name to asofDate. This named range will be filled report's creation date later.

All the code for this workbook resides behind Sheet1. Select Sheet1 in the Solution Explorer and select View > Code from the Visual Studio menu. Insert the following code into the Sheet1 class:

Imports System.Data

Public Class Sheet1
'//Declare variables that will be cached
  <Cached()> Public reportDate As String 'the report creation date
  <Cached()> Public salesData As DataSet 'the untyped data set 


  Private Sub Sheet1_Startup(ByVal sender As Object, ByVal e As System.EventArgs)
    Handles Me.Startup

   '//Set the ListObject's headers to auto update
   '//based on the field names of the inserted query/table
    Me.ReportList.AutoSetDataBoundColumnHeaders = True
    '//Set the list's data source to the cached dataset
    Me.ReportList.DataSource = Me.salesData
    '//Set the list to display the cached data's SalesReport table
    '//This will be added by the Web Page.
    Me.ReportList.DataMember = "SalesReport"

    '//Insert the report date (set by the Web Page) into the named range
    Globals.Sheet1.asofDate.Value2 = reportDate
  End Sub

  Private Sub Sheet1_Shutdown(ByVal sender As Object, ByVal e As System.EventArgs)
    Handles Me.Shutdown

  End Sub

End Class

The last step is to publish the workbook to the Web site used for this project. Doing so allows the assembly to execute from the web site's URL. Select Build > Publish from the Visual Studio menu and specify http://localhost/website as the URL.

Build the Web Site Project

Second, you need to build a Web site project that will fill the SalesReport.xls workbook with data and serve up the file in an http Response object.

Create a new Web site project in Visual Studio. Once created, add a reference to the Microsoft.VisualStudio.Tools.Applications.Runtime library. This library provides access to the VSTO ServerDocument class and provides the capability to manipulate the VSTO data cache.

Open the Default.aspx page in the View Designer. Add a Button control to the page and name it btnBuildReport. This is all that's required for the web page's design; all the page does is trigger the code that builds the sales report workbook.

Now select View > Code from the Visual Studio menu and insert the following code:

Imports System.Data
Imports Microsoft.Office.Interop.Excel
Imports System.IO
Imports Microsoft.VisualStudio.Tools.Applications.Runtime


Partial Class _Default
  Inherits System.Web.UI.Page

  Protected Sub btnBuildReport_Click(ByVal sender As Object, ByVal e As System.EventArgs)
    Handles btnBuildReport.Click

    '//setup connection to the Northwind database and open it
    Dim ds As New System.Data.DataSet
    Dim dt As System.Data.DataTable = ds.Tables.Add("SalesReport")
    Dim da As New OleDb.OleDbDataAdapter
    Dim cnn As New OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;
      Data Source= C:\Inetpub\website\Northwind.mdb; User Id=admin; Password=")

    da.SelectCommand = New OleDb.OleDbCommand("SELECT TOP 200 Employees.Country,
      Employees.LastName, Employees.FirstName, Orders.OrderDate, Orders.OrderID,
   [Order Subtotals].Subtotal AS SaleAmount FROM Employees 
   INNER JOIN (Orders INNER JOIN [Order Subtotals] 
   ON Orders.OrderID=[Order Subtotals].OrderID) 
   ON Employees.EmployeeID=Orders.EmployeeID;")
    da.SelectCommand.Connection = cnn
    da.Fill(dt)

    '//Set the location of the SalesReport.xls template
    Dim master As String = "C:\Inetpub\website\SalesReport.xls"
    
    '//Open the Sales Report Excel File (ExcelWorkbook01.xls)
    Dim wb As New FileStream(master, FileMode.Open, FileAccess.Read)
    Dim rdr As New BinaryReader(wb)
    Dim newFile(CInt(wb.Length)) As Byte
    newFile = rdr.ReadBytes(CInt(wb.Length))
    wb.Close()

    '//Open the XL Sales Report ServerDocument, 
    '//fill it with updated data and return it
    Dim sd As New ServerDocument(newFile, ".XLS")
    '//Set a reference to the data cache items contained in Sheet1
    Dim cdhi As CachedDataHostItem = sd.CachedData.HostItems("SalesReport.Sheet1")

    '//Set report's creation date as today
    Dim reportDate As String = Format(Today(), "short date")

    '//Insert the report data and data set values into the Workbooks data cache
    cdhi.CachedData("reportDate").SerializeDataInstance(reportDate.ToString)
    cdhi.CachedData("salesData").SerializeDataInstance(ds)

    '//Save all changes made to the cached data in the XLS file
    sd.Save()
    '//Update the bytes with the new data and close the XLS template
    newFile = sd.Document
    sd.Close()

    '//Build the response object and serve up the file in the browser
    With Response
      .AppendHeader("Content-disposition", "filename=Report.xls")
      .ContentType = "application/vnd.ms-excel"
      .OutputStream.Write(newFile, 0, newFile.Length)
      .Flush()
      .Close()
    End With
  End Sub
End Class

The button's click event retrieves sales data from the Northwind database and uses it to fill a data set object. With this data in memory, the code then opens the SalesReport.xls file and ready its contents into a byte object. This is done so that the original file is not modified and thus remains blank for the next report generation.

To access the cached data within the Excel workbook, a ServerDocument must be created. The code creates a ServerDocument instance and fills it with the NewFile byte object containing the workbook template. Each cached data item can be accessed via the HostItems collection (which is a child of the CachedData object). The HostItems collection contains all CachedDataHostItem objects stored within the data cache.

Using these objects, the code inserts the report's creation data (reportDate) as well as the retrieved dataset (ds). The code saves the changes to the ServerDocument object and then updates the NewFile byte object to reflect the new version of the SalesReport.xls workbook.

Finally, the code builds out the response object by specify the content type and headers and then sends the workbook to the browser.

Execute the Web page, and click the button to generate the report. The final result is a freshly generated Excel file, containing cached data from the Northwind database.

Summary

Office documents are utilized everyday by the majority of business users and are an ideal client for document-based applications. With the release of Visual Studio 2005 Tools for Office, document-based applications can be extended to include offline capabilities.

In addition, external applications can now use Office data on the server without the need to interact with the Office application object models. The capabilities provided by VSTO greatly extend the reach of Office-based applications in the enterprise at a time when Smart Clients are gaining in popularity.

Ty Anderson runs Cogent Company, a consultancy in Dallas specializing in developing Information Worker solutions with the Microsoft Office System. Ty writes frequently about professional development with the Microsoft Office Platform and has recently written a book, Office Programming 2003: Real World Applications, focused entirely on building business applications with the Microsoft Office System 2003.



 
 
>>> More Using Microsoft Visual Studio Articles          >>> More By Ty Anderson