Generic Classes

Generic classes are a new feature in the .NET Framework and are supported in Visual Basic 2005. A generic class is a single class that provides functionality for different data types, without the need to write a separate class definition for each data type. You can also define generic methods, structures, and interfaces. A generic class uses type parameters as placeholders for the data types. The code example in Listing 3.10 shows the declaration of a generic class using t to represent the type...

Customizing Menus and Toolbars in Outlook

One of the main points of entry to code in Microsoft Office 2003 applications is through their menus and toolbars. Using the code you created in the preceding section to add a task, you can add additional code to call this code from a menu item that you create. In this example, you will delete the toolbar if it already exists and then re-create it. We take this approach instead of setting a reference to the existing toolbar if found because we don't know what state the toolbar was in when...

Control Type

When you add a Windows Forms control to a document, VSTO creates its version of the Windows Forms control. Instead of the control being in the System.Windows.Forms namespace, it is in the Microsoft.Office.Tools.Word.Controls namespace or the Microsoft.Office.Tools.Excel.Controls namespace, depending on which application you're using. The document or worksheet does not know anything about Windows Forms controls or their behaviors. ActiveX controls are the only thing that documents are aware of....

Creating and Registering the Form Region Manifest

You need to create a form region manifest file and register it in the registry. Let's look at how to do this. 1. To add a form region manifest to your project, click Project, and then in the main menu click Add New Item. 2. In the Templates pane of the Add New Item dialog box, select XML File. 3. Name the new item MySimpleFormRegionManifest.xml, and add the XML in Listing 14.33 to the MySimpleFormRegionManifest.xml file you just added. 4. On the Project menu, click SimpleFormRegion Properties....

Converting a Recorded VBA Macro to Visual Basic in VSTO 1

In this section, you will record a simple macro in VBA and then convert the code to Visual Basic 2005. This example is similar to the one in Chapter 6 in that you will record a macro that sets the selection to bold and italic. However, there isn't any toggle enumeration available in Excel that is similar to Word's wdToggle enumeration. Using Excel, you must write additional code to apply and remove the bold and italic formatting. 1. Open an Excel workbook outside Visual Studio, and type some...

Adding Controls to the Task Pane

Adding controls to the task pane is very similar to adding controls to a Windows Form. Using VSTO, you add controls to the ActionsPane object for Word 2003 and Excel 2003 solutions. If you're using VSTO 2005 SE and Office 2007, you can add the controls to the Custom task pane, which is available to any document you have opened. The remainder of this section describes controls on the actions pane, but it is also applicable to the Custom task pane. In Chapter 14 you'll learn more about adding...

Converting an Outlook Macro to a VSTO Addin

In this section you will create a simple VBA macro for Outlook and convert the code to a VSTO add-in. The VBA code is in the ItemSend event handler of the Application object in a VBA project, as shown in Listing 10.1. Listing 10.1. VBA macro that checks for a subject on an outgoing e-mail Private Sub Application_ItemSend ByVal Item As Object, _ Cancel As Boolean If Item.Class olMail Then If Item.Subject Then sendMessage MsgBox Subject text is missing. amp _ vbCrLf amp vbCrLf amp Do you want to...

Document Events

Following are the events that are available for a Document object in VSTO. Some of these events are available on the document in VBA and are exposed in the primary interop assembly PIA , others were added from the Application object, and still others are specific to VSTO. Notice that some of the event names have been changed. For example, the Close event is renamed CloseEvent, because there is both a Close method and a Close event on the Document object. To avoid collisions, VSTO has changed...

The Breakpoints Window

The Breakpoints window lets you see all the breakpoints in your application in one place. You can easily disable and enable breakpoints using the check boxes next to each breakpoint in the window. To view the Breakpoints window, click the Debug menu, point to Windows, and click Breakpoints. Figure 2.35 shows the Breakpoints window, with the current breakpoint displayed in bold. 1 0 1 Sheet l.vbj line 28 character 9 no condition -0 1 Sheet l.vbj line 31 character 9 no condition -0 1 Sheet2.vbj...

Accessing an Interop Object from a Host Control 1

Sometimes you need to access the Interop object associated with a given host control. For example, you might be working with the host controls and want to call a method that specifically requires an Interop object. You cannot cast a VSTO object into an Interop object, but you can instead call the InnerObject property of the host control to return its underlying Interop object. For example, if you wanted to write a solution that enables users to add a NamedRange control to the worksheet by...

