OFFICE UI

New VSTO Features Help You Customize Word And Outlook

Steve Fox and Paul Stubbs

This article is based on a prerelease version of Microsoft Visual Studio Tools for the Microsoft Office System. All information herein is subject to change.

This article discusses:
  • New features in VSTO “Orcas” Beta 1
  • Using the Ribbon designer for Office documents
  • Customizing the Ribbon with XML
  • Data binding with Word content controls
  • Using VSTO to build custom Outlook form regions
This article uses the following technologies:
VSTO, Office, Visual Studio

Contents

Overview of VSTO
Customizing the Office UI with the Ribbon Designer
Customizing Advanced Ribbons Using XML
VSTO Word Content Controls
Outlook Form Regions
Wrap Up

The 2007 Microsoft® Office system has evolved into a robust business application platform that you can use to build and deploy a range of Office Business Applications (OBAs). OBAs are an emerging class of applications that address real-world and critical business problems. You can build them by seamlessly integrating existing Office software and services (Microsoft Office Word, Excel® Services and SharePoint® Server) with line-of-business (LOB) systems such as SAP. Couple the power and extensibility of the Office system with the upcoming release of Visual Studio® later this year (code-named "Orcas") and you have an extremely strong marriage of technology. In this article, we focus on how professional developers can use Microsoft Visual Studio Tools for the Microsoft Office System (VSTO) to build powerful custom applications against the 2007 Microsoft Office system.

Overview of VSTO

VSTO is a powerful set of tools and features that let developers extend and customize Microsoft Office applications using Visual Basic® and C#. The "Orcas" release of VSTO will bring even more power to the developer. It includes integration of managed code development with Microsoft Office and Microsoft Office SharePoint in unique and exciting ways. It also provides a Ribbon visual designer that lets you customize the Office Ribbon and program against it using a simple Windows® Forms-like programming model.

Furthermore, VSTO provides the ability to easily extend Microsoft Office Outlook® forms with a visual designer that supports the use of Windows Forms controls and Windows Presentation Foundation controls, and also supports the ability to import forms composed of Outlook built-in controls. In addition, SharePoint workflow in C# or Visual Basic is now a rapid application development (RAD) experience in Visual Studio. VSTO includes visual workflow designers and new support for quickly deploying and debugging a custom workflow on a SharePoint server, which can reduce the labor-intensive process from 15 steps and several days to a few clicks in a wizard.

VSTO also has visual designers for Word 2007 and Excel 2007 that appear inside the Visual Studio IDE. This allows the document to act like a visual design surface, which makes the creation of powerful document-based solutions easy. The ability to construct Word 2007 documents using the new Word content controls, with full support for ADO.NET-style data binding, drag and drop from the data sources window, and property grid support are all available in VSTO as well.

In this article, we focus on a subset of the above features. Specifically, we illustrate how you can customize the Office Ribbon, add Word content controls to Microsoft Office Word 2007, integrate a custom Ribbon with the content controls, and build Outlook form regions. Obviously, these are just a few of the features in Visual Studio "Orcas," but we discuss them here because they will be a part of the Beta 1 release, which should be available by the time you read this.

Customizing the Office UI with the Ribbon Designer

In VSTO "Orcas," there are two ways in which you can customize the Office Ribbon. The first is similar to Microsoft Visual Studio 2005 Tools for Office Second Edition (VSTO 2005 SE); that is, through the use of an XML class and definition you can define the elements of the Ribbon and then hook the Ribbon elements to event handlers (through callback code). Since you’re probably familiar with this method, we are going to focus more on the second method of customizing the Office Ribbon in VSTO "Orcas": the Ribbon Designer. (If you’re interested in customizing the Ribbon with VSTO 2005 SE, see Ken Getz’s Advanced Basics column in this issue of MSDN® Magazine.)

