*HOWTO:
The examples in this file are adapted for use from the
Professional VSTO 2005 edition published by Wiley
Each method illustrates a code listing in the chapter.
The solution represents a chapter.
To execute the examples, simply uncomment the relevant example
and run the solution from the Visual Studio Environment. Since
binaries are not included, you must compile the solution.
In some cases, there may be multiple handlers for one event.
The additional handlers are commented out. You will need to
uncomment the relevant handler to cause the code to work correctly.
For file loads, the actual file data is added as a file to the
solution. You will need to provide the fully qualified file path
to cause the application to run without error. The file path must
point to the file on disk. By default, the file is found in
the working folder directory. A sample file, data.txt is part of the project.
Where necessary, the excel spreadsheet contains data to cause
some examples to execute correctly. Additionally, controls may
already be present on the design surface as well.
A more detailed explanation of the code is already presented in the
chapter.
*/using System;
using System.Windows.Forms;
using Microsoft.VisualStudio.Tools.Applications.Runtime;
using
Outlook = Microsoft.Office.Interop.
Outlook;
using Office = Microsoft.Office.Core;
using System.Runtime.InteropServices;
using System.Reflection;
namespace AllSamples
{
public partial class ThisApplication
{
private void Listing_5_1()
{
if (this.Session.Folders.Count > 0)
{
Outlook.MAPIFolder folder = this.Session.Folders[1];
{
MessageBox.Show("The " + folder.Name + " folder contains " + folder.Items.Count + " items.");
}
}
}
private void Listing_5_2()
{
Outlook.MAPIFolder folder = this.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts);
Outlook.Explorer explorerWindow = this.Explorers.Add(folder, Outlook.OlFolderDisplayMode.olFolderDisplayNormal);
explorerWindow.Activate();
}
private void Listing_5_3()
{
Outlook.Application ol = new Microsoft.Office.Interop.Outlook.Application();
Outlook.MailItem NewMail = ol.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem) as Outlook.MailItem;
Outlook.Inspector inspectorWindow = this.Inspectors.Add(NewMail);
inspectorWindow.Activate();
}
//to run this example, add a valid email address in the to field
private void Listing_5_4()
{
CreateAndSendEmail();
}
public void CreateAndSendEmail()
{
Outlook.Application ol = new Microsoft.Office.Interop.Outlook.Application();
Outlook.MailItem NewMail = ol.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem) as Outlook.MailItem;
NewMail.Subject = "This is my email subject";
NewMail.To = "Add a valid email address here";
NewMail.Importance = Microsoft.Office.Interop.Outlook.OlImportance.olImportanceNormal;
NewMail.HTMLBody = "This <u>is</u> truly <b>amazing</b>";
NewMail.BodyFormat = Microsoft.Office.Interop.Outlook.OlBodyFormat.olFormatHTML;
NewMail.Send();
}
private void Listing_5_5()
{
BlockAttachments();
}
private void BlockAttachments()
{
Outlook.MAPIFolder inbox = Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
if (inbox.Items.Count > 0)
{
foreach (object item in inbox.Items)
{
Outlook.MailItem virus = item as Outlook.MailItem;
if (virus != null)
{
if (virus.Attachments != null)
{
System.Collections.ArrayList forbidden = new System.Collections.ArrayList(virus.Attachments.Count);
foreach (Outlook.Attachment attachObject in virus.Attachments)
{
object obj = attachObject.MAPIOBJECT;
if (obj != null)
{
attachObject.Delete();
forbidden.Add(attachObject.DisplayName);
}
}
if (forbidden.Count > 0)
{
MessageBox.Show("Some emails were blocked because they contain attachments");
}
}
}
}
}
}
private void Listing_5_6()
{
//creat the outlook appointment
Outlook.Application appItem = new Microsoft.Office.Interop.Outlook.Application();
Outlook.AppointmentItem appointment = appItem.CreateItem(Outlook.OlItemType.olAppointmentItem) as Outlook.AppointmentItem;
//set up some custom features
appointment.Subject = "This is my new appointment subject";
appointment.Body = "This is my new appointment body";
appointment.AllDayEvent = true;
appointment.BusyStatus = Outlook.OlBusyStatus.olBusy;
appointment.Start = DateTime.Now;
appointment.End = DateTime.Now.AddMinutes(30);
appointment.ReminderSet = true;
appointment.Importance = Microsoft.Office.Interop.Outlook.OlImportance.olImportanceHigh;
//activate
appointment.Save();
}
//to fire this code, we first need to subscribe tot he newinspector event
//after the application is run, trigger a newinspector object by double-clicking
//on an email item, or a contact item etc.
private void Listing_5_7()
{
Inspectors.NewInspector += new Microsoft.Office.Interop.Outlook.InspectorsEvents_NewInspectorEventHandler(Inspectors_NewInspector);
}
void Inspectors_NewInspector(Microsoft.Office.Interop.Outlook.Inspector Inspector)
{
if (this.Inspectors.Count > 0)
{
object item = this.Inspectors[1].CurrentItem;
Type type = item.GetType();
string propertyMapper = type.InvokeMember("MessageClass",
BindingFlags.Public | BindingFlags.GetField | BindingFlags.GetProperty, null, item, new object[] { }).ToString();
if (propertyMapper == "IPM.Note")
{
Outlook.MailItem note = item as Outlook.MailItem;
if (note != null)
{
if (!note.IsConflict)
{
Outlook.Conflicts conflicts = note.Conflicts;
if (conflicts.Count < 1)
{
string subject = note.To;
MessageBox.Show("The email is addressed to " + subject);
}
System.Runtime.InteropServices.Marshal.ReleaseComObject(note);
}
}
}
}
}
private void Listing_5_8()
{
DeleteAppointments("This is my new appointment subject");
}
public void DeleteAppointments(string item)
{
Outlook.MAPIFolder oCalendar = Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderCalendar);
string retVal = string.Empty;
foreach (Outlook.AppointmentItem oResult in oCalendar.Items)
{
if (oResult != null)
{
retVal = (string)oResult.GetType().InvokeMember("Subject", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.GetProperty, null, oResult, null, null);
if (retVal == item)
{
oResult.Delete();
}
}
}
}
//the code below demonstrates adding appointments. You will need to replace the
//i.ToString() with valid attendees
private void Listing_5_9()
{
//creat the outlook appointment
Outlook.Application appItem = new Microsoft.Office.Interop.Outlook.Application();
Outlook.AppointmentItem appointment = appItem.CreateItem(Outlook.OlItemType.olAppointmentItem) as Outlook.AppointmentItem;
Outlook.Recipients attendees = appointment.Recipients;
//add meeting participants
for (int i = 0; i < 10; i++)
{
Outlook.Recipient developer = attendees.Add(i.ToString());
developer.Type = (int)Outlook.OlMeetingRecipientType.olRequired;
}
//activate
appointment.Send();
}
private void Listing_5_10()
{
Outlook.Application ol = new Microsoft.Office.Interop.Outlook.Application();
Outlook.NoteItem NewNote;
//Create a new note
NewNote = ol.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olNoteItem) as Outlook.NoteItem;
NewNote.Body = "This is my new note body";
NewNote.Categories = "Memo";
NewNote.Display(false);
}
private void Listing_5_11()
{
Outlook.Application ol = new Microsoft.Office.Interop.Outlook.Application();
Outlook.NoteItem NewNote;
//Create a new note
NewNote = ol.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olNoteItem) as Outlook.NoteItem;
object modal = true;
NewNote.Body = "Holiday 2morrow";
NewNote.Categories = "Business";
NewNote.Height %= 2;
NewNote.Color = Outlook.OlNoteColor.olBlue;
NewNote.Display(modal);
}
private void Listing_5_12()
{
Outlook.MAPIFolder itemsBox = Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderDeletedItems);
if (itemsBox.Items.Count > 0)
{
foreach (object item in itemsBox.Items)
{
Outlook.MailItem oItem = item as Outlook.MailItem;
if (oItem != null)
{
//code to process items
}
}
}
}
private void Listing_5_13()
{
GetInfoFromAddressBook("contact", "enter search name here");
}
private Outlook.AddressEntry GetInfoFromAddressBook(string contact, string name)
{
if (name == null || name.Trim().Length == 0)
return null;
if (contact == null || contact.Trim().Length == 0)
contact = "Contacts";
contact = contact.Trim();
name = name.Trim();
if (Session.AddressLists != null && Session.AddressLists.Count > 0)
{
Outlook.AddressLists addressLists = Session.AddressLists as Outlook.AddressLists;
foreach (Outlook.AddressList address in addressLists)
{
if (address.Name.Trim() == contact)
{
foreach (Outlook.AddressEntry entry in address.AddressEntries)
{
if (entry.Name.Trim() == name)
{
return entry;
}
}
}
}
}
return null;
}
private void Listing_5_14()
{
this.MAPILogonComplete += new Microsoft.Office.Interop.Outlook.ApplicationEvents_11_MAPILogonCompleteEventHandler(ThisApplication_MAPILogonComplete);
}
void ThisApplication_MAPILogonComplete()
{
MessageBox.Show("Welcome " + this.GetNamespace("MAPI").CurrentUser.Name.ToString());
}
//this routine searches the inbox folder for emails matching the subject "virus"
private void Listing_5_15()
{
SearchRoutine("virus");
}
public void SearchRoutine(string searchToken)
{
Outlook.MAPIFolder oInbox = Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
int count = oInbox.Items.Count;
string retVal = string.Empty;
foreach (object oResult in oInbox.Items)
{
retVal = (string)oResult.GetType().InvokeMember("Subject", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.GetProperty, null, oResult, null, null);
if (retVal == searchToken)
{
MessageBox.Show("Found a suspicious item");
}
}
}
private void Listing_5_16()
{
//OutlookSearch.Properties.
Outlook.MAPIFolder oInbox = Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
object oResult = oInbox.Items.Find(@"[Subject] = ""virus""");
if (oResult != null)
{
Outlook.MailItem data = (Outlook.MailItem)oResult;
if (data != null)
{
}
}
}
private void Listing_5_17()
{
Outlook.MAPIFolder oInbox = Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
object oResult = oInbox.Items.Find(@"[Subject] = ""virus""");
do
{
oResult = oInbox.Items.FindNext();
} while (oResult != null);
Outlook.MailItem data;
if (oResult != null)
{
MessageBox.Show("Found");
data = (Outlook.MailItem)oResult;
}
}
private void Listing_5_18()
{
string scope = @"’Inbox’";
string filter = @"""subject"" LIKE ‘%vir%’";
string tag = "uniqueTag";
object subFolders = false;
this.AdvancedSearchComplete += new Microsoft.Office.Interop.Outlook.ApplicationEvents_11_AdvancedSearchCompleteEventHandler(ThisApplication_AdvancedSearchComplete);
this.AdvancedSearch(scope, filter, subFolders, tag);
}
//event handler code. Notice that this code is different from the text in the book
//the reason for this change is that the advancedsearchcomplete method executes on
//a separate thread that isn’t allowed to manipulate GUI objects that are part of
//Outlook. The access simply causes a run-time exception. The code has been simplified
//to show an appropriate message.
void ThisApplication_AdvancedSearchComplete(Microsoft.Office.Interop.Outlook.Search SearchObject)
{
if (SearchObject != null)
{
MessageBox.Show("A piece of mail with subject ‘virus’ was found");
}
}
//to run this example, add a valid email address in the to field
private void Listing_5_19()
{
Outlook.MailItem NewMail = this.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem) as Outlook.MailItem;
NewMail.Subject = "This is my email subject";
NewMail.To = "vapordan@hotmail.com";
NewMail.Send();
}
Office.CommandBar NewCommandBar;
Office.CommandBarButton NewCBarButton;
Office.CommandBars newCommandBar;
Outlook.Explorer explorer;
private void Listing_5_20()
{
explorer = this.ActiveExplorer();
newCommandBar = explorer.CommandBars;
object val = false;
NewCommandBar = newCommandBar.Add("myButton", Office.MsoBarPosition.msoBarTop, false, false);
NewCBarButton = (Office.CommandBarButton)NewCommandBar.Controls.Add(Office.MsoControlType.msoControlButton, missing, missing, missing, false);
NewCBarButton.Caption = "button1";
NewCBarButton.FaceId = 563;
NewCommandBar.Visible = true;
NewCBarButton.Visible = true;
NewCBarButton.TooltipText = "My new button1";
NewCBarButton.Click += new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(NewCBarButton_Click);
}
void NewCBarButton_Click(Microsoft.Office.Core.CommandBarButton Ctrl, ref bool CancelDefault)
{
MessageBox.Show("Hello, world!");
}
private void Listing_5_21()
{
Outlook.Explorer explorer = this.ActiveExplorer();
Office.CommandBars newCommandBar = explorer.CommandBars;
//do not replicate command bar objects
foreach (Office.CommandBar cmdBar in newCommandBar)
{
if (cmdBar.Name.Equals("ShortcutBar"))
{
cmdBar.Delete();
break;
}
}
}
Office.CommandBar menubar;
Office.CommandBarPopup cmdBarControl;
Office.CommandBarButton menuCommand;
private void Listing_5_22()
{
// Add the menu.
menubar = this.ActiveExplorer().CommandBars.ActiveMenuBar;
cmdBarControl = (Office.CommandBarPopup)menubar.Controls.Add(
Office.MsoControlType.msoControlPopup, missing, missing, menubar.Controls.Count, true);
if (cmdBarControl != null)
{
cmdBarControl.Caption = "&Add-in Tools";
// Add the menu command.
menuCommand = (Office.CommandBarButton)cmdBarControl.Controls.Add(
Office.MsoControlType.msoControlButton, missing, missing, missing, true);
menuCommand.Caption = "&Word Count…";
menuCommand.Tag = DateTime.Now.ToString();
menuCommand.Click += new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(menuCommand_Click);
}
}
void menuCommand_Click(Microsoft.Office.Core.CommandBarButton Ctrl, ref bool CancelDefault)
{
MessageBox.Show("Hello, World!");
}
//to run this example, pass in the string identifier of the bar to be removed
private void Listing_5_23()
{
RemoveMenubar("statusbar");
}
private void RemoveMenubar(string menuTitle)
{
//remove the menu
try
{
Office.CommandBarPopup foundMenu = (Office.CommandBarPopup)
this.ActiveExplorer().CommandBars.ActiveMenuBar.
FindControl(Office.MsoControlType.msoControlPopup,
missing, menuTitle, true, true);
if (foundMenu != null)
{
foundMenu.Delete(true);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//the following start up event handler is designed to call the code for each
//example in chapter 5. To run these examples, uncomment the appropriate function
private void ThisApplication_Startup(object sender, System.EventArgs e)
{
//Listing_5_1();
//Listing_5_2();
//Listing_5_3();
//Listing_5_4();
//Listing_5_5();
//Listing_5_6();
//Listing_5_7();
//Listing_5_8();
//Listing_5_9();
//Listing_5_10();
//Listing_5_11();
//Listing_5_12();
//Listing_5_13();
//Listing_5_14();
//Listing_5_15();
//Listing_5_16();
//Listing_5_17();
//Listing_5_18();
//Listing_5_19();
//Listing_5_20();
//Listing_5_21();
//Listing_5_22();
//Listing_5_23();
}
private void ThisApplication_Shutdown(object sender, System.EventArgs e)
{
}
#region VSTO generated code
/// <summary>
/// Required method for Designer support – do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InternalStartup()
{
this.Startup += new System.EventHandler(ThisApplication_Startup);
this.Shutdown += new System.EventHandler(ThisApplication_Shutdown);
}
#endregion
}