none
vb.net Outlook application inspector raises an error when a new inspector event fires when a note is created/opened RRS feed

  • Question

  • Hi, I was wondering if anyone has had this issue before.

    I have an VSTO AddIn that I have created for Outlook 2003.  The Add In creates a new button on Outlook mail items that users can click to change the sensitivity of the email to confidential.  A gateway service then automatically encrypts out going emails set to confidential.

    I have working code that adds the button and sets the correct sensitivity when clicked.  However if a users opens a Note in Outlook my code raises an error.

    I'm new to programming Office Add-Ins and I have to say that I've been stuck on this issue for quite some time.  My code is written in vb.net and is as follows:


    Imports System
    Imports Microsoft.Office.Core
    Imports System.Runtime.InteropServices
    Imports System.Diagnostics

    Public Class SecureEmailAddIn
        Dim WithEvents allInsp As Outlook.Inspectors
        Dim oApp As Outlook.Application

        Private Sub SecureEmailAddIn_Startup(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Startup
            Try
                'Hooking in to Outlook
                oApp = New Outlook.Application
                'Getting a connection to all inspectors (outlook windows such as new mail, contacts and tasks)
                allInsp = oApp.Inspectors
            Catch ex As Exception
                MsgBox("The Secure Email Button AddIn has had an error.  Please view the event log for further details.", MsgBoxStyle.Critical)
                WriteToEventLog("Sub: SecureEmailAddIn_Startup. Error reads: " & vbCrLf & ex.Message, "SecureEmailButtonAddin", EventLogEntryType.Error, "Application")
            End Try
        End Sub

        Private Sub SecureEmailAddIn_Shutdown(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Shutdown
            oApp = Nothing
        End Sub

    Private Sub allInsp_NewInspector(ByVal Inspector As Microsoft.Office.Interop.Outlook.Inspector) Handles allInsp.NewInspector
            'This sub routine runs when a new inspector is created
            Try
                Dim itm As Object 'Object to hold the new inspector
                Dim msg As Outlook.MailItem 'A email object
                Dim commandBar As Office.CommandBar 'Used for hooking in to the standard toolbar in an email

                'Buttons to add to the standard tool bar to enable/disable encryption
                Dim encryptButton As Office.CommandBarButton
                Dim decryptButton As Office.CommandBarButton

                'Hooking the current inspector so we can work with it
                itm = Inspector.CurrentItem

                'If the new item is a email then we want to add encryption buttons
                If TypeOf itm Is Outlook.MailItem Then
                    'Hooking in to the standard toolbar of the email
                    commandBar = Inspector.CommandBars("Standard")

                    'Checking to see if the encryption buttons already exist
                    encryptButton = commandBar.FindControl(Tag:="EncryptMail")
                    decryptButton = commandBar.FindControl(Tag:="DecryptMail")

                    'If the buttons already exist remove them, if you don't do this you end up with multiple copies of the button
                    If Not (encryptButton Is Nothing) Then
                        encryptButton.Delete()
                    End If

                    If Not (decryptButton Is Nothing) Then
                        decryptButton.Delete()
                    End If

                    'Configuring the encryption buttons
                    'The reason there are two buttons was due to an issue with the AddHandler.  Originally I had one button that switched between
                    'encrypt and decrypt.  However everytime a new inspector was created and the button was removed and added the handler of the
                    'previous button would attach to the new button.  So the first time the button would have one event, the second time it would
                    'have 2 events, third time 3 events etc.  This meant that on event clicks the encryption would turn on and then off.  Using
                    'teo buttons is a bit of a messy hack but I couldn't find another way to get it to work.
                    encryptButton = CType(commandBar.Controls.Add(1), Office.CommandBarButton)
                    encryptButton.Style = Office.MsoButtonStyle.msoButtonIconAndCaption
                    encryptButton.FaceId = 718
                    encryptButton.Caption = "Secure Email"
                    encryptButton.Tag = "EncryptMail"

                    decryptButton = CType(commandBar.Controls.Add(1), Office.CommandBarButton)
                    decryptButton.Style = Office.MsoButtonStyle.msoButtonIconAndCaption
                    decryptButton.FaceId = 718
                    decryptButton.Caption = "Secure Email"
                    decryptButton.Tag = "DecryptMail"

                    'Event handlers for the newly created buttons.
                    AddHandler encryptButton.Click, AddressOf encryptbutton_Click
                    AddHandler decryptButton.Click, AddressOf decryptbutton_Click

                    'Setting the new item as a email object so we can access its details
                    msg = CType(itm, Outlook.MailItem)

                    'Preconfiguring the ecnryption buttons
                    If msg.Sensitivity = Outlook.OlSensitivity.olConfidential Then
                        encryptButton.Visible = False
                        decryptButton.State = Office.MsoButtonState.msoButtonDown
                        decryptButton.Visible = True
                    Else
                        decryptButton.Visible = False
                        encryptButton.State = Office.MsoButtonState.msoButtonUp
                        encryptButton.Visible = True
                    End If
                Else
                    'Removing the encryption buttons from non emails (contacts etc)
                    commandBar = Inspector.CommandBars("Standard")
                    encryptButton = commandBar.FindControl(Tag:="EncryptMail")
                    decryptButton = commandBar.FindControl(Tag:="DecryptMail")
                    If Not (encryptButton Is Nothing) Then
                        encryptButton.Delete()
                    End If

                    If Not (decryptButton Is Nothing) Then
                        decryptButton.Delete()
                    End If
                End If

                itm = Nothing
            Catch ex As Exception
                MsgBox("The Secure Email Button AddIn has had an error.  Please view the event log for further details.", MsgBoxStyle.Critical)
                WriteToEventLog("Function: allInsp_NewInspector. Error reads: " & vbCrLf & ex.Message, "SecureEmailButtonAddin", EventLogEntryType.Error, "Application")
            End Try
        End Sub

    I think that the bit of code causing the problem is "Private Sub allInsp_NewInspector(ByVal Inspector As Microsoft.Office.Interop.Outlook.Inspector) Handles allInsp.NewInspector".  I don't think that the note object likes being set to an Inspector.

    Any help with this problem would be great.

     

    Thursday, November 22, 2012 5:12 PM

Answers

  • Never, ever create a new Outlook.Application object in an Outlook addin. Use the trusted Application object from Me.Application. That's the first thing.
     
    Second, Note items are brain dead. If you try to work with them you will see all sorts of problems. Test for the type of item before trying to add any CommandBar UI and just don't do it if the item is a Note item.

    --
    Ken Slovak
    [MVP-Outlook]
    http://www.slovaktech.com
    Author: Professional Programming Outlook 2007
    "Simon Goodson" <=?utf-8?B?U2ltb24gR29vZHNvbg==?=> wrote in message news:6519d110-fb55-46b3-a1a3-92dfefd91143...

    Hi, I was wondering if anyone has had this issue before.

    I have an VSTO AddIn that I have created for Outlook 2003.  The Add In creates a new button on Outlook mail items that users can click to change the sensitivity of the email to confidential.  A gateway service then automatically encrypts out going emails set to confidential.

    I have working code that adds the button and sets the correct sensitivity when clicked.  However if a users opens a Note in Outlook my code raises an error.

    I'm new to programming Office Add-Ins and I have to say that I've been stuck on this issue for quite some time.  My code is written in vb.net and is as follows:


    Imports System
    Imports Microsoft.Office.Core
    Imports System.Runtime.InteropServices
    Imports System.Diagnostics

    Public Class SecureEmailAddIn
        Dim WithEvents allInsp As Outlook.Inspectors
        Dim oApp As Outlook.Application

        Private Sub SecureEmailAddIn_Startup(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Startup
            Try
                'Hooking in to Outlook
                oApp = New Outlook.Application
                'Getting a connection to all inspectors (outlook windows such as new mail, contacts and tasks)
                allInsp = oApp.Inspectors
            Catch ex As Exception
                MsgBox("The Secure Email Button AddIn has had an error.  Please view the event log for further details.", MsgBoxStyle.Critical)
                WriteToEventLog("Sub: SecureEmailAddIn_Startup. Error reads: " & vbCrLf & ex.Message, "SecureEmailButtonAddin", EventLogEntryType.Error, "Application")
            End Try
        End Sub

        Private Sub SecureEmailAddIn_Shutdown(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Shutdown
            oApp = Nothing
        End Sub

    Private Sub allInsp_NewInspector(ByVal Inspector As Microsoft.Office.Interop.Outlook.Inspector) Handles allInsp.NewInspector
            'This sub routine runs when a new inspector is created
            Try
                Dim itm As Object 'Object to hold the new inspector
                Dim msg As Outlook.MailItem 'A email object
                Dim commandBar As Office.CommandBar 'Used for hooking in to the standard toolbar in an email

                'Buttons to add to the standard tool bar to enable/disable encryption
                Dim encryptButton As Office.CommandBarButton
                Dim decryptButton As Office.CommandBarButton

                'Hooking the current inspector so we can work with it
                itm = Inspector.CurrentItem

                'If the new item is a email then we want to add encryption buttons
                If TypeOf itm Is Outlook.MailItem Then
                    'Hooking in to the standard toolbar of the email
                    commandBar = Inspector.CommandBars("Standard")

                    'Checking to see if the encryption buttons already exist
                    encryptButton = commandBar.FindControl(Tag:="EncryptMail")
                    decryptButton = commandBar.FindControl(Tag:="DecryptMail")

                    'If the buttons already exist remove them, if you don't do this you end up with multiple copies of the button
                    If Not (encryptButton Is Nothing) Then
                        encryptButton.Delete()
                    End If

                    If Not (decryptButton Is Nothing) Then
                        decryptButton.Delete()
                    End If

                    'Configuring the encryption buttons
                    'The reason there are two buttons was due to an issue with the AddHandler.  Originally I had one button that switched between
                    'encrypt and decrypt.  However everytime a new inspector was created and the button was removed and added the handler of the
                    'previous button would attach to the new button.  So the first time the button would have one event, the second time it would
                    'have 2 events, third time 3 events etc.  This meant that on event clicks the encryption would turn on and then off.  Using
                    'teo buttons is a bit of a messy hack but I couldn't find another way to get it to work.
                    encryptButton = CType(commandBar.Controls.Add(1), Office.CommandBarButton)
                    encryptButton.Style = Office.MsoButtonStyle.msoButtonIconAndCaption
                    encryptButton.FaceId = 718
                    encryptButton.Caption = "Secure Email"
                    encryptButton.Tag = "EncryptMail"

                    decryptButton = CType(commandBar.Controls.Add(1), Office.CommandBarButton)
                    decryptButton.Style = Office.MsoButtonStyle.msoButtonIconAndCaption
                    decryptButton.FaceId = 718
                    decryptButton.Caption = "Secure Email"
                    decryptButton.Tag = "DecryptMail"

                    'Event handlers for the newly created buttons.
                    AddHandler encryptButton.Click, AddressOf encryptbutton_Click
                    AddHandler decryptButton.Click, AddressOf decryptbutton_Click

                    'Setting the new item as a email object so we can access its details
                    msg = CType(itm, Outlook.MailItem)

                    'Preconfiguring the ecnryption buttons
                    If msg.Sensitivity = Outlook.OlSensitivity.olConfidential Then
                        encryptButton.Visible = False
                        decryptButton.State = Office.MsoButtonState.msoButtonDown
                        decryptButton.Visible = True
                    Else
                        decryptButton.Visible = False
                        encryptButton.State = Office.MsoButtonState.msoButtonUp
                        encryptButton.Visible = True
                    End If
                Else
                    'Removing the encryption buttons from non emails (contacts etc)
                    commandBar = Inspector.CommandBars("Standard")
                    encryptButton = commandBar.FindControl(Tag:="EncryptMail")
                    decryptButton = commandBar.FindControl(Tag:="DecryptMail")
                    If Not (encryptButton Is Nothing) Then
                        encryptButton.Delete()
                    End If

                    If Not (decryptButton Is Nothing) Then
                        decryptButton.Delete()
                    End If
                End If

                itm = Nothing
            Catch ex As Exception
                MsgBox("The Secure Email Button AddIn has had an error.  Please view the event log for further details.", MsgBoxStyle.Critical)
                WriteToEventLog("Function: allInsp_NewInspector. Error reads: " & vbCrLf & ex.Message, "SecureEmailButtonAddin", EventLogEntryType.Error, "Application")
            End Try
        End Sub

    I think that the bit of code causing the problem is "Private Sub allInsp_NewInspector(ByVal Inspector As Microsoft.Office.Interop.Outlook.Inspector) Handles allInsp.NewInspector".  I don't think that the note object likes being set to an Inspector.

    Any help with this problem would be great.

     


    Ken Slovak MVP - Outlook
    • Marked as answer by Simon Goodson Tuesday, November 27, 2012 3:51 PM
    Monday, November 26, 2012 3:23 PM
    Moderator

All replies

  • Did you referenced to the right version of PIA?

    Is this your full code? When I tried these, compiler says that WriteToEventLog() encryptbutton_Click()decryptbutton_Click() are not declared.


    John


    Monday, November 26, 2012 4:51 AM
  • Hi John,

    Sorry i didn't include the code for those subs/functions as the error happens before they run.  The code is as follows:

    Private Sub encryptbutton_Click()
            'Changing email sensitivity
            oApp.ActiveInspector.CurrentItem.Sensitivity = Outlook.OlSensitivity.olConfidential

            'Setting the button state to reflect whether the email is secure or not
            Dim commandBar As Office.CommandBar
            Dim encryptButton As Office.CommandBarButton
            Dim decryptButton As Office.CommandBarButton

            commandBar = oApp.ActiveInspector.CommandBars("Standard")
            encryptButton = commandBar.FindControl(Tag:="EncryptMail")
            decryptButton = commandBar.FindControl(Tag:="DecryptMail")

            If Not (encryptButton Is Nothing) Then
                encryptButton.Visible = False
                decryptButton.Visible = True
                decryptButton.State = Office.MsoButtonState.msoButtonDown
            End If
        End Sub

        Private Sub decryptbutton_Click()
            'Changing email sensitivity
            oApp.ActiveInspector.CurrentItem.Sensitivity = Outlook.OlSensitivity.olNormal

            'Setting the button state to reflect whether the email is secure or not
            Dim commandBar As Office.CommandBar
            Dim encryptButton As Office.CommandBarButton
            Dim decryptButton As Office.CommandBarButton

            CommandBar = oApp.ActiveInspector.CommandBars("Standard")
            encryptButton = CommandBar.FindControl(Tag:="EncryptMail")
            decryptButton = CommandBar.FindControl(Tag:="DecryptMail")

            If Not (decryptButton Is Nothing) Then
                decryptButton.Visible = False
                encryptButton.Visible = True
                encryptButton.State = Office.MsoButtonState.msoButtonUp
            End If
        End Sub

        Public Function WriteToEventLog(ByVal Entry As String, Optional ByVal AppName As String = "VB.NET Application", Optional ByVal EventType As EventLogEntryType = EventLogEntryType.Information, Optional ByVal LogName As String = "Application") As Boolean
            Dim objEventLog As New EventLog()

            Try
                'Register the App as an Event Source
                If Not EventLog.SourceExists(AppName) Then
                    EventLog.CreateEventSource(AppName, LogName)
                End If

                objEventLog.Source = AppName

                objEventLog.WriteEntry(Entry, EventType)
                Return True
            Catch Ex As Exception
                Return False
            End Try
        End Function

    Monday, November 26, 2012 10:28 AM
  • Never, ever create a new Outlook.Application object in an Outlook addin. Use the trusted Application object from Me.Application. That's the first thing.
     
    Second, Note items are brain dead. If you try to work with them you will see all sorts of problems. Test for the type of item before trying to add any CommandBar UI and just don't do it if the item is a Note item.

    --
    Ken Slovak
    [MVP-Outlook]
    http://www.slovaktech.com
    Author: Professional Programming Outlook 2007
    "Simon Goodson" <=?utf-8?B?U2ltb24gR29vZHNvbg==?=> wrote in message news:6519d110-fb55-46b3-a1a3-92dfefd91143...

    Hi, I was wondering if anyone has had this issue before.

    I have an VSTO AddIn that I have created for Outlook 2003.  The Add In creates a new button on Outlook mail items that users can click to change the sensitivity of the email to confidential.  A gateway service then automatically encrypts out going emails set to confidential.

    I have working code that adds the button and sets the correct sensitivity when clicked.  However if a users opens a Note in Outlook my code raises an error.

    I'm new to programming Office Add-Ins and I have to say that I've been stuck on this issue for quite some time.  My code is written in vb.net and is as follows:


    Imports System
    Imports Microsoft.Office.Core
    Imports System.Runtime.InteropServices
    Imports System.Diagnostics

    Public Class SecureEmailAddIn
        Dim WithEvents allInsp As Outlook.Inspectors
        Dim oApp As Outlook.Application

        Private Sub SecureEmailAddIn_Startup(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Startup
            Try
                'Hooking in to Outlook
                oApp = New Outlook.Application
                'Getting a connection to all inspectors (outlook windows such as new mail, contacts and tasks)
                allInsp = oApp.Inspectors
            Catch ex As Exception
                MsgBox("The Secure Email Button AddIn has had an error.  Please view the event log for further details.", MsgBoxStyle.Critical)
                WriteToEventLog("Sub: SecureEmailAddIn_Startup. Error reads: " & vbCrLf & ex.Message, "SecureEmailButtonAddin", EventLogEntryType.Error, "Application")
            End Try
        End Sub

        Private Sub SecureEmailAddIn_Shutdown(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Shutdown
            oApp = Nothing
        End Sub

    Private Sub allInsp_NewInspector(ByVal Inspector As Microsoft.Office.Interop.Outlook.Inspector) Handles allInsp.NewInspector
            'This sub routine runs when a new inspector is created
            Try
                Dim itm As Object 'Object to hold the new inspector
                Dim msg As Outlook.MailItem 'A email object
                Dim commandBar As Office.CommandBar 'Used for hooking in to the standard toolbar in an email

                'Buttons to add to the standard tool bar to enable/disable encryption
                Dim encryptButton As Office.CommandBarButton
                Dim decryptButton As Office.CommandBarButton

                'Hooking the current inspector so we can work with it
                itm = Inspector.CurrentItem

                'If the new item is a email then we want to add encryption buttons
                If TypeOf itm Is Outlook.MailItem Then
                    'Hooking in to the standard toolbar of the email
                    commandBar = Inspector.CommandBars("Standard")

                    'Checking to see if the encryption buttons already exist
                    encryptButton = commandBar.FindControl(Tag:="EncryptMail")
                    decryptButton = commandBar.FindControl(Tag:="DecryptMail")

                    'If the buttons already exist remove them, if you don't do this you end up with multiple copies of the button
                    If Not (encryptButton Is Nothing) Then
                        encryptButton.Delete()
                    End If

                    If Not (decryptButton Is Nothing) Then
                        decryptButton.Delete()
                    End If

                    'Configuring the encryption buttons
                    'The reason there are two buttons was due to an issue with the AddHandler.  Originally I had one button that switched between
                    'encrypt and decrypt.  However everytime a new inspector was created and the button was removed and added the handler of the
                    'previous button would attach to the new button.  So the first time the button would have one event, the second time it would
                    'have 2 events, third time 3 events etc.  This meant that on event clicks the encryption would turn on and then off.  Using
                    'teo buttons is a bit of a messy hack but I couldn't find another way to get it to work.
                    encryptButton = CType(commandBar.Controls.Add(1), Office.CommandBarButton)
                    encryptButton.Style = Office.MsoButtonStyle.msoButtonIconAndCaption
                    encryptButton.FaceId = 718
                    encryptButton.Caption = "Secure Email"
                    encryptButton.Tag = "EncryptMail"

                    decryptButton = CType(commandBar.Controls.Add(1), Office.CommandBarButton)
                    decryptButton.Style = Office.MsoButtonStyle.msoButtonIconAndCaption
                    decryptButton.FaceId = 718
                    decryptButton.Caption = "Secure Email"
                    decryptButton.Tag = "DecryptMail"

                    'Event handlers for the newly created buttons.
                    AddHandler encryptButton.Click, AddressOf encryptbutton_Click
                    AddHandler decryptButton.Click, AddressOf decryptbutton_Click

                    'Setting the new item as a email object so we can access its details
                    msg = CType(itm, Outlook.MailItem)

                    'Preconfiguring the ecnryption buttons
                    If msg.Sensitivity = Outlook.OlSensitivity.olConfidential Then
                        encryptButton.Visible = False
                        decryptButton.State = Office.MsoButtonState.msoButtonDown
                        decryptButton.Visible = True
                    Else
                        decryptButton.Visible = False
                        encryptButton.State = Office.MsoButtonState.msoButtonUp
                        encryptButton.Visible = True
                    End If
                Else
                    'Removing the encryption buttons from non emails (contacts etc)
                    commandBar = Inspector.CommandBars("Standard")
                    encryptButton = commandBar.FindControl(Tag:="EncryptMail")
                    decryptButton = commandBar.FindControl(Tag:="DecryptMail")
                    If Not (encryptButton Is Nothing) Then
                        encryptButton.Delete()
                    End If

                    If Not (decryptButton Is Nothing) Then
                        decryptButton.Delete()
                    End If
                End If

                itm = Nothing
            Catch ex As Exception
                MsgBox("The Secure Email Button AddIn has had an error.  Please view the event log for further details.", MsgBoxStyle.Critical)
                WriteToEventLog("Function: allInsp_NewInspector. Error reads: " & vbCrLf & ex.Message, "SecureEmailButtonAddin", EventLogEntryType.Error, "Application")
            End Try
        End Sub

    I think that the bit of code causing the problem is "Private Sub allInsp_NewInspector(ByVal Inspector As Microsoft.Office.Interop.Outlook.Inspector) Handles allInsp.NewInspector".  I don't think that the note object likes being set to an Inspector.

    Any help with this problem would be great.

     


    Ken Slovak MVP - Outlook
    • Marked as answer by Simon Goodson Tuesday, November 27, 2012 3:51 PM
    Monday, November 26, 2012 3:23 PM
    Moderator
  • Hi Ken,

    Thank you for the feedback.  I have modifed the code so that I'm using Me.Application.  None of the examples I'd been working from worked in this manner.

    As for your second point at first I thought that I was checking for the item type, then I slapped my forehead for being dumb when I realised that although I have a "If TypeOf itm Is Outlook.MailItem Then" statement I was then following it up with an else to clear down my added button from none mail items.  I have now added a check to see if the item is a note.

    This has stopped the try statement in the sub allInsp_NewInspector from raising an error.  However I should have stated that originally I was getting two errors.  The first error reads "Error: The operation failed".  The second was being raised by the try statement.

    As you can guess I am still getting the first error message regarding the operation failing.  

    From testing it would appear that the error is raised as soon as "Private Sub allInsp_NewInspector(ByVal Inspector As Microsoft.Office.Interop.Outlook.Inspector) Handles allInsp.NewInspector" is called.  I am presuming that it is the line "allInsp = oApp.Inspectors" in the sub SecureEmailAddIn_Startup that is causing this.  I'm a little stumped as the try block in SecureEmailAddIn_Startup is does not appear to be called.  The error being displaying is in a standard message dialog, not in the critical message dialog that I am creating.

    When I ok the error message the note opens ok.

    Any ideas?

    My code now reads as follows:

    Public Class SecureEmailAddIn
        Dim WithEvents allInsp As Outlook.Inspectors
        Dim oApp As Outlook._Application

        Private Sub SecureEmailAddIn_Startup(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Startup
            Try
                'Hooking in to Outlook
                oApp = Me.Application
                'Getting a connection to all inspectors (outlook windows such as new mail, contacts and tasks)
                allInsp = oApp.Inspectors
            Catch ex As Exception
                MsgBox("The Secure Email Button AddIn has had an error.  Please view the event log for further details.", MsgBoxStyle.Critical)
                WriteToEventLog("Sub: SecureEmailAddIn_Startup. Error reads: " & vbCrLf & ex.Message, "SecureEmailButtonAddin", EventLogEntryType.Error, "Application")
            End Try
        End Sub

        Private Sub SecureEmailAddIn_Shutdown(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Shutdown
            oApp = Nothing
        End Sub

        Private Sub allInsp_NewInspector(ByVal Inspector As Microsoft.Office.Interop.Outlook.Inspector) Handles allInsp.NewInspector
            'This sub routine runs when a new inspector is created
            Try
                Dim itm As Object 'Object to hold the new inspector
                Dim msg As Outlook.MailItem 'A email object
                Dim commandBar As Office.CommandBar 'Used for hooking in to the standard toolbar in an email

                'Buttons to add to the standard tool bar to enable/disable encryption
                Dim encryptButton As Office.CommandBarButton
                Dim decryptButton As Office.CommandBarButton

                'Hooking the current inspector so we can work with it
                itm = Inspector.CurrentItem

                'If the new item is a email then we want to add encryption buttons
                If TypeOf itm Is Outlook.MailItem Then
                    'Hooking in to the standard toolbar of the email
                    commandBar = Inspector.CommandBars("Standard")

                    'Checking to see if the encryption buttons already exist
                    encryptButton = commandBar.FindControl(Tag:="EncryptMail")
                    decryptButton = commandBar.FindControl(Tag:="DecryptMail")

                    'If the buttons already exist remove them, if you don't do this you end up with multiple copies of the button
                    If Not (encryptButton Is Nothing) Then
                        encryptButton.Delete()
                    End If

                    If Not (decryptButton Is Nothing) Then
                        decryptButton.Delete()
                    End If

                    'Configuring the encryption buttons
                    'The reason there are two buttons was due to an issue with the AddHandler.  Originally I had one button that switched between
                    'encrypt and decrypt.  However everytime a new inspector was created and the button was removed and added the handler of the
                    'previous button would attach to the new button.  So the first time the button would have one event, the second time it would
                    'have 2 events, third time 3 events etc.  This meant that on event clicks the encryption would turn on and then off.  Using
                    'teo buttons is a bit of a messy hack but I couldn't find another way to get it to work.
                    encryptButton = CType(commandBar.Controls.Add(1), Office.CommandBarButton)
                    encryptButton.Style = Office.MsoButtonStyle.msoButtonIconAndCaption
                    encryptButton.FaceId = 718
                    encryptButton.Caption = "Secure Email"
                    encryptButton.Tag = "EncryptMail"

                    decryptButton = CType(commandBar.Controls.Add(1), Office.CommandBarButton)
                    decryptButton.Style = Office.MsoButtonStyle.msoButtonIconAndCaption
                    decryptButton.FaceId = 718
                    decryptButton.Caption = "Secure Email"
                    decryptButton.Tag = "DecryptMail"

                    'Event handlers for the newly created buttons.
                    AddHandler encryptButton.Click, AddressOf encryptbutton_Click
                    AddHandler decryptButton.Click, AddressOf decryptbutton_Click

                    'Setting the new item as a email object so we can access its details
                    msg = CType(itm, Outlook.MailItem)

                    'Preconfiguring the ecnryption buttons
                    If msg.Sensitivity = Outlook.OlSensitivity.olConfidential Then
                        encryptButton.Visible = False
                        decryptButton.State = Office.MsoButtonState.msoButtonDown
                        decryptButton.Visible = True
                    Else
                        decryptButton.Visible = False
                        encryptButton.State = Office.MsoButtonState.msoButtonUp
                        encryptButton.Visible = True
                    End If
                ElseIf TypeOf itm Is Outlook.NoteItem Then
                    'Do nothing with notes, they are dumb
                Else
                    'Removing the encryption buttons from non emails (contacts etc)
                    commandBar = Inspector.CommandBars("Standard")
                    encryptButton = commandBar.FindControl(Tag:="EncryptMail")
                    decryptButton = commandBar.FindControl(Tag:="DecryptMail")
                    If Not (encryptButton Is Nothing) Then
                        encryptButton.Delete()
                    End If

                    If Not (decryptButton Is Nothing) Then
                        decryptButton.Delete()
                    End If
                End If

                itm = Nothing
            Catch ex As Exception
                MsgBox("The Secure Email Button AddIn has had an error.  Please view the event log for further details.", MsgBoxStyle.Critical)
                WriteToEventLog("Function: allInsp_NewInspector. Error reads: " & vbCrLf & ex.Message, "SecureEmailButtonAddin", EventLogEntryType.Error, "Application")
            End Try
        End Sub

        Private Sub encryptbutton_Click()
            'Changing email sensitivity
            oApp.ActiveInspector.CurrentItem.Sensitivity = Outlook.OlSensitivity.olConfidential

            'Setting the button state to reflect whether the email is secure or not
            Dim commandBar As Office.CommandBar
            Dim encryptButton As Office.CommandBarButton
            Dim decryptButton As Office.CommandBarButton

            commandBar = oApp.ActiveInspector.CommandBars("Standard")
            encryptButton = commandBar.FindControl(Tag:="EncryptMail")
            decryptButton = commandBar.FindControl(Tag:="DecryptMail")

            If Not (encryptButton Is Nothing) Then
                encryptButton.Visible = False
                decryptButton.Visible = True
                decryptButton.State = Office.MsoButtonState.msoButtonDown
            End If
        End Sub

        Private Sub decryptbutton_Click()
            'Changing email sensitivity
            oApp.ActiveInspector.CurrentItem.Sensitivity = Outlook.OlSensitivity.olNormal

            'Setting the button state to reflect whether the email is secure or not
            Dim commandBar As Office.CommandBar
            Dim encryptButton As Office.CommandBarButton
            Dim decryptButton As Office.CommandBarButton

            CommandBar = oApp.ActiveInspector.CommandBars("Standard")
            encryptButton = CommandBar.FindControl(Tag:="EncryptMail")
            decryptButton = CommandBar.FindControl(Tag:="DecryptMail")

            If Not (decryptButton Is Nothing) Then
                decryptButton.Visible = False
                encryptButton.Visible = True
                encryptButton.State = Office.MsoButtonState.msoButtonUp
            End If
        End Sub

        Public Function WriteToEventLog(ByVal Entry As String, Optional ByVal AppName As String = "VB.NET Application", Optional ByVal EventType As EventLogEntryType = EventLogEntryType.Information, Optional ByVal LogName As String = "Application") As Boolean
            Dim objEventLog As New EventLog()

            Try
                'Register the App as an Event Source
                If Not EventLog.SourceExists(AppName) Then
                    EventLog.CreateEventSource(AppName, LogName)
                End If

                objEventLog.Source = AppName

                objEventLog.WriteEntry(Entry, EventType)
                Return True
            Catch Ex As Exception
                Return False
            End Try
        End Function


    Tuesday, November 27, 2012 9:55 AM
  • Example image of the error
    Tuesday, November 27, 2012 9:59 AM
  • I preach this all the time, never use NewInspector() do much of anything other than assigning the Inspector to a wrapper class if desired and testing the type of item in Inspector.CurrentItem.
     
    During NewInspector() that item and even the Inspector are weak object references, where many of the properties aren't filled in yet. Just try to get Inspector.WordEditor in that event handler, for example. It fires an exception or returns a null.
     
    You need to wait for the first Activate() event of the Inspector (or the Open() event for the CurrentItem) to be able to work with things such as CommandBars or much else.
     
    Just assigning your WithEvents Inspectors collection to Application.Inspectors in startup is is perfectly fine and will cause no problems.
     
    One other thing. More modern versions of Outlook don't use CommandBars and even deprecate them so they are hidden properties on Inspectors and Explorers. You use the ribbon instead of CommandBars for both in 2010 or later, and for Inspectors in 2007. Using CommandBars for Inspectors in 2007 or later will put any UI you create into the Add-Ins tab instead of where you want it placed.
     
    I always recommend checking Application.Version to see what you're running under and therefore what's available for you to use.

    --
    Ken Slovak
    [MVP-Outlook]
    http://www.slovaktech.com
    Author: Professional Programming Outlook 2007
    "Simon Goodson" <=?utf-8?B?U2ltb24gR29vZHNvbg==?=> wrote in message news:3c0a9671-b973-4377-b2fb-c749489b543d...

    Hi Ken,

    Thank you for the feedback.  I have modifed the code so that I'm using Me.Application.  None of the examples I'd been working from worked in this manner.

    As for your second point at first I thought that I was checking for the item type, then I slapped my forehead for being dumb when I realised that although I have a "If TypeOf itm Is Outlook.MailItem Then" statement I was then following it up with an else to clear down my added button from none mail items.  I have now added a check to see if the item is a note.

    This has stopped the try statement in the sub allInsp_NewInspector from raising an error.  However I should have stated that originally I was getting two errors.  The first error reads "Error: The operation failed".  The second was being raised by the try statement.

    As you can guess I am still getting the first error message regarding the operation failing.  

    From testing it would appear that the error is raised as soon as "Private Sub allInsp_NewInspector(ByVal Inspector As Microsoft.Office.Interop.Outlook.Inspector) Handles allInsp.NewInspector" is called.  I am presuming that it is the line "allInsp = oApp.Inspectors" in the sub SecureEmailAddIn_Startup that is causing this.  I'm a little stumped as the try block in SecureEmailAddIn_Startup is does not appear to be called.  The error being displaying is in a standard message dialog, not in the critical message dialog that I am creating.

    When I ok the error message the note opens ok.

    Any ideas?

    My code now reads as follows:

    Public Class SecureEmailAddIn
        Dim WithEvents allInsp As Outlook.Inspectors
        Dim oApp As Outlook._Application

        Private Sub SecureEmailAddIn_Startup(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Startup
            Try
                'Hooking in to Outlook
                oApp = Me.Application
                'Getting a connection to all inspectors (outlook windows such as new mail, contacts and tasks)
                allInsp = oApp.Inspectors
            Catch ex As Exception
                MsgBox("The Secure Email Button AddIn has had an error.  Please view the event log for further details.", MsgBoxStyle.Critical)
                WriteToEventLog("Sub: SecureEmailAddIn_Startup. Error reads: " & vbCrLf & ex.Message, "SecureEmailButtonAddin", EventLogEntryType.Error, "Application")
            End Try
        End Sub

        Private Sub SecureEmailAddIn_Shutdown(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Shutdown
            oApp = Nothing
        End Sub

        Private Sub allInsp_NewInspector(ByVal Inspector As Microsoft.Office.Interop.Outlook.Inspector) Handles allInsp.NewInspector
            'This sub routine runs when a new inspector is created
            Try
                Dim itm As Object 'Object to hold the new inspector
                Dim msg As Outlook.MailItem 'A email object
                Dim commandBar As Office.CommandBar 'Used for hooking in to the standard toolbar in an email

                'Buttons to add to the standard tool bar to enable/disable encryption
                Dim encryptButton As Office.CommandBarButton
                Dim decryptButton As Office.CommandBarButton

                'Hooking the current inspector so we can work with it
                itm = Inspector.CurrentItem

                'If the new item is a email then we want to add encryption buttons
                If TypeOf itm Is Outlook.MailItem Then
                    'Hooking in to the standard toolbar of the email
                    commandBar = Inspector.CommandBars("Standard")

                    'Checking to see if the encryption buttons already exist
                    encryptButton = commandBar.FindControl(Tag:="EncryptMail")
                    decryptButton = commandBar.FindControl(Tag:="DecryptMail")

                    'If the buttons already exist remove them, if you don't do this you end up with multiple copies of the button
                    If Not (encryptButton Is Nothing) Then
                        encryptButton.Delete()
                    End If

                    If Not (decryptButton Is Nothing) Then
                        decryptButton.Delete()
                    End If

                    'Configuring the encryption buttons
                    'The reason there are two buttons was due to an issue with the AddHandler.  Originally I had one button that switched between
                    'encrypt and decrypt.  However everytime a new inspector was created and the button was removed and added the handler of the
                    'previous button would attach to the new button.  So the first time the button would have one event, the second time it would
                    'have 2 events, third time 3 events etc.  This meant that on event clicks the encryption would turn on and then off.  Using
                    'teo buttons is a bit of a messy hack but I couldn't find another way to get it to work.
                    encryptButton = CType(commandBar.Controls.Add(1), Office.CommandBarButton)
                    encryptButton.Style = Office.MsoButtonStyle.msoButtonIconAndCaption
                    encryptButton.FaceId = 718
                    encryptButton.Caption = "Secure Email"
                    encryptButton.Tag = "EncryptMail"

                    decryptButton = CType(commandBar.Controls.Add(1), Office.CommandBarButton)
                    decryptButton.Style = Office.MsoButtonStyle.msoButtonIconAndCaption
                    decryptButton.FaceId = 718
                    decryptButton.Caption = "Secure Email"
                    decryptButton.Tag = "DecryptMail"

                    'Event handlers for the newly created buttons.
                    AddHandler encryptButton.Click, AddressOf encryptbutton_Click
                    AddHandler decryptButton.Click, AddressOf decryptbutton_Click

                    'Setting the new item as a email object so we can access its details
                    msg = CType(itm, Outlook.MailItem)

                    'Preconfiguring the ecnryption buttons
                    If msg.Sensitivity = Outlook.OlSensitivity.olConfidential Then
                        encryptButton.Visible = False
                        decryptButton.State = Office.MsoButtonState.msoButtonDown
                        decryptButton.Visible = True
                    Else
                        decryptButton.Visible = False
                        encryptButton.State = Office.MsoButtonState.msoButtonUp
                        encryptButton.Visible = True
                    End If
                ElseIf TypeOf itm Is Outlook.NoteItem Then
                    'Do nothing with notes, they are dumb
                Else
                    'Removing the encryption buttons from non emails (contacts etc)
                    commandBar = Inspector.CommandBars("Standard")
                    encryptButton = commandBar.FindControl(Tag:="EncryptMail")
                    decryptButton = commandBar.FindControl(Tag:="DecryptMail")
                    If Not (encryptButton Is Nothing) Then
                        encryptButton.Delete()
                    End If

                    If Not (decryptButton Is Nothing) Then
                        decryptButton.Delete()
                    End If
                End If

                itm = Nothing
            Catch ex As Exception
                MsgBox("The Secure Email Button AddIn has had an error.  Please view the event log for further details.", MsgBoxStyle.Critical)
                WriteToEventLog("Function: allInsp_NewInspector. Error reads: " & vbCrLf & ex.Message, "SecureEmailButtonAddin", EventLogEntryType.Error, "Application")
            End Try
        End Sub

        Private Sub encryptbutton_Click()
            'Changing email sensitivity
            oApp.ActiveInspector.CurrentItem.Sensitivity = Outlook.OlSensitivity.olConfidential

            'Setting the button state to reflect whether the email is secure or not
            Dim commandBar As Office.CommandBar
            Dim encryptButton As Office.CommandBarButton
            Dim decryptButton As Office.CommandBarButton

            commandBar = oApp.ActiveInspector.CommandBars("Standard")
            encryptButton = commandBar.FindControl(Tag:="EncryptMail")
            decryptButton = commandBar.FindControl(Tag:="DecryptMail")

            If Not (encryptButton Is Nothing) Then
                encryptButton.Visible = False
                decryptButton.Visible = True
                decryptButton.State = Office.MsoButtonState.msoButtonDown
            End If
        End Sub

        Private Sub decryptbutton_Click()
            'Changing email sensitivity
            oApp.ActiveInspector.CurrentItem.Sensitivity = Outlook.OlSensitivity.olNormal

            'Setting the button state to reflect whether the email is secure or not
            Dim commandBar As Office.CommandBar
            Dim encryptButton As Office.CommandBarButton
            Dim decryptButton As Office.CommandBarButton

            CommandBar = oApp.ActiveInspector.CommandBars("Standard")
            encryptButton = CommandBar.FindControl(Tag:="EncryptMail")
            decryptButton = CommandBar.FindControl(Tag:="DecryptMail")

            If Not (decryptButton Is Nothing) Then
                decryptButton.Visible = False
                encryptButton.Visible = True
                encryptButton.State = Office.MsoButtonState.msoButtonUp
            End If
        End Sub

        Public Function WriteToEventLog(ByVal Entry As String, Optional ByVal AppName As String = "VB.NET Application", Optional ByVal EventType As EventLogEntryType = EventLogEntryType.Information, Optional ByVal LogName As String = "Application") As Boolean
            Dim objEventLog As New EventLog()

            Try
                'Register the App as an Event Source
                If Not EventLog.SourceExists(AppName) Then
                    EventLog.CreateEventSource(AppName, LogName)
                End If

                objEventLog.Source = AppName

                objEventLog.WriteEntry(Entry, EventType)
                Return True
            Catch Ex As Exception
                Return False
            End Try
        End Function



    Ken Slovak MVP - Outlook
    Tuesday, November 27, 2012 2:54 PM
    Moderator
  • Hi Ken,

    Thanks for all of your advice.

    I finally figured out what was causing my remaining error message.  Feel a bit of an idiot now!!

    I was re-writing my code as you suggested an found i was still getting the error.  I then commented out all of the code that actually did anything so that all my add-in did was start up.  I still got the error message.

    That's when I noticed that the title bar of the error read "ConfidentialToolbar" not "SecureEmailAddin".  Then I twigged.  When I first started playing around with creating an Outlook add-in the first program I created was called ConfidentialToolbar.  I then abandoned it and started with clean code to create my current add-in.  However it was still hooked in to Outlook so that everytime Outlook started so did it.

    I have removed the hooks and deleted the source code as it is no longer needed.  I no longer get the error.

    Sorry I wasted your time on that second error, however your first bit of advice did fix my other error message so I have marked that as having fixed my issue. 

    Tuesday, November 27, 2012 3:59 PM