The Ribbon Designer, which includes a visual designer and an extensibility object model, makes it straightforward for developers to create, configure, and debug the Ribbon UI. As with other visual designers, you can drag and drop controls onto the design surface, set properties through the Properties window, and easily create event handlers for your new Ribbon items by double-clicking the control. Further, Office callbacks are mapped to the events on the VSTO Ribbon objects so developers write event handlers instead of callback methods. Let’s go ahead and customize a sample Ribbon for Word 2007 for illustration.

To begin, create a new Word 2007 project in either the C# or Visual Basic Office node and call it WordRibbonExample. After you create the project, Visual Studio automatically creates a number of project resource files. On the root project file (WordExample.cs), right-click and select Add New Item | Ribbon (Visual Designer). You can either provide a name for the Ribbon or accept the default name. This will create a default custom Ribbon on which you can add Ribbon elements.

The Ribbon Designer facilitates drag and drop functionality, so you can drag controls from the Office Ribbon Controls tab of the toolbox. Tabs, groups, and buttons are the Ribbon controls that are supported in the Beta 1 release of VSTO "Orcas." Supported Office applications are Word 2007, Excel 2007, PowerPoint® 2007, and Outlook 2007.

In the following example, we have added three groups (you must have groups as containers for the Ribbon controls) to the Ribbon tab—called My Custom Tab. Within each of the groups, we have added buttons and images. Figure 1 shows how to edit a control’s properties.

Figure 1 Ribbon Designer

Figure 1** Ribbon Designer **(Click the image for a larger view)

A typical VSTO Ribbon customization consists of one or more Ribbon objects, each of which contains one or more Tab objects that contain one or more Group objects, and so on. Thus, a VSTO customization is constructed within a specific hierarchical structure of Ribbon objects. For example, the conceptual diagram in Figure 2 illustrates that you must have a tab as the highest level control. You can then add one or more group controls to the tab and one or more buttons, toggle buttons, and menus to the group. Within any given menu, though, you can only go five levels deep.

Figure 2 Control Hierarchy

Figure 2** Control Hierarchy **

With a custom Ribbon now built, you can add event handlers to the Ribbon elements. You add an event handler to an individual Ribbon control basically the same way you do it with other controls: double-click the control and Visual Studio automatically adds a click event and opens the source-code view for you to enter your event handler code. For example, if you have a button named testButtonOne, you can double-click the button in the designer and the code view will open to the testButtonOne_click event where you can enter some event-handling code, like so:

private void testButtonOne_click(
    object sender, RibbonControlEventArgs e)
{
    // Simple message box to illustrate click event.
    testButtonOne.label = “New Label”;
    MessageBox.Show(testButtonOne.label);
}

Customizing Advanced Ribbons Using XML

In VSTO 2005 SE, you customized the Office Ribbon through an XML file, by selecting Ribbon Support when adding a new item to your project. This automatically created a Ribbon class, which is used to load the custom UI, and a Ribbon XML file, which defines the custom UI. Figure 3 illustrates the default XML code in the Ribbon Support item.

Figure 3 Default XML Ribbon Definition

<customUI xmlns=”http://schemas.microsoft.com/office/2006/01/customui” onLoad=”OnLoad”>
  <ribbon>
    <tabs>
      <tab idMso=”TabAddIns”>
        <group id=”MyGroup”
               label=”My Group”>
          <toggleButton id=”toggleButton1” 
                        size=”large”
                        label=”My Button”
                        screentip=”My Button Screentip”
                        onAction=”OnToggleButton1” 
                        imageMso=”HappyFace” />
        </group>
      </tab>
    </tabs>
  </ribbon>
</customUI>

There are also default elements that are added to your project that help you customize the UI, such as a toggle button that calls a message box when the user clicks it, callback code that provides you with a sense for how you can build event handlers for the custom UI, and helper code.