Project Properties

You can set various properties for your project using the Project Designer. To open the Project Designer, select lt ProjectName gt Properties from the Project menu. Or you can double-click the MyProject node in Solution Explorer, as shown in Figure 2.l9. Several pages are available in the Project Designer. You can navigate to each page by clicking the appropriate tab on the left side of the window. Table 2.2 briefly describes each page. Table 2.2. Project Files Output During Build Table 2.2....

Vba Permissionset

In the Permission Set tab, you define the permissions that the code group grants as shown in Figure 11.5. VSTO solutions must be given full trust in order to run. The default behavior is for the VSTO project system to grant trust to your project, but you can turn off this behavior using your project's Trust Assemblies Location property, as shown in Figure 11.6. Figure 11.5. Permission Set tab of the code group Properties page Figure 11.5. Permission Set tab of the code group Properties page Add...

AndAlso Operator

The AndAlso operator is used to evaluate two expressions but evaluates the second expression only if the first expression is True. For example, if you want to access a property of a Bookmark object only if the bookmark exists thus avoiding an error , you can use the AndAlso statement, as shown in Listing 4.7. This technique is often referred to as short circuiting. Listing 4.7. Using the AndAlso operator If Bookmark1 IsNot Nothing AndAlso Bookmark1.Bold Then MsgBox The bookmark text is bold End...

Creating Custom Task Panes

Creating a Custom task pane in Office 2007 is as easy as creating a document-level actions pane for Word 2003 or Excel 2003. With VSTO 2005 SE, you first create an add-in project for an application that supports the Custom task pane, and then you add a user control to the application's CustomTaskPanes collection. VSTO 2005 SE supports Custom task panes for Word 2007, Excel 2007, Outlook 2007, InfoPath 2007, and PowerPoint 2007. Let's take a closer look at creating a simple Custom task pane for...

Granting Access to the VBA Project System

The very first time you create a VSTO project for Word and Excel, VSTO displays a dialog box informing you that the project must have access to the Visual Basic for Applications project system, as shown in Figure 2.5. You must click OK to create a VSTO project. If you click Cancel, the project will not be created. Vou must explicitly enable access to the Microsoft Office Visual Basic for Applications project system before you can create or open a Visual Studio Tools for the Microsoft Office...

SelectedIndexChanged Event Handler

You can write code in the SelectedIndexChanged event handler to show the value of the currently selected range in a text box on the actions pane, as shown in Listing 7.34. Listing 7.34. Displaying the current value of the list object in the actions pane Dim myTextbox As New TextBox Private Sub List1_SelectedIndexChanged ByVal sender As _ Object, ByVal e As System.EventArgs Handles _ List1.SelectedIndexChanged Dim currentRange As Excel.Range Me.Application.Selection myTextbox.Text...

Reenabling a SoftDisabled Addin

1. Create an Outlook add-in project with VSTO. 2. In the Startup event handler of ThisApplication, add the code in Listing 10.14. Listing 10.14. Creating an error at startup Private Sub ThisApplication_Startup ByVal sender As Object, _ ByVal e As System.EventArgs Handles Me.Startup Dim first As Integer 12 Dim second As Integer 0 Dim DivideByZero As Integer first second MsgBox DivideByZero 3. Press F5 to run the code. The message box does not display the code throws a divide-by-zero exception,...

Managing the Actions Pane

Several layers of containers make up the actions pane. Figure 5.2 illustrates these layers. Figure 5.2. Containers within the actions pane Figure 5.2. Containers within the actions pane The first container is the Office task pane itself. This container holds individual panes, such as the Document Actions task pane. The ActionsPane object is contained by the Document Actions task pane and acts as a container for Windows Forms controls. You can program-matically add Windows Forms controls...

Inheritance

Using inheritance, you can create a class that is based on an existing class, giving your new class all the behavior and functionality of the existing class. The class that you inherit from is known as the base class, and the class that is inheriting the functionality is known as the derived class. You can extend the functionality of the derived class by adding properties or methods that did not exist in the base class, or you can override inherited properties or methods so that they behave...

Microsoft PSS VSTO Client Troubleshooter

It can be difficult to verify that you have configured the client machine correctly with all the requirements. Some of this difficulty can be attributed to the different ways Office can be installed. You cannot always assume that Office has been installed to allow .NET programmability. However, you can use a tool created by the VSTO product support team that will analyze a client machine to determine whether the correct software is installed to run a deployed VSTO solution. This Microsoft PSS...

