Microsoft Office Outlook Programming Using VSTO 3.0 and C#: Part 2

Exclusive offer: get 50% off this eBook here
VSTO 3.0 for Office 2007 Programming

VSTO 3.0 for Office 2007 Programming — Save 50%

Get to grips with Programming Office 2007 using Visual Studio Tools for Office

$20.99    $10.50
by Vivek Thangaswamy | March 2009 | Microsoft

Primarily, the Microsoft Office Outlook serves as an email application for a wide range of users. In the previous part of the article, we took an Overview of the Outlook object model and its features in VSTO. We saw the extensibility of Microsoft Office Outlook 2007 using the object model. We also learned to customize Microsoft Office Outlook menus and toolbars using VSTO. In the last part, we worked with form regions in Outlook, how to manipulate folders, contact information, and mail items using VSTO programming.

In this article by Vivek Thangaswamy, we will take a look at the following topics:

  • Learning the concepts and seeing a demonstration of working with Outlook meetings and appointments
  • Working with Ribbons for Outlook 2007
  • Outlook applications and the Microsoft SQL Server 2008 database interaction

Working with Appointments

Before we start working with the Appointments feature in Microsoft Office Outlook 2007, let's take a look at the Microsoft Office Outlook calendar. This will help you understand the concepts of Appointments more easily, and also explain how you can utilize this functionality for your needs. The Microsoft Outlook 2007 calendar is the scheduling component of the Outlook mail management system. It is well-integrated with other Microsoft Outlook functionality such as email, contacts, appointments, and other items in.

Appointments are the actions you're scheduling in your Outlook calendar, inviting other people to participate if required. You can set the status of your availability for an appointment, and you can also schedule recurring appointments.

Let's create an Outlook Appointment dynamically by using VSTO objects and C# programming:

  1. Open Visual Studio 2008, to create a new Outlook 2007 Add-in template project.
  2. Select New Project. Under Office select 2007 and select Outlook 2007 Add-in template and name the project as per your requirement.
  3. The solution will be created with all of supporting files required for the development of our Outlook solution.
  4. Write the following code, which will dynamically create an Appointment item in the ThisAddIn.cs file:
    private void ThisAddIn_Startup(object sender, System.EventArgs e)
    {
    // Outlook AppointmentItem object to compose new Appointment
    Outlook.AppointmentItem PacktAppointmentItem = (Outlook.
    AppointmentItem)this.Application.CreateItem(Outlook.
    OlItemType.olAppointmentItem);
    // Set the subject property value
    PacktAppointmentItem.Subject = "Regarding book review";
    // Set the location property value
    PacktAppointmentItem.Location = "Meeting Hall";
    // Set the start date
    PacktAppointmentItem.Start = DateTime.Today;
    // Set the end date
    Pac ktAppointmentItem.End = DateTime.Today;
    // Set the body property value
    PacktAppointmentItem.Body = "Book review comments from
    all editors";
    // Set the required attendee information
    PacktAppointmentItem.RequiredAttendees = "vivek@vsto.com";
    // Set the optional attandee information
    PacktAppointmentItem.OptionalAttendees = "radhika@vsto.com";
    // If parameter is set to false compose Appointment won't display
    PacktAppointmentItem.Display(true);
    // To send the composed PacktAppointmentItem
    //((Outlook._AppointmentItem)PacktAppointmentItem).Send();
    }

The following screenshot shows the results of adding and executing this code:

VSTO 3.0 for Office 2007 Programming

The AppointmentItem object is used to create appointments dynamically. An AppointmentItem object can be used to create a meeting, a one-time appointment, or a recurring appointment.

Let's perform a demonstration of how to delete a recurring appointment from your Outlook 2007 calendar, by using VSTO programming.

Open Visual Studio 2008 and create a new solution, as described earlier. Write the following code, which will dynamically delete an Appointment item, inside the ThisAddIn.cs file:

private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
// Reading the calendar folder through MEPIFolder object
Outlook.MAPIFolder PacktCalendarInfo = Application.Session.
GetDefaultFolder(Outlook.OlDefaultFolders.
olFolderCalendar);
// Get the data items in the calendar folder
Outlook.Items PacktCalendarDataItems = PacktCalendarInfo.Items;
// Searching the Appointment items based on subject
Outlook.AppointmentItem PacktAppointmentItem =
PacktCalendarDataItems["Book release"] as Outlook.
AppointmentItem;
// Selected appointment's recurrence information
Outlook.RecurrencePattern PacktRecPattern = PacktAppointmentItem.
GetRecurrencePattern();
// Loading the appointment to AppointmentItem Object
Outlook.AppointmentItem PacktAppointmentDelete = PacktRecPattern.
GetOccurrence(new DateTime(2008, 9, 28, 8, 0, 0));
// Now delete using the Delete method
PacktAppointmentDelete.Delete();
}

Working with meetings

Meetings are generally discussions amongst more than two people, during which predetermined topics are discussed. Meetings help you prepare a plan, or finalize pending work, or perform other tasks involving colleagues. In Microsoft Office Outlook, a meeting is a scheduled appointment—that is, people are invited to attend. You can set the meeting time and other options for the meeting attendees, to process the invitation.

VSTO 3.0 supports the dynamic creation of meeting items for Office. Let's create a meeting invitation dynamically, by using the VSTO object model and C# programming.

Open Visual Studio 2008 and create a new solution, as explained earlier. Write the following code, which will dynamically create a meeting invite item, inside the ThisAddIn.cs file:

private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
// Outlook PacktMeetingItem object to compose new meeting request
Outlook.AppointmentItem PacktMeetingItem = (Outlook.
AppointmentItem)this.Application.CreateItem(Microsoft.Office.
Interop.Outlook.OlItemType.olAppointmentItem);
PacktMeetingItem.MeetingStatus = Microsoft.Office.
Interop.Outlook.OlMeetingStatus.olMeeting;
// Set the subject for the meeting
PacktMeetingItem.Subject = "Changes in book content";
// Update the body information of the meeting
PacktMeetingItem.Body = "Work on the changes and update";
// Start Expiry Time of the meeting
PacktMeetingItem.Start = new DateTime(2008, 9, 28, 9, 0, 0);
// Set the recipient information
Outlook.Recipient PacktRecipient = PacktMeetingItem.Recipients.
Add("Radhika Rajagopalan");
PacktRecipient.Type = (int)Outlook.OlMeetingRecipientType.
olRequired;
// If parameter is set to false compose MeetingItem won't display
PacktMeetingItem.Display(true);
// To send the composed PacktMeetingItem
//((Outlook.MeetingItem)PacktMeetingItem).Send();
}

As we can see in the following screenshot, a Meeting tab is created successfully after executing this program.

VSTO 3.0 for Office 2007 Programming

An Outlook meeting is one of the many types of Appointments in Outlook. Meetings are internally linked with the Outlook calendar. A meeting request can be created using only the AppointmentItem object. To create and set the meeting invitation by using the AppointmentItem, you must set the MeetingStatus property to olMeeting.

VSTO 3.0 for Office 2007 Programming Get to grips with Programming Office 2007 using Visual Studio Tools for Office
Published: March 2009
eBook Price: $20.99
Book Price: $34.99
See more
Select your format and quantity:

Creating a Ribbon menu for Outlook 2007

The Ribbon is the new way of presenting menus for Office users and organizing related commands; visually it will appear as controls. The Ribbon menu feature is supported in most of the Office 2007 applications, such as Word, Excel, and Outlook. InfoPath and Visio are not provided with the Ribbon menu feature.