While the new Ribbon Designer enables common Ribbon customization tasks, it does not provide support for the more advanced scenarios (such as repurposing built-in commands or working with some of the less commonly used controls). In the event that you want to customize the default Office UI or use control types not available in the designer, you can fall back to using Ribbon XML for your customization. You can either choose to start with the Ribbon (XML) item or you can use the designer as a starting point, then export to Ribbon XML and continue to define the custom UI using XML—but note that this is a one-time export. You will then need to manually define the callback signatures and port any event handler code you’ve written against the designer.

VSTO Word Content Controls

While the customization of the Ribbon enables you to create and wrap custom UI at the application level, VSTO Word content controls enable you to customize a document or template very simply to create a more structured and smarter document. Using drag and drop functionality, you can add controls to a Word 2007 template, build business logic into those controls, protect the content controls from user editing and deleting, and add simple data binding to local or enterprise databases. Because VSTO helps you to access powerful customization features (such as task pane customization), you can imagine a scenario where the document surface becomes an interface into enterprise data and the task pane (or a custom Ribbon) becomes the way in which users can populate the content controls within the Word 2007 document.

Using content controls, let’s create a simple Word template that can be built automatically using data from a customer database, and add a custom Ribbon that enables the end user to browse the data within the database. The resulting document will look like Figure 4.

Figure 4 Example Invitation Letter

Figure 4** Example Invitation Letter **

To start, you must create a solution so your end users can customize the Word template by selecting the content of predefined areas—based on the data in the customer database. In Visual Studio, you create a new project and, in either Visual Basic or C#, select Office and then Word 2007 Document template. This opens a blank Word document within the Visual Studio IDE, along with the content controls in the Toolbox shown in Figure 5.

Figure 5 Word Controls

Figure 5** Word Controls **

With the shell of the project, you can now add controls to the surface of the document. While adding controls is great, we also need to supply some structure to the document. To build this document template, you can either create the template within the Visual Studio environment or you can load a pre-defined template. For this example, we’ve first added some default text that will act as the invitation letter template and then added five content controls (by dragging and dropping the controls from the Toolbox to the surface of the document). The controls we added were a RichTextContentControl for the company name, company address, and addressee; and a DatePickerContentControl for the date and response date. After the controls are on the document surface, you can adjust the properties of the controls (similar to other controls within Visual Studio) through the Properties window. If you look back at Figure 4 you’ll see where we’ve added controls that, when hooked to the data browse event handlers, will allow a user to browse through the customer database.

If you’ve followed along, press F5 to build and run your solution. Because we have not hooked the controls to any existing database, there is no data to populate these fields. So close the Word document without saving, and return to the Visual Studio environment.

With the controls now placed in the document, you can reference a specific data source and bind the controls to it. For this sample, we created a very simple Microsoft Office Access™ customer database called CustomerDatabase. The database comprises one table with six columns: ID, CompanyName, CompanyAddress, ContactName, CurrentDate, and ResponseDate. Creating the reference is quite straightforward: you simply use the Data Source Configuration Wizard to bind the controls to specific records within the customer database.

To begin, click the Data menu and select Add a New Data Source. The Data Source Configuration Wizard will prompt you for a choice. Select Database and click Next. In the next dialog, click New Connection, and then in the Add Connection dialog, accept the default Data Source (which is Access) and then browse to your Access database. The wizard will then prompt you to select the tables and views that you want to associate with the project. If you created the same database that we did, select the CustomerInfo table and leave the Views option unchecked. Figure 6 illustrates this dialog.

Figure 6 Choose Your Database Objects Dialog

Figure 6** Choose Your Database Objects Dialog **(Click the image for a larger view)

After you’ve completed this step, click Finish. Based on the information that you’ve provided, Visual Studio automatically creates a data set, table adapter, and binding source—the elements you will need to bind your controls to the data and programmatically manipulate the records in your database. For this example, Visual Studio has automatically assigned names for these as follows: customerDatabaseDataSet, customerInfoTableAdapter, and customerInfoBindingSource.

