Help and Support

Article ID: 555538 - Last Review: December 19, 2005 - Revision: 1.0

VSTO Server document caching

Author: Alvin Bruney MVP
Expand all | Collapse all

SUMMARY

This article describes how to use and server document class for application caching and document management without running an instance of the Microsoft Office on the web server.

Abstract

Perhaps you’ve heard of Visual Studio Tools for Office System 2005 (VSTO). In fact, I’d venture a guess that some of you may have toyed with it or even started serious development based on the tool suite. For those of you who haven’t, Visual Studio Tools for Office System 2005 allows developers to harness the power of Microsoft Office in enterprise level applications.
 
Currently, the VSTO tool suite supports Microsoft Excel, Word, InfoPath and Outlook. These applications may be built using either C# or Visual Basic.NET (Visual Basic). While most of the development targets windows forms and thick client development, one important piece focuses on server-side development.
 

Testing Microsoft Office automation thru VSTO

VSTO-based applications can be manipulated without the need to start an instance of Microsoft Office on the server. This paper demonstrates that an instance of Office is not needed for document automation by developing an application that manipulates documents on the server. We then create another application that can access and modify the data. Finally, we write a third piece - a watchdog process - that simply monitors the server for an instance of Microsoft Office. If an instance is detected, our watchdog process will notify us.
 
Here is the code for the watchdog process.
 
using System;
using System.Runtime.InteropServices;
 
namespace WatchDog
{
    classProgram
    {
        staticvoid Main(string[] args)
        {
            object automator = null;
            while (automator == null)
            {
                try
                {
                    automator = Marshal.GetActiveObject("Word.Application");
                    Console.WriteLine("An instance of Office is running.");
                    Console.Read();
                    Marshal.ReleaseComObject(automator);
                }
                catch (System.Runtime.InteropServices.COMException)
                {
                    //Microsoft Word is not running
                    Console.WriteLine("Watching...");
                }
            }
        }
    }
}
Listing 1-0 Watchdog process code
 
The watchdog application is conceptually simple. A while loop drives the process. During each iteration, the code searches for an instance of Microsoft Word. If no instance exists, the application prints an appropriate message and continues monitoring. To test watchdog, compile and fire the application. While the application is running, open Microsoft Word and you should be notified that an instance is running. Remember, for a Microsoft Office automation application to scale well, it must necessarily avoid creating an instance of Microsoft Word on the server.
 
Here is the code to create and house the VSTO based data. Create a new VSTO based project and enter the following code.
 
using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using Microsoft.VisualStudio.Tools.Applications.Runtime;
using Word = Microsoft.Office.Interop.Word;
using Office = Microsoft.Office.Core;
 
namespace WordDocument1
{
    public partial class ThisDocument
    {
        [Cached]
        public DataSet data;
        private void ThisDocument_Startup(object sender, System.EventArgs e)
        {
            data = new DataSet();
            data.ReadXml("sampledata.xml");
        }
 
        private void ThisDocument_Shutdown(object sender, System.EventArgs e)
        {
        }
    }
}
Listing 1-1 Application data
 
This application sets up the necessary plumbing that allows data to be stored inside a VSTO-based application. The first line of code declares a public dataset with a cached attribute. The cached attribute informs VSTO that the data contained in the dataset should be stored in a special way so that it is accessible outside the application.
 
Next, the code loads some arbitrary data, sampledata.xml, into the dataset. In the real world, this application would typically read from a data store and apply some sort of business logic to the data. This isn’t the real world so we skip the business logic piece.
 
Our final piece of code simply tries to access the data. Here is the code.
 
Public void ManipulateData()
{
            DataSet newDataSet;
            //point to the doc file in the debugger directory
            String fileName = “C:\WordDocument1\bin\debug\WordDocument1.doc”;
            if (ServerDocument.IsCacheEnabled(fileName))
            {
                ServerDocument servDoc = null;
                try
                {
                    servDoc = newServerDocument(fileName);
                    newDataSet = new System.Data.DataSet();
 
                    //grab the namespace and the class that contains the cached data
                    CachedDataHostItem hostI = servDoc.CachedData.HostItems["WordDocument1.ThisDocument"];
 
                    CachedDataItem dataI = hostI.CachedData[0];
                    // load the data
                    if (null != dataI.Xml && null != dataI.Schema)
                    {
                        System.IO.StringReader xmlReader = new System.IO.StringReader(dataI.Xml);
                        System.IO.StringReader schemaReader = new System.IO.StringReader(dataI.Schema);
                    
                        newDataSet.ReadXmlSchema(schemaReader);
                        newDataSet.ReadXml(xmlReader);
                        
if(newDataSet != null && newDataSet.Tables != null && newDataSet.Tables.Count > 0)
{
            // Modify the data by adding some arbitrary information
            foreach (DataRow row in newDataSet.Tables[0].Rows)
            {
                 row[0] = “my new value goes here”;
            }
  }
 
                        dataI.SerializeDataInstance(newDataSet);
                        servDoc.Save();
                    }
                }
                finally
                {
                    if (servDoc != null)
                        servDoc.Close();
                }
            }
}
Listing 1-2 Application to manipulate data
 