Clearing the Data Cache

Using ServerDocument, you can clear the cached data from the document. For example, suppose you have a VSTO solution that you want to deploy to an end user, but you don't want to remove the solution or the Runtime Storage Control because the user will run the VSTO solution. You do want to clear the data cache so that your test data does not go to the end user. Listing 13.16 shows how to clear the data cache from the document. Listing 13.16. Clearing the data cache in a VSTO document Imports Dim...

What Is a Task Pane

The mark of good action is that it appears inevitable in retrospect. Robert Louis Stevenson To gather user input, Office developers typically display forms to be filled out by end users. There are disadvantages to this approach because it often forces users to attend to the form before they can continue working in the document. The form also obstructs users' view of the contents of the document. In this chapter, you will learn how to customize the Document Actions task pane to provide a rich...

Caption Property

The Caption property is a read-only property that enables you to retrieve the text that is displayed at the top of the smart tag menu. The Caption property is set when you create the smart tag, and it passes the smart tag's unique namespace identifier and caption. In the example in Listing 9.4, the caption passed is Control Smart Tag. It is displayed at the top of the Smart Tag menu, followed by the recognized term or expression, as shown in Figure 9.7. Figure 9.7. The caption of a smart tag

Next replace the GetCustomUI function to return the correct Ribbon manifest

Listing 14.20. Returning the Ribbon manifest Public Function GetCustomUI ByVal ribbonID As String As String _ Implements Case Microsoft.Outlook.Mail.Read Return GetResourceText _ Case Microsoft.Outlook.Contact Return GetResourceText _ Case Else

Customizing the BuiltIn Ribbon

Rather than create your own tab, you might instead want to customize an existing built-in tab. Remember that just because you can do something, it doesn't mean that you should There are some things to keep in mind as you customize the Ribbon. Although you can hide tabs and groups, you should avoid doing so. Other installed add-ins might rely on these built-in items that you've hidden. You cannot add buttons to a built-in group. This is unfortunate because in some situations it would make sense...

Add the code in Listing to the ThisAddin class replacing the autogenerated

Listing 14.31. Code to read worksheet styles and populate the Custom task pane Dim WithEvents worksheet As Excel.Worksheet Dim myCustomTaskPane As Microsoft.Office.Tools.CustomTaskPane Dim myControl As UserControl1 Private Sub ThisAddIn_Startup ByVal sender As Object, _ ByVal e As System.EventArgs Handles Me.Startup Me.Application CType Microsoft.Office.Tools.Excel _ .ExcelLocale1033Proxy.Wrap GetType _ Excel.Application , Me.Application , Excel.Application ' End of VSTO-generated code...

The Ribbon Item

The Ribbon is often used as an entry point into your code. For example, your PowerPoint add-in might add a design Ribbon that contains controls that enable end users to design new PowerPoint themes. When you create an add-in to customize the Ribbon using VSTO 2005 SE, a generic Hello world tab, a group, and a toggle button are added to the Ribbon by default. This gives you the basic XML and code necessary to customize the Ribbon, which you can then modify to your liking. First we look at...

NET Framework Class Library

As the name suggests, the .NET Framework class library is a library of classes that contains popular functionality for use in your code. For example, an XMLReader class in the System.XML namespace gives you quick access to XML data. Instead of writing your own classes or functionality, you can use any of the thousands of classes and interfaces such as Windows Forms controls and input output IO functions that are included in the .NET Framework class library. You can also derive your own classes...

String Functions

It is important to note that the string handling functions for bytes and double-bytes in VBA are not supported in Visual Basic 2005. Visual Basic 2005 strings are in Unicode, and conversion of Strings to doublebyte character sets is no longer needed. Table 4.3 lists the VBA functions that are no longer supported and their equivalent Visual Basic 2005 functions found in the Microsoft.VisualBasic namespace . Table 4.3. Unsupported VBA Functions and the Equivalent Visual Basic 2005 Functions Table...

Overlapping Bookmarks

Bookmarks can overlap. For example, text in a document can be shared between bookmarks. Figure 6.22 shows two overlapping bookmarks. The first one is displayed within light gray brackets, and the second one is displayed within black brackets. This is some sample text to show howbookmarks can overlap. Figure 6.22. Overlapping bookmarks In this example, Bookmarkl contains the text This is some sample text to show, Bookmark2 contains text to show how bookmarks, and the text in the overlap of the...

