Export (0) Print
Expand All

Lab 15: Managed Code Business Logic in InfoPath 2003

 

Microsoft Corporation

April 2004

Applies to:
    Microsoft® Office InfoPath™ 2003

Summary: Learn how to use managed code business logic for Microsoft InfoPath forms in Microsoft Visual Studio .NET 2003. Discover how to debug managed business logic using Visual Studio .NET 2003 and set up Microsoft .NET Framework Security for your InfoPath form. (10 printed pages)

Download the odc_INF03_Labs.exe sample file.

Contents

Prerequisites
Scenario

Lab Objective
Setup
Exercises
Conclusion

Level

300

Prerequisites

  • An understanding of Microsoft® Visual C#® or Microsoft Visual Basic® .NET
  • A familiarity with the Microsoft Visual Studio® .NET 2003 integrated development environment (IDE)
  • Completion of Lab 5
  • A familiarity with Microsoft Active Directory® directory service and Microsoft Exchange 2000

Scenario

The information technology (IT) department at Contoso is investigating adding business logic written in managed code to their sales reports. They plan to utilize functionality provided by the Microsoft .NET Framework classes in a form, while continuing to use the built-in, form-specific features (data validation, conditional formatting) of Microsoft Office InfoPath™ 2003.

Lab Objective

In this lab you learn about:

  • Integrating with Visual Studio .NET 2003
  • Debugging managed business logic using Visual Studio .NET 2003
  • Accessing .NET Framework Classes from InfoPath business logic
  • Setting up .NET Framework Security for your InfoPath form
  • Using roles in managed code

Setup

  • Visual Studio .NET 2003
  • Microsoft .NET Framework 1.1 (installed by default with Visual Studio .NET 2003)
  • Microsoft Office InfoPath .NET Programmability Support (installed by default if .NET Framework 1.1 is installed)
  • Microsoft Office InfoPath 2003 Toolkit for Visual Studio .NET

Exercises

Exercise 1: Hello, World

Using managed code business logic, InfoPath forms can call into the same InfoPath Object Model (OM) that is available from script. In this exercise, you learn how to display a simple alert dialog box using the InfoPath OM.

Before you can write managed code business logic in InfoPath, you must create an InfoPath project in Visual Studio .NET 2003:

To create an InfoPath project in Visual Studio .NET 2003

  1. Start Visual Studio .NET 2003.
  2. On the File menu, point to New, and then point to Project.
  3. Expand the Microsoft Office InfoPath Projects, and select Visual C# Projects.
  4. Name the project Lab15-1.
  5. Click OK.
  6. In Microsoft Office Project Wizard, click Finish.

    Click here for larger image.

    Figure 1. Create an InfoPath project in Visual Studio .NET 2003
  7. In the Microsoft Office Project Wizard, click Create new form template.
  8. Click Finish.

Now that you have created an InfoPath project, you are ready to add event handlers.

To add an OnClick event handler

  1. In InfoPath Designer, from the Design Tasks task pane, click Controls.
  2. In the Standard controls section, click the Button control to insert it into the view.
  3. Double-click the button to open the Button Properties dialog box.
  4. Change the Label field to Alert.
  5. Change the ID field to AlertID.
  6. Click Edit Form Code. Note that an OnClick event handler is added to the FormCode.cs file in Visual Studio.
  7. Close the Button property dialog box.

You can now populate the event handler with managed code that runs whenever the button is clicked.

To add form code to the event handler

  1. In the OnClick event handler, add the following code:
    thisXDocument.UI.Alert("Hello, World");
    
    

    Note that a Microsoft IntelliSense® window is displayed after each period (.) is typed.

    Click here for larger image.

    Figure 2. Add form code to the event handler
  2. On the Project menu, point to Preview, then click Default.
  3. In the Preview window, click Alert.

You have completed your first InfoPath form with managed code business logic. Next, learn how to add debugging breakpoints to your business logic.

To debug your code

  1. In Visual Studio .NET 2003, click the grey bar next to the line:
    thisXDocument.UI.Alert("Hello, World");
    

    A red circle appears to indicate that the runtime pauses at this breakpoint in your business logic.

  2. On the Debug menu, click Start (or press F5).
  3. In the Preview window, click Alert. Note that Visual Studio .NET is given focus, and the breakpoint line is highlighted.

    Click here for larger image.

    Figure 3. Debug your code
  4. From the Debug menu, click Step Over (or press F10) to continue stepping through the code.

The Alert code is executed, and an alert is shown in the InfoPath Preview window.

Exercise 2: Get the Current User's Username

By using the .NET Framework classes, you can take advantage of functionality that was not easily available in script. In this example, you learn how use the .NET Framework classes to get the current user's username.

To add an On Load event

  1. In Visual Studio .NET 2003, open the InfoPath project that you created in Exercise 1.
  2. On the View menu, click Data Source.
  3. Right-click the myFields node, and then click Add.
  4. In the Name field, type employee, then click OK.
  5. Drag the employee node into the view.
  6. On the Tools menu, click Programming, and then click On Load Event. The code in this event handler is called each time the form is loaded.

To add the code

  1. In the OnLoad event handler, type the following code:
    // store an XMLDOM node as a local variable
    IXMLDOMNode nodeEmployee = 
    thisXDocument.DOM.selectSingleNode("my:myFields/my:employee");
    if(nodeEmployee != null){
          if(nodeEmployee.text == ""){
             // if the employee name is blank when we load the form, 
             // populate the employee node with the current user name
    nodeEmployee.text = System.Environment.UserName;
    }
    }
    
    
  2. Compile and preview the form.

The employee text box is populated with your username. Next, learn how to use managed code in a real world scenario.

Exercise 3: Roles and Active Directory

Note   If your organization is not using Active Directory or Microsoft Exchange Server® 2000 or later, the code in this exercise does not run correctly.

Now that you are aware of some of the tools available to you, let's look at a more complex scenario.

The .NET Framework assembly System.DirectoryServices is used to make Lightweight Directory Access Protocol (LDAP) queries to Active Directory. This allows you to determine the current user's manager. You use this information on subsequent loads to display a different view (using Roles functionality) depending on whether the current user is the original employee who filled out the form, the employee's manager, or someone else.

To create an InfoPath project based on an existing form template

  1. Open Visual Studio .NET 2003.
  2. On the File menu, click New, and then click Project.
  3. Expand the Microsoft Office InfoPath Projects, and then click Visual C# Projects.
  4. Name the project Lab15-3.
  5. Click OK.
  6. In the Microsoft Office Project Wizard, click Open existing form template.
  7. Browse to the path to Lab 15 Form Template, and then click Finish.

The Roles functionality, as well as three views, are completed for you. For more information on Roles, see Lab 7.

To add a Reference to a .NET Assembly

  1. In Solution Explorer, right-click References, and then select Add References.
  2. On the .NET tab, click System.DirectoryServices.dll.
  3. Click Select.
  4. Click OK.
  5. At the top of your FormCode.cs file, add the following:
    using System.DirectoryServices;
    
    

To work with DirectoryServices

  1. In the InfoPath Designer, from the Tools menu, click Programming, and then click On Load Event.
  2. In your OnLoad event handler, add the following code:
    IXMLDOMNode nodeEmployee = 
    thisXDocument.DOM.selectSingleNode("my:SalesReport/my:salesRep");
    IXMLDOMNode nodeManager = 
    thisXDocument.DOM.selectSingleNode("my:SalesReport/my:manager");
    if(nodeEmployee.text == ""){
    // get current user name
    string strUserName = System.Environment.UserName;
       nodeEmployee.text = System.Environment.UserDomainName + "\\" + 
        strUserName;
       // if the manager field is blank, 
       // we should look one up using Directory Services
       if(nodeManager.text == ""){
          // search for user whose mailNickname is the logon name
          DirectorySearcher ds = new DirectorySearcher("(mailNickname=" 
            + strUserName + ")");
          SearchResult result = ds.FindOne();
          if(result == null){
             thisXDocument.UI.Alert("Error finding user" + 
               strUserName + " using Active Directory.");
             return;
          }
          DirectoryEntry employeeEntry = result.GetDirectoryEntry();
          // find manager's LDAP DN from the DirectoryEntry
          string strManagerDN = 
            employeeEntry.Properties["manager"].Value.ToString();
          // use the DN to create a new DirectoryEntry
          DirectoryEntry managerEntry = new DirectoryEntry
           ("LDAP://" + strManagerDN);
          // get the alias of the manager
          string strManagerAlias = 
           managerEntry.Properties["mailNickname"].Value.ToString();
          nodeManager.text = System.Environment.UserDomainName + 
           "\\" + strManagerAlias;
          }
       }         
    
    // now we set the default view the user sees based on their Role
    // their role is determined based on comparing the current login 
    // with the salesRep and manager nodes in the data source
    if(thisXDocument.Role == "Employee"){
       thisXDocument.ViewInfos["Employee View"].IsDefault = true;
    }
    else if(thisXDocument.Role == "Manager"){
       thisXDocument.ViewInfos["Manager View"].IsDefault = true;
    }
    else if(thisXDocument.Role == "Other"){
       thisXDocument.ViewInfos["Standard View"].IsDefault = true;
    }
    
    

To summarize, using LDAP queries, this code acquires the alias of the current user's manager, and populates the salesRep and manager nodes in the data source with their respective aliases.

Next, based on your current Role, we determine which view to display.

To grant your form template FullTrust permissions

In order to make calls into Active Directory, your form needs to be granted FullTrust Permissions.

You have four options for making your form fully trusted:

  • Use the .NET Framework 1.1 Configuration utility to grant FullTrust Permissions to your C# code only.
  • Use the RegForm utility from the InfoPath SDK to make your InfoPath form fully-trusted, which in turn grants FullTrust permissions to your C# code.
  • Digitally sign your form template (.xsn) file with a code signing certificate, which your users are prompted to trust when they open the form. This makes your form fully-trusted, and in turn grants FullTrust permissions to your C# code.
  • Use external automation in InfoPath to call the RegisterSolution() method. Note that this method is only good for form development since a registered form only registers for your individual computer. Any additional form users must register the same form on their own computer which is not recommended. When publishing your form, the previous three methods are preferred.

Since this form is still under development, use the fourth option, using external automation to call the RegisterSolution() method.

To create a JavaScript file that grants FullTrust permissions to form template

  1. In InfoPath Designer, on the Tools menu, and then click Form Options.
  2. Click Security.
  3. Clear the Automatically determine security level based on form's design (recommended) box.
    Note   InfoPath cannot automatically detect business logic that requires full trust permissions so we must explicitly give full trust permissions.
  4. Select Full Trust, and then click OK.
  5. Close InfoPath Designer. Click Yes if asked to save changes.
  6. In Visual Studio .NET 2003, in Solution Explorer, double-click the manifest.xsf file to open it.
  7. In the root node, look for the publishUrl attribute and remove it along with its value.
  8. Save your changes.
  9. In Visual Studio .NET 2003, on the Build menu, click Build Solution.
  10. Open Notepad (or any other text editor)
  11. Add the following code to a blank text file:
    oApp = WScript.CreateObject("InfoPath.ExternalApplication");
    strAbsolutePath = "project_folder_url\\manifest.xsf"
    oApp.RegisterSolution(strAbsolutePath,"overwrite");
    
    Note   Don't forget to escape your path to your manifest.xsf. All \ in your path should be replaced with \\.
  12. Save this file on your computer as register.js
  13. Double-click the register.js file that you just created.

Now you successfully registered your solution. It can run with FullTrust permissions on your computer when you open it by double-clicking the manifest.xsf from the project folder. This also grants ability to preview or debug with Full Trust through Visual Studio.

To test your form

Now let's take a look at how the form functions.

  1. Browse to project_folder_URL.
  2. Double-click the manifest.xsf file to begin filling out a form based on this form template.
    Note   Your user name and your manager's name are automatically populated by the code running in the OnLoad event.
  3. In the Customer Name field, type Northwind.
  4. On the File menu, click Save As.
  5. Name the form employee.xml and save it to your desktop.
  6. Re-open the form in InfoPath.
    Note   You are still in the Employee role, and are viewing the Employee view.

To see your manager's view

Now that we have seen how the form looks for an employee, let's test out what your manager sees when they open the form. To do this, change the data so that your user name appears in the Manager field.

To cause your user name to appear in the Manager field.

  1. Change the Sales Representative field to Domain\managerUsername.
  2. Change the Manager field to Domain\Username.
  3. Save the form as manager.xml and close the form.
  4. Re-open manager.xml in InfoPath.
    Note   You are now in the Manager role, and are viewing the Manager view. The employee's comments (Customer Name) are read-only in this view.

Conclusion

After completing this lab, you have an understanding of how to work with managed code business logic for InfoPath forms in Visual Studio .NET 2003. Here are some additional references to help you with your continued learning for writing business logic in managed code.

Show:
© 2014 Microsoft