Creating an Outlook Add-In Part 2

Intro

In part 1 of Creating an Outlook Add-In I explained how to create an Outlook 2003 Add In. With this article, I will use the same project and just use Outlook 2007 instead.

Design

I have decided to do things a bit differently with this article. If you recall, with the first project, I made use of the Extensibility project template to create the add-in. With this article, I selected File, New project, Visual Basic, Office, 2007, Outlook 2007 Add-In. Short, sweet, simple. This gives a file entitled ThisAddIn.vb. This is where we will write code almost identical to my first project's, with minor differences.

Outlook Add-In

Figure 1 - Outlook Add-In

Code

ThisAddIn.vb Gives us the following methods:

  • ThisAddIn_Startup
  • ThisAddIn_Shutdown

We will use the Startup event to call our function(s) to add the button onto the Outlook Toolbar, and we will use the Shutdown event to release all resources. Not much of the code has changed, but the most differences comes with creating the setup project.

Our code looks as follows:

Imports

Imports Microsoft.Office.Core 'Core Framework
'Imports Extensibility 'Ability to Extend Office
Imports System.Runtime.InteropServices 'Interop Services
Imports Microsoft.Office.Interop 'Office interop
Imports System.Windows.Forms

Declarations

    '  Private WithEvents btnFunny As Office.CommandBarButton 'Our Command Button CHANGED HERE
    Private objAppObject As Outlook.Application = New Outlook.Application() 'Application Object CHANGED HERE
    Private objAddIn As Object 'Instance
    Private FunnyToolBarTag As String = "Save Your Funnies"

    Private FunnyToolBar As Office.CommandBar
    Private btnFunny As Office.CommandBarButton

BackupEmails Sub

    '''Main Sub to Backup All Emails 
    Sub BackupEmails()
        Try
            Dim i As Long 'First Loop - Folders
            Dim j As Long 'Second Loop - Subfolders
            Dim lngRemoveSlash As Long 'Name, After Unecessary \ Was Removed

            Dim strSubject As String 'Email Subject
            Dim strEmailName As String 'Email Name
            Dim strFileName As String 'Filename of Email
            Dim strPath As String 'Path
            Dim strSelFolder As String 'Selected Outlook Folder
            Dim strSelFolderPath As String 'Selected Outlook Folder Path
            Dim strSaveToFolder As String 'Where to Save to

            Dim outNameSpace As Outlook.NameSpace = New Outlook.NameSpace 'Outlook Namespace CHANGED HERE
            Dim objApp As Outlook.Application = New Outlook.Application() 'Outlook Application CHANGED HERE
            Dim objMailFolder As Outlook.MAPIFolder 'Outlook Mail Folder
            Dim objMailItem As Outlook.MailItem = New Outlook.MailItem 'Outlook Email Item CHANGED HERE


            Dim objFSO As Object 'File System Object
            Dim objFolderToBackup As Object 'Which Folder Must We Backup

            Dim colFolders As New Collection 'All Folders
            Dim colEntryID As New Collection 'All Entities
            Dim colStoreID As New Collection 'All Stores



            objFSO = CreateObject("Scripting.FileSystemObject") 'Create FSO Object

            objApp = New Outlook.Application 'Create Outlook Instance
            outNameSpace = objApp.GetNamespace("MAPI") 'Get Appropriate Outlook Namespace

            objFolderToBackup = outNameSpace.PickFolder 'Choose Folder to Backup

            If objFolderToBackup Is Nothing Then 'Nothing Selected

                Exit Sub

            End If

            strPath = CustomBrowseForFolder() 'Show & Get Output Folder

            If strPath = "" Then 'If No Path Chosen

                Exit Sub

            End If

            If Not Right(strPath, 1) = "\" Then 'Add \ Afterwards

                strPath = strPath & "\"

            End If

            Call GetOutLookFolders(colFolders, colEntryID, colStoreID, objFolderToBackup) 'Get All Folders

            For i = 1 To colFolders.Count 'Loop Through Folders

                strSelFolder = StripCharacters(colFolders(i)) 'Remove Characters that aren't Allowed in Filenames

                lngRemoveSlash = InStr(3, strSelFolder, "\") + 1 'Remove \

                strSelFolder = Mid(strSelFolder, lngRemoveSlash, 256) 'Edited Filename
                strSelFolderPath = strPath & strSelFolder & "\" 'Add \

                strSaveToFolder = Left(strSelFolderPath, Len(strSelFolderPath) - 1) & "\" 'Get Parent Folder of Message

                If Not objFSO.FolderExists(strSelFolderPath) Then 'If Folder doesn't Exist, Create it

                    objFSO.CreateFolder(strSelFolderPath)

                End If

                objMailFolder = objApp.Session.GetFolderFromID(colEntryID(i), colStoreID(i)) 'Get All Subfolders in Chosen Folder

                For j = 1 To objMailFolder.Items.Count 'Establish Count

                    objMailItem = objFolderToBackup.Items(j) 'Get Subfolder Items, ie, Emails in Folder

                    strSubject = objMailItem.Subject 'Get Subject
                    strEmailName = StripCharacters(strSubject) 'Strip Invalid Characters out of FileName

                    strFileName = strSaveToFolder & strEmailName & ".msg" 'Name of Message to be Saved

                    strFileName = Left(strFileName, 256)

                    objMailItem.SaveAs(strFileName, 3) 'Save

                Next j

            Next i

        Catch ex As Exception
            MessageBox.Show(ex.Message.ToString())
        End Try
    End Sub

GetOutLookFolders Sub

    '''Get All Outlook Folders
    Sub GetOutLookFolders(ByVal colAllFolders As Collection, ByVal colAllEntryIDs As Collection, ByVal colAllStoreIDs As Collection, ByVal strSelFolder As Outlook.MAPIFolder)
        Try
            Dim strSubFolder As Outlook.MAPIFolder 'Get Chosen Folder

            colAllFolders.Add(strSelFolder.FolderPath) 'Path
            colAllEntryIDs.Add(strSelFolder.EntryID) 'Entry ID
            colAllStoreIDs.Add(strSelFolder.StoreID) 'Store ID

            For Each strSubFolder In strSelFolder.Folders 'Loop Through Folders

                GetOutLookFolders(colAllFolders, colAllEntryIDs, colAllStoreIDs, strSelFolder) 'Get Subfolders

            Next strSubFolder

            strSubFolder = Nothing 'Release Object
        Catch ex As Exception
            MessageBox.Show(ex.Message.ToString())
        End Try
    End Sub