To create this gallery add the XML markup in Listing to the Ribbonxml file and

Listing 14.12. XML markup for adding a gallery to the Ribbon lt gallery id galleryPrinter label Printer size large columns 2 imageMso FilePrint onAction OnAction itemWidth 25 itemHeight 25 gt lt item id Print imageMso FilePrint label Print gt lt item id PrintPreview label Print Preview gt lt item id QuickPrint imageMso FilePrintQuick label Quick Print gt lt item id PrintSetup imageMso PrintSetupDialog label Print Setup gt lt item id PrintOptions label Print Options gt Listing 14.13. Handling...

Garbage Collection

The common language runtime provides automatic memory management known as garbage collection. Garbage collection is a process of releasing memory used to store an object or object reference when it is no longer being used. The garbage collector examines variables and objects and checks whether there are any existing references. If the objects are not being referenced, they are not destroyed rather, they are flagged for garbage collection. The .NET Framework determines the time frame in which...

Introduction to VSTO SE

You can install a free, fully supported add-on for Visual Studio that lets you develop application-level solutions for several 2007 Microsoft Office system and Microsoft Office 2003 applications. This add-on is available as a free download in the Microsoft Download Center. This download is Visual Studio 2005 Tools for the 2007 Microsoft Office System. In this book, it is referred to as Visual Studio Tools for Office Second Edition VSTO 2005 SE to distinguish it from Visual Studio Tools for...

Chart Control Events

Table 7.4 shows the events that are available for a Chart control in VSTO. Table 7.4. Events of the Chart Control Table 7.4. Events of the Chart Control Raised when the chart is activated. The Activate event handler enables you to take action when focus is moved to the Chart control. Raised when the chart is double-clicked before the default action occurs. Raised when the chart is right-clicked before the default action occurs. Raised when the binding context of the chart changes. Raised when...

The Excel Locale Issue

When you create Excel solutions with VBA, the Excel object model expects English US formatting regardless of the user's locale settings. VSTO mimics this behavior by creating transparent proxies for the objects that always report that the locale is English US locale ID 1033 . Although the Excel object model expects locale ID 1033, it formats the data according to the user's locale settings when the data is displayed in the worksheet. The AssemblyInfo.vb file within your Excel solutions contains...

Writing Callbacks from VBA into VSTO Code

Typically you should not mix VBA code and VSTO code in your project, but there are some features in Excel that must use VBA because they are not available directly in VSTO. Creating user defined functions UDFs is one such area. In this case, you can create a callback in a VBA module that calls into the managed code of your VSTO solution. To do this, you must first create a public class that has an attribute called ComVisible that is set to True, as shown in Listing 7.6. You can also use this...

Opening and Closing the Custom Task Pane

If users close this Custom task pane, the only way to reopen it is to close PowerPoint and then reopen it, because you added the code to the Startup event handler. This probably isn't a good approach to take. Instead, you should provide a button on the Ribbon that enables you to toggle the Custom task pane on and off. 1. As shown in Listing 14.26, add a variable for the Custom task pane, and change the code in the Startup event handler of ThisAddin. Remove the code that sets the Visible...

Quick Access Toolbar

The Quick Access toolbar is a customizable toolbar that you see above the Ribbon, to the right of the File menu. As the name implies, this toolbar gives you quick access to the most often used features in the application. By default in Word, you see a Save item, Do and Undo, and a Quick Print item. You can add any built-in command to this menu, or any control that an add-in has added to the Ribbon. To do this, you can use the Customization tab of the Options dialog box or you can right-click a...

Outlook Items

Items in Outlook are contained within folders. Outlook has an Items collection that can contain multiple types of objects. The Items collection always returns an Object type, which must be cast into the specific Outlook item before you can use it in your code. Table 10.2 lists the Outlook items available in Outlook. A meeting or appointment in the Calendar folder. A contact containing information about a person in the Contacts folder. A distribution list containing several contacts in the...

Code Modules

Code modules in Visual Basic work in the same way as they do in VBA. A code module is a container for global methods and properties that can be used by other parts of your application. Unlike classes, you do not need to create a new instance of a module in order to call the methods. Nor do you need to fully qualify your call unless the same method exists in multiple modules. To fully qualify the method name you would use moduleName.methodName . Modules are a simple way to create code that can...

