Adding User Information from Active Directory Domain Services to InfoPath 2007 Forms

This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies. This page may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.

Summary: Learn how to retrieve information about the current user of a Microsoft Office InfoPath 2007 form template from Active Directory Domain Services and add the information to the form.

Office Visual How To

Applies to: 2007 Microsoft Office System, Microsoft Office InfoPath 2007

Mark Roberts, Microsoft Corporation

November 2007

Overview

This Microsoft Office Visual How To describes how to get information about the current user of a Microsoft Office InfoPath 2007 form template from Active Directory Domain Services by using the DirectorySearcher class and DirectoryEntry class of the System.DirectoryServices namespace.

See It Adding User Information to InfoPath 2007 Forms

Watch the Video

Length: 04:10 | Size: 3.65 MB | Type: WMV file

Code It | Read It | Explore It

Code It

The Microsoft.Office.InfoPath namespace provides the UserName property and the LoginName property of the User class. These properties let you retrieve the user name (and logon domain, if necessary) for a user from Active Directory Domain Services. You can also use the DirectorySearcher class and the DirectoryEntry class of the System.DirectoryServices namespace to obtain additional information about the user from Active Directory Domain Services.

To demonstrate this process, this section describes the following steps:

  • Creating an InfoPath form template that contains the fields in which to insert the data retrieved from Active Directory Domain Services.

  • Adding a Button control and Clicked event handler for testing the code that is used to get user information from Active Directory Domain Services and insert it into the fields on the form.

  • Adding a Loading event procedure that uses the same code to automatically fill in the fields when the form is opened.

  • Adding two fields and code to demonstrate how to enumerate all the attributes and values returned in the DirectoryEntry object for the current user.

Creating the Form

Before you can run the code for this demonstration, you must create an InfoPath form template that contains the fields in which to insert the data retrieved from Active Directory Domain Services.

To create a form to contain the user information

  1. In design mode, create a blank form template.

  2. On the Table menu, point to Insert, and then click Layout Table.

  3. Set Number of columns to 2, set Number of rows to 9, and then click OK.

  4. Drag nine Text Box controls from the Controls task pane into the cells in the second column of the layout table.

  5. Double-click each Text Box control, and rename the fields that are bound to the controls to the names in the following list.

    • FirstName

    • LastName

    • Alias

    • Email

    • Manager

    • Location

    • Title

    • TelephoneNumber

    • Department

  6. Type labels for each Text Box control in the first column of the layout table.

  7. Drag a Button control to a location below the nine text boxes, and then double-click the button. Change the Label to Get User Information, and then change the ID to GetUserInformation.

    The controls on your form template should look like the example in Figure 1.

    Figure 1. Text boxes and button for displaying user information

    Text boxes and button for displaying information

To allow form code to access user information in Active Directory Domain Services, the security level of the form must be set to Full Trust.

To set the form template to Full Trust

  1. On the Tools menu, click Form Options.

  2. In the Security and Trust category, clear the Automatically determine security level check box, and then click Full Trust.

  3. Click OK.

NoteNote

Setting the form to Full Trust is sufficient for previewing the form while you are testing it. When you deploy a form template that requires Full Trust, you must perform additional steps, such as digitally signing the form template or creating an installable form template. For information about how to do that, see "Deploying Form Templates That Require Full Trust" in How to: Deploy InfoPath Projects.

The following section describes how to add code to the button's event handler.

Adding the Code

To add user information to fields in the form's main data source, the code added to the Get User Information button's event handler performs the following operations:

  • Gets the user name for the current user by using the UserName property.

  • Creates a DirectorySearcher object, passing in the mailNickname attribute and the user name as the LDAP (Lightweight Directory Access Protocol) filter to specify the user to search for.

  • Uses the FindOne method to find the user, returning the result to a SearchResult object.

  • Confirms that the user was found, and then uses the GetDirectoryEntry method of the SearchResult class to save the collection of user properties to a DirectoryEntry object.

  • Retrieves the values of each of the nine specified properties from the PropertyCollection object of the DirectoryEntry object and saves them to string variables.

    For information about how to determine the names of the properties that are available in the collection, see the Adding Code to Enumerate the Attributes Available in Active Directory Domain Services section.

  • Creates an XPathNavigator object by using the CreateNavigator method, which positions the XPathNavigator at the root of the form's main data source.

  • Uses the SelectSingleNode method to select each field, and then sets its value by using the SetValue method.

For more information about using the XPathNavigator class to work in data in InfoPath form templates, see Working with XML Data Using the XPathNavigator Class in InfoPath 2007 Form Templates.

To add code to the Get User Information button

  1. Double-click the Get User Information button, and then click Edit Form Code to add code to the button's Clicked event handler. This opens the Visual Studio Tools for Applications development environment and adds an empty GetUserInformation_Clicked event handler.

    To use members of the System.DirectoryServices namespace in your form code, you must add a reference to its assembly in the Visual Studio Tools for Applications environment.

  2. On the Project menu, click Add Reference.

  3. On the .NET tab of the Add Reference dialog box, select System.DirectoryServices, and then click OK.

  4. At the top of the code module below the existing using statements, add the following statement

    using System.DirectoryServices;
    
  5. Locate the GetUserInformation_Clicked event handler and add the following code to it.

    try
    {
       // Get the user name of the current user.
       string userName = this.Application.User.UserName;
    
       // Create a DirectorySearcher object using the user name 
       // as the LDAP search filter. If using a directory other
       // than Exchange, use sAMAccountName instead of mailNickname.
       DirectorySearcher searcher = new DirectorySearcher(
          "(mailNickname=" + userName + ")");
    
       // Search for the specified user.
       SearchResult result = searcher.FindOne();
    
       // Make sure the user was found.
       if (result == null)
       {
          MessageBox.Show("Error finding user: " + userName);
       }
       else
       {
          // Create a DirectoryEntry object to retrieve the collection
          // of attributes (properties) for the user.
          DirectoryEntry employee = result.GetDirectoryEntry();
    
          // Assign the specified properties to string variables.
          string FirstName = employee.Properties[
             "givenName"].Value.ToString();
          string LastName = employee.Properties["sn"].Value.ToString();
          string Mail = employee.Properties["mail"].Value.ToString();
          string Location = employee.Properties[
             "physicalDeliveryOfficeName"].Value.ToString();
          string Title = employee.Properties["title"].Value.ToString();
          string Phone = employee.Properties[
             "telephoneNumber"].Value.ToString();
          string Department = employee.Properties[
             "department"].Value.ToString();
    
          // The manager property returns a distinguished name, 
          // so get the substring of the common name following "CN=".
          string ManagerName = employee.Properties[
             "manager"].Value.ToString();
          ManagerName = ManagerName.Substring(
             3, ManagerName.IndexOf(",") - 3);
    
          // Create an XPathNavigator to walk the main data source
          // of the form.
          XPathNavigator xnMyForm = this.CreateNavigator();
          XmlNamespaceManager ns = this.NamespaceManager;
    
          // Set the fields in the form.
          xnMyForm.SelectSingleNode("/my:myFields/my:FirstName", ns)
             .SetValue(FirstName);
          xnMyForm.SelectSingleNode("/my:myFields/my:LastName", ns)
             .SetValue(LastName);
          xnMyForm.SelectSingleNode("/my:myFields/my:Alias", ns)
             .SetValue(userName);
          xnMyForm.SelectSingleNode("/my:myFields/my:Email", ns)
             .SetValue(Mail);
          xnMyForm.SelectSingleNode("/my:myFields/my:Manager", ns)
             .SetValue(ManagerName);
          xnMyForm.SelectSingleNode("/my:myFields/my:Location", ns)
             .SetValue(Location);
          xnMyForm.SelectSingleNode("/my:myFields/my:Title", ns)
             .SetValue(Title);
          xnMyForm.SelectSingleNode(
             "/my:myFields/my:TelephoneNumber", ns)
             .SetValue(Phone);
          xnMyForm.SelectSingleNode("/my:myFields/my:Department", ns)
             .SetValue(Department);
    
          // Clean up.
          xnMyForm = null;
          searcher.Dispose();
          result = null;
          employee.Close();
       }
    
    }
    catch (Exception ex)
    {
       MessageBox.Show("The following error occurred: " + 
          ex.Message.ToString());
       throw;
    }
    
    Try
       ' Get the user name of the current user.
       Dim userName As String = Me.Application.User.UserName
    
       ' Create a DirectorySearcher object using the user name
       ' as the LDAP search filter. If using a directory other
       ' than Exchange, use sAMAccountName instead of mailNickname.
       Dim searcher As DirectorySearcher = New DirectorySearcher( _
          "(mailNickname=" + userName + ")")
    
       ' Search for the specified user.
       Dim result As SearchResult = searcher.FindOne()
    
       ' Make sure the user was found.
       If result Is Nothing Then
           MessageBox.Show("Error finding user: " + userName)
       Else
          ' Create a DirectoryEntry object to retrieve the collection
          ' of attributes (properties) for the user.
          Dim employee As DirectoryEnTry = result.GetDirectoryEnTry()
    
          ' Assign the specified properties to string variables.
          Dim FirstName As String = employee.Properties( _
             "givenName").Value.ToString()
          Dim LastName As String = employee.Properties( _
             "sn").Value.ToString()
          Dim Mail As String = employee.Properties( _
             "mail").Value.ToString()
          Dim Location As String = employee.Properties( _
             "physicalDeliveryOfficeName").Value.ToString()
          Dim Title As String = employee.Properties( _
             "title").Value.ToString()
          Dim Phone As String = employee.Properties( _
             "telephoneNumber").Value.ToString()
            Dim Department As String = employee.Properties( _
             "department").Value.ToString()
    
          ' The manager property returns a distinguished name, 
          ' so get the substring of the common name following "CN=".
          Dim ManagerName As String = employee.Properties( _
            "manager").Value.ToString()
          ManagerName = ManagerName.Substring( _
             3, ManagerName.IndexOf(",") - 3)
    
          ' Create an XPathNavigator to walk the main data source
          ' of the form.
          Dim xnMyForm As XPathNavigator = Me.CreateNavigator()
          Dim ns As XmlNamespaceManager = Me.NamespaceManager
    
          ' Set the fields in the form.
          xnMyForm.SelectSingleNode("/my:myFields/my:FirstName", ns) _
             .SetValue(FirstName)
          xnMyForm.SelectSingleNode("/my:myFields/my:LastName", ns) _
             .SetValue(LastName)
          xnMyForm.SelectSingleNode("/my:myFields/my:Alias", ns) _
             .SetValue(userName)
          xnMyForm.SelectSingleNode("/my:myFields/my:Email", ns) _
             .SetValue(Mail)
          xnMyForm.SelectSingleNode("/my:myFields/my:Manager", ns) _
             .SetValue(ManagerName)
          xnMyForm.SelectSingleNode("/my:myFields/my:Location", ns) _
             .SetValue(Location)
          xnMyForm.SelectSingleNode("/my:myFields/my:Title", ns) _
             .SetValue(Title)
          xnMyForm.SelectSingleNode("/my:myFields/my:TelephoneNumber", _
             ns).SetValue(Phone)
          xnMyForm.SelectSingleNode("/my:myFields/my:Department", ns) _
             .SetValue(Department)
    
          ' Clean up.
          xnMyForm = Nothing
          searcher.Dispose()
          result = Nothing
          employee.Close()
       End If
    
    Catch ex As Exception
       MessageBox.Show("The following error occurred: " + _
          ex.Message.ToString())
       Throw
    End Try
    

With the code in place, you can now preview the form to confirm that it works.

Important noteImportant

For the following code to work, you must be logged on to a network that uses Active Directory Domain Services to store user information.

To preview the form and test the code

  1. Switch back to Office InfoPath 2007.

  2. On the Standard toolbar, click Preview.

  3. To run the code, click Get User Information.

    The fields in the form should fill with your user information from Active Directory Domain Services.

  4. Click Close Preview.

Adding Code to the Loading Event Handler

In a more typical scenario, you want the user's information filled in automatically when the form is opened. To do that, you can copy the code from the button event handler to the Loading event handler of the form template.

To add the code to the Loading event handler

  1. On the Tools menu, point to Programming, and then click Loading Event.

  2. Copy the code from the GetUserInformation_Clicked event handler into the FormEvents_Loading event handler.

  3. Switch back to Office InfoPath 2007.

  4. On the Standard toolbar, click Preview.

    When the form opens, the fields in the form should automatically fill with your information from Active Directory Domain Services.

  5. Click Close Preview.

Adding Code to Enumerate the Available Attributes

To view all the attributes that are available for the current user in Active Directory Domain Services, you can add fields and code that display the names of the attributes and their values in the form.

To add fields to display attributes and their values

  1. Switch back to Office InfoPath 2007.

  2. On the View menu, click Data Source.

  3. In the Data Source pane, click Add a Field or Group.

  4. In the Add Field or Group dialog box, in the Name box, type gpProperties, set Type to Group, and then click OK.

  5. Right-click gpProperties, and then click Add.

  6. In the Name box, type gpProperty, set Type to Group, select the Repeating check box, and then click OK.

  7. Right-click gpProperty, and then click Add.

  8. In the Name box, type PropertyName, leave Type as Field (element) and Data type as Text (string), and then click OK.

  9. Right-click gpProperty, and then click Add.

  10. In the Name box, type PropertyValue, leave Type as Field (element) and Data type as Text (string), and then click OK.

  11. Drag gpProperty from the Data Source pane to a location below the Get User Information button.

  12. From the pop-up menu, select Repeating Table.

  13. Drag a Button control to a location below the Repeating Table, double-click the control, and then change the Label to List All Properties and change the ID to ListAllProperties.

    The controls added to your form template should look like the example in Figure 2.

    Figure 2. Text boxes and button for enumerating attributes

    Text boxes and button for enumerating atttributes

To display the enumerated attributes, add code to the button's Clicked event hander. The code for this event handler is similar to the code to set individual field values. However, instead of specifying which properties to retrieve, it loops through the entire PropertiesCollection object that is returned for the current user and displays each property's name in the text box bound to the PropertyName field and each property's value in the text box bound to PropertyValue field.

To add code to display attributes and their values

  1. Double-click the List All Properties button, and then click Edit Form Code to add code to the button's Clicked event handler. This opens the VSTA development environment, and adds an empty ListAllProperties_Clicked event handler.

  2. Add the following code to the ListAllProperties_Clicked event handler.

    // Get the user name of the current user.
    string userName = this.Application.User.UserName;
    
    // Create a DirectorySearcher object using the user name
    // as the search filter.
    DirectorySearcher searcher = new DirectorySearcher(
       "(mailNickname=" + userName + ")");
    
    // Create a DirectoryEntry object and retrieve the properties 
    // for the user.
    DirectoryEntry employee = searcher.FindOne().GetDirectoryEntry();
    
    // Create an XPathNavigator to walk the form's data source.
    XPathNavigator xnDoc = this.MainDataSource.CreateNavigator();
    XmlNamespaceManager ns = this.NamespaceManager;
    
    // Create XPathNavigators for setting values in
    // the properties table.
    XPathNavigator xnPropertiesTable = null;
    XPathNavigator xnPropertyName = null;
    XPathNavigator xnPropertyValue = null;
    
    // Loop through properties and display their values in
    // the properties table.
    foreach (string userProperty in employee.Properties.PropertyNames)
    {
        try
        {
            xnPropertiesTable = xnDoc.SelectSingleNode(
               "/my:myFields/my:gpProperties[last()]/my:gpProperty",
               ns);
            xnPropertyName = xnPropertiesTable.SelectSingleNode(
               "my:PropertyName", ns);
            xnPropertyValue = xnPropertiesTable.SelectSingleNode(
               "my:PropertyValue", ns);
            xnPropertyName.SetValue(userProperty);
            xnPropertyValue.SetValue(
               employee.Properties[userProperty].Value.ToString());
            xnPropertiesTable.InsertBefore(xnPropertiesTable.OuterXml);
        }
    
        catch (Exception)
        {
            xnPropertyValue.SetValue("Value cannot be displayed");
        }
    }
    
    // Clean up.
    searcher.Dispose();
    employee.Close();
    xnDoc = null;
    xnPropertiesTable = null;
    xnPropertyName = null;
    xnPropertyValue = null:
    
    ' Get the user name of the current user.
    Dim userName As String = Me.Application.User.UserName
    
    ' Create a DirectorySearcher object using the user name
    ' as the search filter.
    Dim searcher As DirectorySearcher = New DirectorySearcher( _
       "(mailNickname=" + userName + ")")
    
    ' Create a DirectoryEntry object and retrieve the properties 
    ' for the user.
    Dim employee As DirectoryEntry = searcher.FindOne().GetDirectoryEnTry()
    
    ' Create an XPathNavigator to walk the form's data source.
    Dim xnDoc As XPathNavigator = Me.MainDataSource.CreateNavigator()
    Dim ns As XmlNamespaceManager = Me.NamespaceManager
    
    ' Create XPathNavigators for setting values in
    ' the properties table.
    Dim xnPropertiesTable As XPathNavigator = Nothing
    Dim xnPropertyName As XPathNavigator = Nothing
    Dim xnPropertyValue As XPathNavigator = Nothing
    
    ' Loop through properties and display their values in
    ' the properties table.
    Dim userProperty As String
    For Each userProperty In employee.Properties.PropertyNames
        Try
            xnPropertiesTable = xnDoc.SelectSingleNode( _
               "/my:myFields/my:gpProperties[last()]/my:gpProperty", ns)
            xnPropertyName = xnPropertiesTable.SelectSingleNode( _
              "my:PropertyName", ns)
            xnPropertyValue = xnPropertiesTable.SelectSingleNode( _
               "my:PropertyValue", ns)
            xnPropertyName.SetValue(userProperty)
            xnPropertyValue.SetValue( _
               employee.Properties(userProperty).Value.ToString())
            xnPropertiesTable.InsertBefore(xnPropertiesTable.OuterXml)
        Catch
            xnPropertyValue.SetValue("Value cannot be displayed")
        End Try
    Next
    
    ' Clean up.
    searcher.Dispose()
    employee.Close()
    xnDoc = Nothing
    xnPropertiesTable = Nothing
    xnPropertyName = Nothing
    xnPropertyValue = Nothing
    

With the code in place, you can now preview the form to confirm that it works.

Important noteImportant

For this code to work, you must be logged on to a network that uses Active Directory Domain Services to store user information.

To preview the form and test the code

  1. Switch back to Office InfoPath 2007.

  2. On the Standard toolbar, click Preview.

  3. To run the code, click List All Properties.

    The left column lists the names of all the attributes that are available for the current user. The right column lists the values of the corresponding attribute in the left column.

    NoteNote

    Some of the values in the right column are not strings and cannot be displayed in a Text Box control. In that case, the type name of the value, such as System.Object[], System.__ComObject, or System.Byte[] is displayed instead.

  4. Click Close Preview.

Read It

This Office Visual How To demonstrates how to retrieve information about the current user from Active Directory Domain Services and automatically fill in fields with that information when an InfoPath 2007 form loads. The key steps for performing this process are as follows:

  1. Adding the Text Box controls and fields to display and store the user's information.

  2. Writing code that uses DirectorySearcher and DirectoryEntry classes of the System.DirectoryServices namespace to get user information from Active Directory Domain Services.

  3. Writing code that uses the XPathNavigator class of the System.Xml.XPath namespace to write those values to fields in the form's main data source.

This article also demonstrates how to enumerate the properties of the PropertyCollection object that is returned for the current user so that you can view the names of Active Directory attributes that are available.

Explore It

Acknowledgments

I would like to thank Scott Heim for his contributions to this article.