Working with Outlook Objects
Working with the Application Object
This chapter examines some of the major objects in the Outlook object model, starting with the Application object. Many of the objects in the Outlook object model are very large, and it is beyond the scope of this book to completely describe these objects. Instead, this chapter focuses on the most commonly used methods and properties associated with these objects.
The Application object is the root object in the Outlook object model hierarchy, meaning that you can access all the other objects in the object model by starting at the Application object and accessing its properties and methods and the properties and methods of objects it returns.
A companion object to the Application object is the NameSpace object, which is retrieved by using the Application object's Session property. Some confusion can arise because functionality that you would expect to be on the Application object is often found on the NameSpace object. For example, the way to get to the root folders that are open in Outlook is through the NameSpace object's Folders property. The Application object has no Folders property.
Methods and Properties That Return Active or Selected Objects
The Application object has a number of methods and properties that return active objectsobjects representing things that are active or selected within Outlook. Table 11-1 shows some of these properties and methods.
Name |
Type |
What It Does |
---|---|---|
ActiveExplorer() |
Explorer |
Returns the active Explorer objectthe Explorer window that currently has focus within Outlook. If an Inspector window is active, this returns the Explorer window that is front-most in the stack of Outlook windows. If no Explorer windows are open, this method returns null. |
ActiveInspector() |
Inspector |
Returns the active Inspector objectthe Inspector window that currently has focus within Outlook. If an Explorer window is active, this returns the Inspector window that is front-most in the stack of Outlook windows. If no Inspector windows are open, this method returns null. |
ActiveWindow() |
object |
Returns the active window as an object. If no windows are open, this method returns null. The returned object can be cast to either an Explorer or Inspector object. |
Session |
Session |
A property that returns the NameSpace object. |
GetNameSpace() |
Session |
A method that returns the NameSpace object. Takes the type of NameSpace to return as a string. However, the only string you can pass to GetNameSpace is the string "MAPI". This is an older way to get the NameSpace object. The newer way to access the NameSpace object that is used in this book is through the Session property. |
Properties That Return Important Collections
The Application object has a number of properties that return collections that you will frequently use. Table 11-2 shows several of these properties. Listing 11-1 shows some code from a VSTO Outlook add-in that works with the active object methods and properties shown in Table 11-1 and the collections shown in Table 11-2.
Listing 11-1. A VSTO Add-In That Works with Active Objects and Collections
private void ThisApplication_Startup(object sender, EventArgs e) { Outlook.Explorer activeExplorer = this.ActiveExplorer(); if (activeExplorer != null) { MessageBox.Show(String.Format( "The active explorer is {0}.", activeExplorer.Caption)); } Outlook.Inspector activeInspector = this.ActiveInspector(); if (activeInspector != null) { MessageBox.Show(String.Format( "The Active Inspector is {0}.", activeInspector.Caption)); } object activeWindow = this.ActiveWindow(); if (activeWindow != null) { Outlook.Explorer explorer = activeWindow as Outlook.Explorer; Outlook.Inspector inspector = activeWindow as Outlook.Inspector; if (explorer != null) { MessageBox.Show(String.Format( "The active window is an Explorer: {0}.", explorer.Caption)); } else if (inspector != null) { MessageBox.Show(String.Format( "The active window is an Inspector: {0}.", inspector.Caption)); } } else { MessageBox.Show("No Outlook windows are open"); } Outlook.NameSpace ns = this.Session; MessageBox.Show(String.Format( "There are {0} root folders.", ns.Folders.Count)); MessageBox.Show(String.Format( "There are {0} explorer windows.", this.Explorers.Count)); foreach (Outlook.Explorer explorer in this.Explorers) { MessageBox.Show(explorer.Caption); } MessageBox.Show(String.Format( "There are {0} inspector windows.", this.Inspectors.Count)); foreach (Outlook.Inspector inspector in this.Inspectors) { MessageBox.Show(inspector.Caption); } MessageBox.Show(String.Format( "There are {0} reminders.", this.Reminders.Count)); System.Text.StringBuilder reminders = new System.Text.StringBuilder(); foreach (Outlook.Reminder reminder in this.Reminders) { reminders.AppendLine(reminder.Caption); } MessageBox.Show(reminders.ToString()); }
Property Name |
Type |
What It Does |
---|---|---|
Explorers |
Explorers |
Returns the Explorers collection, which enables you to access any open Explorer windows. |
Inspectors |
Inspectors |
Returns the Inspectors collection, which enables you to access any open Inspector windows. |
Reminders |
Reminders |
Returns the Reminders collection, which enables you to access all the current reminders. |
Performing a Search and Creating a Search Folder
Outlook provides an AdvancedSearch method on the Application object that allows you to perform a search in Outlook. The AdvancedSearch method works asynchronously and raises the AdvancedSearchComplete event when the search has completed. You can also save a search you perform using the AdvancedSearch method as an Outlook Search folder. AdvancedSearch takes four parameters, as shown in Table 11-3.
Parameter Name |
Type |
Description |
---|---|---|
Scope |
string |
Pass the name of the folder or folders that you want to search. For example, to search the Inbox, pass the string "'Inbox'". To search the Inbox and Calendar, pass "'Inbox', 'Calendar'". You can pass the full name of a folder, including the path to the folder, to search a folder within a folder. The scope string "'ReferenceReviews'" searches a folder called Reviews nested in a folder called Reference in the default Outlook Store. You can search a folder in another PST Outlook data file that is open inside of Outlook. The Scope string "'\ArchiveBackup'" searches a folder called Backup in a PST file called Archive that is open in Outlook. |
Filter |
optional object |
Pass the filter string that specifies what you want to search for. You learn how to construct this string below. |
SearchSub-Folders |
optional object |
Pass true to also search any subfolders under the folders specified in Scope. |
Tag |
optional object |
Pass a string to uniquely name the search so that when you handle the Application.AdvancedSearchComplete event you can distinguish between a search created by you and other searches created by other loaded add-ins. This is criticalyou cannot assume that you are the only add-in that is handling this event. You must carefully tag your searches with a unique string to ensure that your add-in does not act on an advanced search started by another add-in. |
We now consider how to construct the filter string that was mentioned in Table 11-3. The easiest way to do this is to let Outlook's built-in UI for constructing filters build the string for you. To do this, first select the folder you want to search. From the Arrange By menu in the View menu, choose Custom to display the Customize View dialog (see Figure 11-1).
Figure 11-1. The Customize View dialog.
Click the Filter button to display the Filter dialog. You can use this dialog to create the filter you want. In Figure 11-2, we have simply set the filter to show messages where the word review is in the subject field.
Figure 11-2. The Filter dialog.
After you have edited the filter to yield the results you want, click the SQL tab shown in Figure 11-3. Check the Edit these criteria directly check box. Doing so enables you to select the filter string and copy and paste it into your code. After you have copied the filter string onto the clipboard, you can cancel out of the Filter Dialog and the Customize View dialog.
Figure 11-3. The SQL tab of the Filter dialog displays a filter string.
Finally, paste the filter string into your code. You will want to use C#'s @ operator to preface the string, and you also need to expand all quotation marks to be double quotation marks. For our example, the C# code would look like this:
string filter = @"""urn:schemas:httpmail:subject"" LIKE '%review%'";
Listing 11-2 shows a complete example of using AdvancedSearch. Note that because the search proceeds asynchronously, we must handle the AdvancedSearchComplete event to determine when the search is finished. We also save the completed search as a search folder by calling Save on the completed Search object.
Listing 11-2. A VSTO Add-In That Uses the AdvancedSearch Method
public partial class ThisApplication { const string searchTag = "'review' Search In Inbox"; private void ThisApplication_Startup(object sender, EventArgs e) { this.AdvancedSearchComplete += new Outlook.ApplicationEvents_11_AdvancedSearchCompleteEventHandler( ThisApplication_AdvancedSearchComplete); this.AdvancedSearchStopped += new Outlook.ApplicationEvents_11_AdvancedSearchStoppedEventHandler( ThisApplication_AdvancedSearchStopped); string scope = @"'Inbox'"; string filter = @"""urn:schemas:httpmail:subject"" LIKE '%review%'"; bool searchSubfolders = true; try { MessageBox.Show("Starting search"); this.AdvancedSearch(scope, filter, searchSubfolders, searchTag); } catch (Exception ex) { MessageBox.Show(ex.Message); } } void ThisApplication_AdvancedSearchStopped( Outlook.Search searchObject) { if (searchObject.Tag == searchTag) { MessageBox.Show(String.Format( "Search completed. Found {0} results.", searchObject.Results.Count)); // Save this search as a search folder searchObject.Save(searchTag); } } void ThisApplication_AdvancedSearchComplete( Outlook.Search searchObject) { if (searchObject.Tag == searchTag) { MessageBox.Show(String.Format( "Search was stopped. Found {0} results.", searchObject.Results.Count)); } } #region VSTO Designer generated code private void InternalStartup() { this.Startup += new System.EventHandler(ThisApplication_Startup); } #endregion }
Copying a File into an Outlook Folder
Outlook provides a method to copy an existing document such as a spreadsheet on your desktop to an Outlook folder. The Application object's CopyFile method takes as a parameter a FilePath as a string, which is the full path to the document you want to copy into the Outlook folder. It also takes a DestFolderPath parameter, which is the name of the Outlook folder you want to copy the document to. Listing 11-3 shows an example of using CopyFile to put a spreadsheet called mydoc.xls into the Inbox and a second spreadsheet called mydoc2.xls into a folder called Reviews nested within a folder called Reference.
Listing 11-3. A VSTO Add-In That Uses the CopyFile Method
private void ThisApplication_Startup(object sender, EventArgs e) { this.CopyFile(@"c:mydoc.xls", "Inbox"); this.CopyFile(@"c:mydoc2.xls", @"ReferenceReviews"); }
Quitting Outlook
The Quit method can be used to exit Outlook. If any unsaved Outlook items are opened, Outlook prompts the user to save each unsaved Outlook item. When users are prompted to save, they get a dialog box that gives them a Cancel button. If the user clicks Cancel, Outlook does not quit.