Sunday, October 14, 2012

Add error-handling to an InfoPath form

Problem: You have written code for an InfoPath form template and want to add error-handling to it.

You can add Try-Catch blocks to all public methods in the FormCode class and use a central error-handler to handle all errors that might take place.

To add error-handling to an InfoPath form:

1 - Add a button control to the view of the form template

2 - Add the following private method to the FormCode class

Private Sub HandleErrors(ByVal ex As Exception)

     System.Windows.Forms.MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK,    MessageBoxIcon.Error)

End Sub

3 - Add the following code to the button clicked event handler

  Try
                Dim mainDS As XPathNavigator = MainDataSource.CreateNavigator
                Dim noValue As String = mainDS.SelectSingleNode("//my:field1", NamespaceManager).Value
            Catch ex As Exception
                HandleErrors(ex)
            Finally
                'Perform any operation for clean up here
   End Try

In the code above "field1" does not exist on the main data source so after previewing the form you will get the following error message "Object reference not set to an instance of an object".

The code above works for an InfoPath Filler form but for a Browser form, modify the HandleErrors() method to log a message to the Windows Event log as follows:

Private Sub HandleErrors(ByVal ex As Exception)

            Dim source As String = "Infopath Browser Form"

            If Not System.Diagnostics.EventLog.SourceExists(source) Then
                System.Diagnostics.EventLog.CreateEventSource(source, "Application")
            End If

            Dim log As New System.Diagnostics.EventLog("Application")
            log.Source = source
            log.WriteEntry(ex.Message, System.Diagnostics.EventLogEntryType.Error)

  End Sub

If you get a request permission error when the form is trying to log the error than set the permission of the form to Full Trust and you will see the error logged on the Windows Event Log.

No comments:

Post a Comment

About Me

My photo
Toronto, Ontario, Canada
MBA, M.Sc. & MCP