Let's create a Ribbon menu for Outlook by using Outlook objects and Visual designer support. In this example, we will create a Ribbon menu with a button on it. When you click the button, the option for composing a new mail will open.

  1. Open Visual Studio 2008 and create a new solution, as described earlier.
  2. Next, let's add the Ribbon component to our solution. Right-click on the project, and select Add | New Item... | Ribbon (Visual Designer), from the context menu. Name the Ribbon component as Ribbon1.cs, and click OK.

    Ribbon Visual Designer is a control that provides a visual designer for basic Ribbon customization tasks.

    VSTO 3.0 for Office 2007 Programming

  3. Expand the Toolbox sliding window in Visual Studio 2008, and you can find the controls that support the Ribbon menu under Office customization.
  4. VSTO 3.0 for Office 2007 Programming

  5. Next, drag-and-drop the controls that are required for your development inside your group control in the Ribbon. In this example, you are going to use the Button control.
  6. The Outlook Ribbon menu is quite different from other Office applications. The Ribbon menu varies for each Outlook region. For example, for reading a mail, you will see different Ribbon menu commands to those for an appointment and so on. To view your add-in that has the Ribbon menu, you need to specify the Ribbon types.

    VSTO 3.0 for Office 2007 Programming

  7. To create a program that will open a window for composing a new mail on a button click event, write the following code snippet inside the Ribbon1.cs file. Also include the code using Microsoft.Office.Interop.Outlook; in the Ribbon1.cs file to get access to the Outlook objects.
    // Click event of the button
    private void Button_OpenNewMail_Click(object sender,
    RibbonControlEventArgs e)
    {
    // Application class to get Outlook object references
    ApplicationClass PacktApplication = new ApplicationClass();
    // Get the MAPIFolder NameSpaces
    NameSpace PacktNameSpace = PacktApplication.
    GetNamespace("MAPIFolder");
    // Access to the default folders
    MAPIFolder ApreeMAPI = PacktNameSpace.
    GetDefaultFolder(OlDefaultFolders.olFolderInbox);
    // Outlook mailitem object to compose new mail
    MailItem PacktMailItem = (MailItem)ApreeMAPI.Items.
    Add(OlItemType.olMailItem);
    // To display the new mail compose window
    PacktMailItem.Display(true);
    }

Adding and executing the preceding code results in the following output:

VSTO 3.0 for Office 2007 Programming

Outlook 2007 data interaction with Microsoft SQL Server 2008

Microsoft presents a programming interface for synchronizing data from an external data source with the Outlook data file dedicated to storing data from that source. As you know, VSTO 3.0 is powerful enough to use features of the .NET technology. Linking the Outlook contacts in a Microsoft SQL Server 2008 database is one of the key features available for Outlook users. Working with your Outlook contacts in a database will keep you informed of changes to Outlook contacts and vice versa.