CustomBrowseForFolder Function

    '''Display Browse for Folder Dialog
    Function CustomBrowseForFolder(Optional ByVal strDefaultLoc As String = "C:\Documents and Settings\hannes\Desktop\To Backup") As String
        Try
            Dim objShell As Object 'Shell Object

            objShell = CreateObject("Shell.Application"). _
            CustomBrowseForFolder(0, "Please Choose a Folder to Backup", 0, strDefaultLoc) 'Create BFF Dialog

            CustomBrowseForFolder = objShell.self.Path 'Set Initial Path

            objShell = Nothing 'Release Object
        Catch ex As Exception
            MessageBox.Show(ex.Message.ToString())
        End Try
    End Function

StripCharacters Function

    '''Strip Invalid Characters from Subjects
    Function StripCharacters(ByVal strSubs As String) As String
        Try
            Dim objRegEx As Object 'Regular Expression Object

            objRegEx = CreateObject("vbscript.regexp") 'Create Regular Expression Object

            'Regex Pattern to Identify Illegal Characters
            objRegEx.Pattern = "[\" & Chr(34) & "\!\@\#\$\%\^\&\*\(\)\=\+\|\[\]\{\}\`\'\;\:\<\>\?\/\,]"

            objRegEx.IgnoreCase = True 'Ignore Case
            objRegEx.[Global] = True

            StripCharacters = objRegEx.Replace(strSubs, "") 'Replace Illegal Character with Empty String

            objRegEx = Nothing 'Release Reg Ex Object
        Catch ex As Exception
            MessageBox.Show(ex.Message.ToString())
        End Try
    End Function