The code isn’t that difficult to follow. First, the code tests to see if the VSTO based application contains a data cache. The data cache is a new container that is able to access and manipulate the data inside a VSTO-based application. If the document supports VSTO data caching, an instance of the ServerDocument class is created. This is a special class that is able to manipulate the actual data inside the application.
 
Notice how the code uses a special naming syntax “WordDocument1.ThisDocument” to access the data. This is because the data that is displayed in a VSTO-based Microsoft word document is no longer stored inside the worddocument1.doc file. It is now stored in a special container accessible thru the serverdocument class using the syntax mentioned here.
Once access to the data is obtained, the code can simply read the data into a dataset and manipulate it. Finally, the serverdocument class’ save method is used to write the changed data in the dataset back into the application store.
 
So let’s fire it up. Run the application watchdog first to begin monitoring for an instance of Microsoft Office. Then run the code in listing 1-1 so that data can be loaded. Finally, fire up the code in listing 1-2 so that the data can be manipulated.
 
After running the test harness you will find that the process executes successfully without notification from the watchdog process. The test harness demonstrates that Microsoft Office is not required to manipulate data contained in VSTO-based applications on the server.
 
The new VSTO design is actually the reason for this improvement. VSTO now separates content from presentation. This divorced architecture allows calling code to service data contained inside VSTO-based applications without the need to start an instance of either Microsoft Office or Microsoft Excel. Because an instance of Office is avoided during the automation, then the scalability problems that accompany Office automation disappear entirely.
 
The code presented demonstrates that the divorced architecture actually works and is scalable – although we haven’t tested the scalability claim. However, there are a couple of drawbacks to this silver bullet. The data must be created using Visual Studio Tools for the Office System 2005 since it needs to support data caching. This is quite a shortcoming because it necessarily means that you must migrate your applications to VSTO solutions first if you intend to take advantage of data caching. Also, Datacaching is only supported in Microsoft Word and Microsoft Excel. There is no support for datacaching in Microsoft Infopath or Microsoft Outlook.
 
Another drawback is that the VSTO tools suite is not free. When compared to the regular Office development based on COM that is essentially free, the zero cash cost can seem like an unnecessary investment. Still, if you have a requirement for a highly scalable piece of Office automation software, VSTO seems like a good alternative.

APPLIES TO
  • Microsoft Visual C# .NET 2003 Standard Edition
Community Solutions ContentCOMMUNITY SOLUTIONS CONTENT DISCLAIMER
MICROSOFT CORPORATION AND/OR ITS RESPECTIVE SUPPLIERS MAKE NO REPRESENTATIONS ABOUT THE SUITABILITY, RELIABILITY, OR ACCURACY OF THE INFORMATION AND RELATED GRAPHICS CONTAINED HEREIN. ALL SUCH INFORMATION AND RELATED GRAPHICS ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. MICROSOFT AND/OR ITS RESPECTIVE SUPPLIERS HEREBY DISCLAIM ALL WARRANTIES AND CONDITIONS WITH REGARD TO THIS INFORMATION AND RELATED GRAPHICS, INCLUDING ALL IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, WORKMANLIKE EFFORT, TITLE AND NON-INFRINGEMENT. YOU SPECIFICALLY AGREE THAT IN NO EVENT SHALL MICROSOFT AND/OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, PUNITIVE, INCIDENTAL, SPECIAL, CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF USE, DATA OR PROFITS, ARISING OUT OF OR IN ANY WAY CONNECTED WITH THE USE OF OR INABILITY TO USE THE INFORMATION AND RELATED GRAPHICS CONTAINED HEREIN, WHETHER BASED ON CONTRACT, TORT, NEGLIGENCE, STRICT LIABILITY OR OTHERWISE, EVEN IF MICROSOFT OR ANY OF ITS SUPPLIERS HAS BEEN ADVISED OF THE POSSIBILITY OF DAMAGES.

Article Translations

 

Related Support Centers