Now that you have the database connected to the project, you must bind the data to the specific controls. To do this, you use the Data binding property in the Properties window (see Figure 7). Select Text, and then select the specific database record you want to associate with each of the content controls. (Note that you can also drag the specific data elements from the Toolbox and drop them onto the control with which you want to associate the data.)

Figure 7 Data Binding Property

Figure 7** Data Binding Property **(Click the image for a larger view)

With the specific records of the customer database now connected to each of the content controls, let’s customize the Ribbon and add event handlers to the new custom buttons to enable the end user to browse through data in the customer database. You can use the Ribbon Designer to create two buttons (a Next and a Previous button) and the Properties window to edit the properties of the tab, button group, and buttons, and also to map bitmap-format images to the buttons. The Figure 8 shows what this custom Ribbon might look like.

Figure 8 Data Browse Buttons

Figure 8** Data Browse Buttons **

The last step is to add event handlers to each of the buttons so the end user can browse the data in the customer database. To do this, double-click each of the buttons and add code that will allow the user to move either forward or backward across the data. When you double-click a button, the code view for the Ribbon class opens and enables you to add the event handler code. The code below uses the Globals object to access the document, the binding source for the customer database, and eventually the MoveNext and MovePrevious methods.

private void button1_OnAction(
  object sender, ControlEventArgs e)
{
  Globals.ThisDocument.customerInfoBindingSource.MoveNext();
}

private void button2_OnAction(
  object sender, ControlEventArgs e)
{
  Globals.ThisDocument.customerInfoBindingSource.MovePrevious();
}

With the custom buttons now hooked into the content controls, you can click F5 to build and run the solution and test the integration of the custom Ribbon and the content controls. When you run the solution, click the Customer Data tab to view the custom Ribbon buttons you just added. When you click the buttons, as you see in Figure 9, in the upper-right-hand corner of the document, they allow you to browse through the data—loading the specific records into the content controls in the document.

Figure 9 Browsing the Customer Data in the Letter

Figure 9** Browsing the Customer Data in the Letter **

This scenario is simple yet practical. It illustrates that with the help of the new Ribbon Designer and the Word content controls, you can create an automated application that can load and create personalized invitation letters for specific customers. As you learn more about how to develop against the 2007 Office system using VSTO, you’ll find ways to extend this scenario and build more sophistication into your customized applications. Now, let’s turn to Outlook form regions.

Outlook Form Regions

Outlook 2007 enables you to create form regions that you can use to display information to the user about a mail message, contact, or any other Outlook item. For example, when e-mail comes in from a customer, you can look up that customer in your system and display his order history in the form region. When you open a contact item, you can display a map of the contact’s address in the form region. In this section, you will create a form region that enables you to add notes about mail messages. The notes are entered and displayed in a form region below the message and persisted as a hidden attachment to the message (see Figure 10).

Figure 10 Outlook 2007 Form Region

Figure 10** Outlook 2007 Form Region **(Click the image for a larger view)

To create an Outlook 2007 form region, you can again start with either a Visual Basic or a C# project. Adding a form region is as simple as adding a new Outlook Form Region item. Right-click the project, and choose Add New Item from the context menu. Choose Outlook Form Region from the Add New Item dialog and set the name as NotesFormRegion.cs. Click Add to launch the Outlook Form Region Wizard, which will guide you through the process of adding the form region. The first thing you need to choose is the type of form region to create. There are four types to choose from: Separate, Adjoining, Replacement, and Replace All.

Choose Adjoining, which will make the form region show at the bottom of the inspector. Click Next to continue. Set the name to VSTO Notes. Note that the title and description are not available for the Adjoining form region types. You can also configure how the form region is displayed in compose mode, reading mode, or the reading pane. Leave all of the defaults checked and then click Next to continue.

Choose which Outlook inspectors your form region is attached to. This example uses the mail message to show the form region only when a mail item is shown. You have now supplied all of the information needed for the wizard to create the form region.