Let's see how to make your Outlook 2007 application interact with a relational database management system, for example, Microsoft SQL Server 2008. Let's consider a scenario where you want to import all of the contact information for your friends or colleagues that is currently managed in a Microsoft SQL Server 2008 database.

  1. Open Visual Studio 2008 and create a new solution, as described earlier.
  2. You need to know about the database, and the details of the tables that you are going to import into your contact folder. You can see the table information that is used in this demonstration in the following images:

    VSTO 3.0 for Office 2007 Programming

    VSTO 3.0 for Office 2007 Programming

  3. Let's write a program to establish effective communication with the Microsoft SQL Server 2008 database table, and import the information to Outlook 2007's contact folder, by using the C# programming language and VSTO.
    private void ThisAddIn_Startup(object sender, System.EventArgs e)
    {
    // Instantiated datatable, used to read the loaded data
    DataTable PacktDataTable = new DataTable();
    // Opening SQL connection for Microsoft SQL Server 2008
    SqlConnection PacktSQLConnection = new SqlConnection(@"Data
    Source=WINNER;Initial Catalog=PacktPub;Integrated
    Security=True");
    // Passing SQL command text and SQL connection information
    SqlCommand PacktSQLCommand = new SqlCommand("SELECT * FROM
    Contacts", PacktSQLConnection);
    // Open the SQL connection through Open method
    PacktSQLConnection.Open();
    // SQL reader to read through data from Database
    SqlDataReader PacktSQLReader = PacktSQLCommand.
    ExecuteReader(CommandBehavior.CloseConnection);
    // Load the read data to datatable
    PacktDataTable.Load(PacktSQLReader);
    // Now close the datareader
    PacktSQLReader.Close();
    // Get the contact folder loaded using MAPIFolder object
    Outlook.MAPIFolder PacktContactFolder = Application.Session.
    GetDefaultFolder(Outlook.OlDefaultFolders.
    olFolderContacts);
    // Accessing the Contact data items through Outlook item object
    Outlook.Items PacktContactItems = PacktContactFolder.Items.
    Restrict("[MessageClass]='IPM.Contact'");
    // To read the data one by one from the datatable
    foreach (System.Data.DataRow PacktDataRow in PacktDataTable.
    Rows)
    {
    // Check if the current contact item exists in Outlook or not.
    Outlook.ContactItem PacktExistingContact = (Outlook.
    ContactItem)PacktContactItems.Find("[Email1Address] =
    '" + PacktDataRow["Email"] + "'");
    // If it exists, then delete
    if (PacktExistingContact != null)
    {
    PacktExistingContact.Delete();
    }
    else
    {
    // Create a new contact object and update with data
    from database
    Outlook.ContactItem PacktAddContact = Application.
    CreateItem(Outlook.OlItemType.olContactItem) as
    Outlook.ContactItem;
    // Assign the value from datarow value
    PacktAddContact.FirstName = PacktDataRow["FirstName"].
    ToString();
    PacktAddContact.Email1Address = PacktDataRow["Email"].
    ToString();
    PacktAddContact.CompanyName = PacktDataRow["Company"].
    ToString();
    // Save the assigned values as contact
    PacktAddContact.Save();
    }
    }
    }

Once executed, the information stored in the database is retrieved and displayed in the Contacts plane, as shown in the following screenshot:

VSTO 3.0 for Office 2007 Programming

Summary

This article examined some important topics regarding programming using VSTO and C# for Microsoft Office Outlook 2007. We learned programming for a meeting and an appointment in Outlook. We have learned about the Ribbon, and how we can create Ribbons for Outlook. We also learned the concept of database interaction with an Outlook application, with the help of an example of how to connect to a database and get information from it into the Contact folder of Outlook.

VSTO 3.0 for Office 2007 Programming Get to grips with Programming Office 2007 using Visual Studio Tools for Office
Published: March 2009
eBook Price: $20.99
Book Price: $34.99
See more
Select your format and quantity:

About the Author :


Vivek Thangaswamy

Vivek Thangaswamy is a Software Solution developer and technical author living and working in the enjoyable surroundings of Chennai city, in India. His range of technical competence stretches across platforms and lines of business, but he specializes in Microsoft enterprise application architectures and Microsoft server-based product integrations. Vivek is currently working for the world's largest software services company in Microsoft Technologies. He holds several Microsoft certifications and Microsoft MVP awards. He has completed his Bachelor of technology degree in Information Technology from one of the world's finest universities and is currently pursuing a Management of Business Administration in Finance degree. Vivek loves spending time with friends and writing poems in his mother tongue.

Books From Packt

C# 2008 and 2005 Threaded Programming: Beginner's Guide
C# 2008 and 2005 Threaded Programming: Beginner's Guide

ASP.NET 3.5 Social Networking
ASP.NET 3.5 Social Networking

Software Testing with Visual Studio Team System 2008
Software Testing with Visual Studio Team System 2008

Implementing Microsoft Dynamics NAV 2009
Implementing Microsoft Dynamics NAV 2009

Learning SQL Server 2008 Reporting Services
Learning SQL Server 2008 Reporting Services

Microsoft Visual C++ Windows Applications by Example
Microsoft Visual C++ Windows Applications by Example

Entity Framework Tutorial
Entity Framework Tutorial

SharePoint Designer Tutorial: Working with SharePoint Websites
SharePoint Designer Tutorial: Working with SharePoint Websites

 

Your rating: None Average: 4.5 (2 votes)
Open web page in outlook 2010 with visual studio by
Thanks for this article. I want to customize my outlook 2010 by adding a new tab on wich i add a button wich onclick have to open a web page in outlook. I try this code onclick of my button it didn't work below my code ; nsp = Application.GetNamespace("MAPI") mpfInbox = nsp.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox) mpfNew = mpfInbox.Folders.Add("MyFolderHomePage") mpfNew.WebViewURL = "http://www.microsoft.com" mpfNew.WebViewOn = True Please help me.
Nice Article by
Thanks for this wonderful article. I was bit scared about outlook customization before reading these two posts, but after reading this i got good visibility to write custom utilities for outlook.

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
4
2
e
j
M
c
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software