AutoCorrect Smart Tags

In the same way that Word places squiggles under errors in grammar or spelling, Visual Studio uses squiggles to indicate errors in code. When a word in your code is marked with a squiggle, you can view more information by holding your mouse cursor over the word to display a tool tip, or you can view the information in the Error List window in Visual Studio. If multiple errors exist, you can click the entry in the error list to move directly to the problem code. The squiggles come in a variety...

Features of VSTO

VSTO provides a programming model that extends some of the common objects in Word and Excel, such as a bookmark or range. These objects now have data binding capabilities. For example, you can bind a field in a database to a cell in Excel. With data binding, you can automatically populate areas of your document with data and update the data in a database with user input. The idea behind VSTO's programming model is to separate data from the presentation of the data. You now can directly access...

IntelliSense Code Snippets

One of the nice features of Visual Studio 2005 is the ability to use IntelliSense code snippets. These are XML files that enable you to insert a shell procedure into your code and then fill in the blanks to make the code snippet specific to your application. They are called IntelliSense code snippets because they are available as you type code directly in the Visual Studio Code Editor, just as other IntelliSense features are available when you type a period after an object name. You can access...

Creating a Form Region Startup Class

In this section you will add a class that implements FormRegionStartup. 1. Click Project, and then in the main menu click Add Class. 2. Name the class MySimpleFormRegion.vb, and add the code in Listing 14.35 to the MySimpleFormRegion.vb file. Listing 14.35. Creating a form region startup class Implements Outlook.FormRegionStartup ByVal FormRegion As Outlook.FormRegion _ Implements Outlook._FormRegionStartup _ .BeforeFormRegionShow Public Function GetFormRegionIcon _ ByVal FormRegionName As...

BeforeAddDataBoundRow Event Handler

The BeforeAddDataBoundRow event can be used to validate data that requires the addition of a new data-bound row to the list object. For example, you might want to check whether the date entered in the Date Scheduled column occurs on or after today's date. The code in Listing 7.28 compares the date entered to today's date and, if it occurs earlier than today, displays a message box and removes the row. Listing 7.28. Validating data entered in a ListObject using BeforeAddDataBoundRow Private Sub...

Debugging Your Code

It has been said that the best measure of good programmers is how well they can debug their code. Visual Studio ships with a number of tools that help you find and fix coding errors. Understanding how and when to use these tools is key to successful debugging. A similar version of some of these tools is available in the VBE, but there is no comparison to the rich features of Visual Studio. In this section, we describe some of the debugging tools you're probably familiar with from using VBA,...

FollowHyperlink Event Handler

You can write code in the FollowHyperlink event handler to take action before the event is raised. For example, you can display the link's address in Excel's status bar, as shown in Listing 7.43. Listing 7.43. Displaying a hyperlink's URL in the status pane Private Sub Sheet1_FollowHyperlink ByVal Target As _ Handles _ Me.FollowHyperlink Application.StatusBar website amp _ CStr Target.Address

OrElse Operator

The OrElse operator is used to evaluate two expressions but evaluates the second expression only if the first expression is False. The code in Listing 4.8 checks whether the text in a bookmark named Bookmarkl has italic formatting. If it doesn't, it then checks whether the bookmark has bold formatting. If either of these expressions is true, a message box is displayed. Listing 4.8. Using the AndAlso operator If Bookmark1.Italic OrElse Bookmark1.Bold Then MsgBox The bookmark text has formatting...

You can resolve this issue by creating the class shown in Listing B This class

Listing B.5. Base class for Inspector CommandBars Imports Microsoft.Office.Interop.Outlook ' This is an abstract base class for creating your Inspector ' CommandBars. Public MustInherit Class CommandBarBase ' Shared static list to hold references to open ' Inspectors. Private Shared ActiveCommandBars As New List Of CommandBarBase WithEvents Inspector As Outlook.Inspector Protected CommandBar As Office.CommandBar WithEvents cbb As Office.CommandBarButton Protected Sub New ByVal Inspector As...

Creating VSTO Solutions

Creating Office customizations with VBA has some similarities to creating Office solutions with VSTO, but there are many differences. When you create a VBA solution, you start in the Office application. In Word and Excel, you can press ALT F11 to open the Visual Basic Editor. Within the VBE, you have access to projects for any documents that are currently open, templates that the document is based on, and any globally accessible templates. You can choose to add your code in a module within the...