After you click Finish, you will see a new NotesFormRegion.cs item added to your project and the Form Region Designer is opened. You can now design your form region as you would design a Windows Form, by dragging controls from the Toolbox onto the design surface. For this example, all you need to add is a single rich-text box, which is used to display the mail notes. Drag a RichTextBox control from the Toolbox onto the form region design surface. Set it to dock in the parent container so that it fills the entire form region. Set the background color to yellow so that it looks like a note. At this point you have a fully functional Outlook form region. You can press F5 to build and launch Outlook. Open a mail message to see your yellow textbox at the bottom of the message.

Now let’s write some code to make the note-taking form region functional. Right-click on the form region designer and choose View Code. In the code view, you can see that the form region derives from the Microsoft.Office.Tools.Outlook.FormRegionControl class. The FormRegionControl base class contains all of the plumbing to embed your control onto an Outlook form region. You will also notice that there are three event handlers. The FormRegionInitializing event is called when the form region is first created. The event allows you to cancel the creation of the form region, and through it you are also passed a reference to the Outlook item to which the form region is attached. The other two events, FormRegionShowing and FormRegionClosed, are called when the form region is displayed and closed. These events are where you will add your code. When the form region is closed, you want to save the text from the rich textbox as a hidden attachment in the message. In order to attach the text you must first save it to a temporary file. When you display the form region, you want to read the text from the hidden attachment and show it in the rich textbox. Again you will need to write the attachment out to a temporary file first. Figure 11 illustrates how this might be done.

Figure 11 Enabling Text Editing in Outlook 2007 Form Region

Outlook.MailItem mailItem;
string NotesPath = “C:\\VSTO Note.txt”;
string NoteDisplayName = “VSTO Note”; 

private void NotesFormRegion_FormRegionShowing(
    object sender, System.EventArgs e)
{
    mailItem = (Outlook.MailItem)this.OutlookItem;
    foreach (Outlook.Attachment attachment in mailItem.Attachments)
    {
        if (attachment.DisplayName == NoteDisplayName)
        {
            attachment.SaveAsFile(NotesPath);
            richTextBox1.Text = System.IO.File.ReadAllText(NotesPath);
        }
    }
}

private void NotesFormRegion_FormRegionClosed(object sender, 
    System.EventArgs e)
{
    if (richTextBox1.Modified)
    {
        System.IO.File.WriteAllText(NotesPath, richTextBox1.Text);
        foreach (Outlook.Attachment attachment in mailItem.Attachments)
        {
            if (attachment.DisplayName == NoteDisplayName)
            {
                attachment.Delete();
            }
        }
        if (richTextBox1.TextLength > 0)
        {
            long position = 0;
            mailItem.Attachments.Add(NotesPath, 
                Outlook.OlAttachmentType.olEmbeddeditem, position, 
                NoteDisplayName);
        }
        mailItem.Save();
    }
}

After you’ve completed all of the steps above, press F5 and run your project. This will build your project and invoke Outlook 2007. When Outlook starts, open a message from your Inbox and type in some text to test it out!

Wrap Up

This article showed you how to customize the Office Ribbon, add content controls to a Word document, integrate a custom Ribbon with the Word document, and create an Outlook form region. These are just some of the Office development features available to you from VSTO in the Beta 1 release of Visual Studio "Orcas."

Steve Fox is a Program Manager with the Visual Studio Tools for Office (VSTO) team. He divides his time working externally with VSTO customers, providing VSTO training, delivering VSTO sessions at conferences and working internally with the development team to help evolve the VSTO product.

Paul Stubbs is a Program Manager with the Visual Studio Tools for Office and Visual Tools for Applications team. He coauthored VSTO for Mere Mortals with Kathleen McGrath (Addison-Wesley, 2006). He has spoken at TechEd and TechReady and participates in the developer community on the Microsoft forums. Read Paul’s blog at blogs.msdn.com/pstubbs.