AddFunnyToolbar Sub

    Private Sub AddFunnyToolbar()
        Try
            ' Delete the existing instance, if applicable.
            Dim ExistingFunnyToolBar As Office.CommandBar = DirectCast(Me.Application.ActiveExplorer().CommandBars.FindControl(vbNull, vbNull, FunnyToolBarTag, True), Office.CommandBar)
            If ExistingFunnyToolBar IsNot Nothing Then
                ExistingFunnyToolBar.Delete()
            End If
            ' Add a new toolbar to the 
            ' CommandBars collection
            ' of the Explorer window.
            FunnyToolBar = Me.Application.ActiveExplorer().CommandBars.Add(FunnyToolBarTag, Office.MsoBarPosition.msoBarTop, False, True)
            If FunnyToolBar IsNot Nothing Then
                ' Add a button to the new toolbar.
                btnFunny = DirectCast(FunnyToolBar.Controls.Add(Office.MsoControlType.msoControlButton, vbNull, vbNull, 1, True), Office.CommandBarButton)
                btnFunny.Style = Office.MsoButtonStyle.msoButtonIconAndCaption
                btnFunny.Caption = "Save Your Funnies"
                btnFunny.FaceId = 1087
                btnFunny.Tag = FunnyToolBarTag

                AddHandler btnFunny.Click, AddressOf btnFunny_Click
                btnFunny.Visible = True
            End If
        Catch ex As System.Exception
            System.Windows.Forms.MessageBox.Show("Error: " & ex.Message.ToString(), "Error Message")
        End Try
    End Sub

All the Events

   Private Sub ThisAddIn_Startup(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Startup

        AddFunnyToolbar()
    End Sub

    Private Sub ThisAddIn_Shutdown(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Shutdown
        Try

            objAppObject = Nothing 'Remove Object References

        Catch ex As Exception
            MessageBox.Show(ex.Message.ToString())
        End Try
    End Sub

    '''Click Event for Our Button
    Private Sub btnFunny_Click(ByVal Ctrl As Office.CommandBarButton, ByRef CancelDefault As Boolean)

        BackupEmails() 'Save Emails

    End Sub

Creating an Outlook Add-In Part 2

All that is worth noting here, is the way the objects are now declared and used. I had to change them to what you have seen above, in order to be compatible with .NET Framework 4. The rest are verbatim the same as in my first project

Setup Project

I thought long and hard about how I will tackle this issue inside this article. I have come to the sad conclusion that I cannot improve on what has already been said at these three links :

  1. http://msdn.microsoft.com/en-us/library/ff937654.aspx
  2. http://msdn.microsoft.com/en-us/library/cc563937(v=office.12).aspx
  3. http://blogs.msdn.com/b/vsto/archive/2008/05/20/common-pitfalls-during-pia-deployment-and-installation.aspx

Go ahead, study the links above. There is just so much information inside, these links are really worth your read. Once you have read, studied and completed the steps outlined in each of the above links, you might have a Setup Project that looks like the following :

[launch.jpg]

Figure 2 - Setup, Launch Conditions

[registry.jpg]

Figure 3 - Setup, Registry Settings

[file.jpg]

Figure 4 - Setup, File System

Conclusion

There you go. It was not such a mouth full as the first installment, but it didn't need to be. I sincerely hope you enjoy playing around with all your Outlook AddIns that will make your life easier. Until next time, cheers!



About the Author

Hannes du Preez

Hannes du Preez is a Microsoft MVP for Visual Basic. He is a trainer at a South African-based company. He is the co-founder of hmsmp.co.za, a community for South African developers.

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: September 19, 2014 @ 2:00 p.m. ET / 11:00 a.m. PT In response to the rising number of data breaches and the regulatory and legal impact that can occur as a result of these incidents, leading analysts at Forrester Research have developed five important design principles that will help security professionals reduce their attack surface and mitigate vulnerabilities. Check out this upcoming eSeminar and join Chris Sherman of Forrester Research to learn how to deal with the influx of new device …

  • Java developers know that testing code changes can be a huge pain, and waiting for an application to redeploy after a code fix can take an eternity. Wouldn't it be great if you could see your code changes immediately, fine-tune, debug, explore and deploy code without waiting for ages? In this white paper, find out how that's possible with a Java plugin that drastically changes the way you develop, test and run Java applications. Discover the advantages of this plugin, and the changes you can expect to see …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds