|   Register   |  
Search  

Powering Office 2003 with XML

Last Updated 2/3/2009 3:43:01 PM


Abstract
This chapter from "Powering Office 2003 with XML" by Peter G. Aitken discusses what's new in Microsoft Office 2003, and it talks about the importance of interoperability. After reading this chapter, you'll understand how Office exchanges information with other programs and you'll know XML's role in Excel, Access, and InfoPath.


SCRIPTING IS a technology that enables you to include program code in an InfoPath form. Not all forms require scripting, but for certain more complex and sophisticated InfoPath applications, you can use script to obtain functionality that is not otherwise available. This chapter provides an overview and some examples of scripting in InfoPath.


SCRIPTING OVERVIEW



Script is computer code that is associated with a form. The code is executed when certain events occur, such as a button on the form being clicked, data in a field being changed, or the user switching to a different view. Script code has access to many of the inner workings of an InfoPath form, including its data. Some of the simpler things you can do with script include:
  • Inserting today's date in a form field when the form is opened
  • Performing complex calculations using form data
  • Preventing the user from closing a view if a certain field is blank
  • Performing certain kinds of data validation that are difficult or not possible using other validation methods
  • Displaying one view or another based on data in the form when the form is loaded
  • Adding an element to the data source if it is not already present
Scripts can perform much more sophisticated actions as well. Script code can use COM (Component Object Model) components such as ActiveX objects, and because the Windows operating system itself and most applications are also based on COM, this provides the potential for a lot of power.

Scripting opens a lot of possibilities for the InfoPath form developer. It is not a simple topic, however. To write scripts you need some background knowledge in several technologies, which are detailed in the next section. It is well beyond the scope of this book to cover these related technologies or, in fact, to cover scripting in its entirety. Instead, this chapter provides an overview of scripting and some examples of how you could use it in your forms.


BACKGROUND INFORMATION



Because InfoPath scripting is based on several technologies, the InfoPath script programmer needs to have a good grounding in several areas, including:
  • The scripting language. InfoPath supports two scripting languages, VBScript and JScript. You need to know the syntax and elements of at least one of these languages.
  • The Document Object Model (DOM). The DOM provides an interface between the script and the data source (XML document). In a script you use DOM objects, methods, and properties to access the form's data.
  • XPath. This is a vocabulary designed for identifying specific elements in an XML document. When you use the DOM to manipulate the data source, you will often use an XPath expression to identify the part of the data source to be acted upon.
  • The InfoPath object model. InfoPath exposes its own object model that script code uses to access InfoPath components, such as task panes, controls, and views.
The Microsoft Script Editor online help provides a great deal of useful information, including both VBScript and JScript language references, an InfoPath Developer's Reference, and debugging information. This should be the first place that you turn for assistance when working with scripts in InfoPath.


SETTING THE SCRIPTING LANGUAGE



InfoPath supports two script languages, VBScript and JScript. A specific InfoPath form can use only one of these languages, and you must set this option before editing or viewing the form's script. To do so:
  1. With the form open in design mode, choose Tools''Form Options to display the Form Options dialog box.
  2. Click the Advanced tab.
  3. In the Script Language section of the dialog box, select the desired language from the drop-down list.
  4. Click OK to close the dialog box.
If you forget to set the script language, it defaults to JScript. Be aware that many of the sample forms that are provided with InfoPath already contain script, and if you are designing a new form based on one of these samples, you're stuck with the sample form's script language (usually JScript). Some of the examples in this chapter use VBScript and others use JScript. If you know one language, it shouldn't be too difficult to translate code from the other.

Please note that the Script Editor is not automatically included in all InfoPath installations. If it isn't installed on your system, then the first time you try to use it you'll be prompted to install it. Simply follow the prompts to complete the installation and then continue.


THE SCRIPT EDITOR



You use the Microsoft Script Editor (see Figure 6-1) to create and edit scripts for InfoPath forms. While you're designing a form, you can open the Script Editor by choosing Tools→Script→Script Editor or by pressing Alt-Shift-F11. The Script Editor also opens automatically at other times when it is needed, as you'll see later. There are three areas of the screen with which you will be most concerned:
  • The Document Outline on the left side of the screen, which lists all of the procedures and functions in the current form (only a single one in this case). Double-click a procedure or function name in this window to display it for editing.
  • The editing window in the middle of the screen, which displays the form's script code. If more than one form is open for design (as in the figure), each one's code is on its own tabbed page in this part of the screen.
  • The Project Explorer at the top right of the screen, which lists the open forms. In the figure there are two, Template1 and Template2.
Each form in the Project Explorer has a script file associated with it, named Script.js or Script.vbs, depending on whether JScript or VBScript is the selected script language for the form. You won't find this file on your disk, however, because all of the files that comprise the definition of a form are combined into a single XSN file.

InfoPath XSN Files
An InfoPath template is stored as a single file with the XSN extension. In reality, this file is a CAB (cabinet) file that contains, in compressed format, the various individual files that comprise a form template, including but not limited to the following:
  • A schema file (XSD) for the form's data model
  • A stylesheet (XSL) that defines the form's views and transformations
  • A script file (JS or VBS) that holds the form's script (if any)
  • Bitmap and other image files for images that are part of the form's user interface
You can extract the individual files for a form template by choosing File'' Extract Form Files while designing a form.

The Script Editor is used for a variety of purposes by Microsoft and is not designed specifically for use with InfoPath. As a result it has many features and commands that aren't relevant for InfoPath form scripts, and those items won't be available to you (for example, a menu command might be grayed out).

When you are editing a script, you can save it by choosing File→Save in the Script Editor. Saving the form template from InfoPath has the same effect of saving changes to the script.


INFOPATH EVENTS



An event is something that the user triggers while filling out an InfoPath form, such as clicking a button on the form, changing the data in a field, or merging a form. If you want script to be executed when an event occurs, you must create an event handler (also called an event procedure) for the event and put the script there. If there is no event handler for an event, it is ignored (as far as script processing is concerned).

InfoPath events are divided into three categories: form-level, data validation, and OnClick. These are discussed in the following sections, which also explain the techniques you use to create a handler for each type of event. Examples for selected events are presented later in the chapter.

Form-Level Events


Form-level events are so named because they occur when something happens to the form as a whole rather than to a component of the form. These events are:
  • OnLoad. Occurs when the form is opened, either when creating a new form from a template or when opening an existing form that has been saved
  • OnSwitchViews. Occurs when the user switches views
  • OnVersionUpgrade. Occurs when the version number of the form being opened does not match the version number of the template in use
  • OnSubmitRequest. Occurs when a form is submitted
You must create an event handler to respond to any of these events. Although in theory you can type the outline of an event handler into the Script Editor, it's better to let InfoPath do it for you, eliminating the possibility of typos and other errors. It's easier and faster, too! Table 6-1 shows how. While you are designing a form in InfoPath, you can perform any action listed in the table and InfoPath will open the Script Editor and insert the outline of the designated event handler. You can then proceed to add the script to be executed when the event occurs.

Data Validation Events


Data validation events are, as their name implies, typically used to validate data. They are associated with elements in the data source. There are three of these events — OnBeforeChange, OnValidate, and OnAfterChange — and they occur, in the order given, when the data in the underlying XML document (the data source) changes. From the user's perspective, this means when the data in a form control is changed. It's important to remember, however, that the events are associated with the data source and not with the controls on the form.

Here's how the data validation events are used:
  • OnBeforeChange occurs when the change has been made but not yet accepted or finalized. Code in this event procedure can examine the new data value and, if it doesn't meet the form's requirements, reject it and keep the old data value.
  • OnValidate occurs after OnBeforeChange, when the change has still not been finalized. It is like OnBeforeChange in that code examines the data value to see if it is acceptable. It differs from OnBeforeChange in that it does not offer the ability to automatically roll back the data to the previous value. Rather, it lets you display a validation error message to users to prompt them to fix the data.
  • OnAfterChange occurs when the change has been accepted and finalized. It is typically used to perform calculations or other updates to the form based on the new data. Strictly speaking, this event really isn't used for data validation but rather to initiate some action after the data has been accepted.
The way that the InfoPath event model works results in these events being called twice in some situations. For example, suppose the user tabs to a field, deletes the data that is already there, and then enters new data. The OnBeforeChange, OnValidate, and OnAfterChange events are triggered twice, once in response to the delete and once in response to the new data being entered. Code in the event procedures must take this possibility into account. The code must also take into account the possibility that the change is the result of an undo or redo operation. I'll show you how this is done in the examples later in the chapter.

Note: When an OnBeforeChange or OnValidate event procedure is executing, the data source is locked so that no changes can be made to it.This prevents the endless sequence of events that could occur if code in one OnBeforeChange or OnValidate event procedure makes changes to the data, which in turn triggers another OnBeforeChange/OnValidate event sequence. The data source is not locked, however, during the OnAfterChange event procedure.

To create a data validation event handler, follow these steps:
  1. Display the Data Source task pane.
  2. Right-click the element that you want the event associated with and select Properties from the pop-up menu to display the Field or Group Properties dialog box.
  3. Click the Validation and Script tab (see Figure 6-2).
  4. In the Script section, pull down the Events list and select the desired event: OnBeforeChange, OnValidate, or OnAfterChange.
  5. Click the Edit button.
An element in the data source can have handlers for one, two, or all three of the data validation events.

The OnClick event


The OnClick event is in a category by itself. It is relevant for the Button control, and is triggered when the user clicks a button. To create the OnClick event procedure for a button, the button must already be on the form. Then:
  1. Right-click the button and select Button properties from the pop-up menu to display the Button properties dialog box.
  2. Click the General tab (see Figure 6-3).
  3. Select Script in the Action list.
  4. Enter the button's caption (the text displayed on the button) in the Label field.
  5. Click the Microsoft Script Editor button.
Notice the Script ID field just below the Label field in the figure. This is the name that will be used to refer to the button in script. You can accept the default name that InfoPath suggests, or you can enter a more descriptive name. When you assign descriptive names, the resulting script code is easier to read because it is clear which button each procedure is attached to.

Event Procedure Arguments


Every event procedure is passed a single argument named eventObj, which makes relevant information available to the code in the event procedure. The type of object passed in the argument depends on the specific event procedure. Table 6-2 lists these objects and provides a brief description of each.

You'll see some of these objects used the example scripts presented later in this chapter. You can find more information about them in the Object Browser (discussed in the chapter) and in the Script Editor online help.


THE INFOPATH OBJECT MODEL



Like all other Office applications, InfoPath has an object model that describes the objects the program exposes. These objects are the components that make up the InfoPath application itself. When an object is exposed, its methods and properties are made available to other programs — in this case, the script code that can be part of an InfoPath form. Two of the more important elements in the InfoPath object model are the Window object, which provides access to the InfoPath user interface, and the XDocument object, which provides access to the underlying XML document (the data source). Table 6-3 summarizes the InfoPath object model.

Detailed coverage of the entire InfoPath object model is well beyond the scope of this book. You'll see some of the objects used in the examples presented later in this chapter. You can find information about the InfoPath objects and their properties and methods in the InfoPath online help, and you can also use the Object Browser, described in the next section, for assistance.


USING THE OBJECT BROWSER



You can use the Object Browser to obtain information about the contents of the InfoPath object model. To display the Object Browser from the Script Editor, choose View→Other Windows→Object Browser. The object model displays in the browser as shown in Figure 6-4.

If the object model doesn't display, follow these steps to load it:
  1. Be sure that Selected Components is selected in the Browse list.
  2. Click the Customize button to display the Selected Components dialog box.
  3. Open the Other Packages and Libraries node. If Microsoft Office InfoPath 1.0 Type Library is displayed in the list, select its check box, and click OK. If it isn't, continue to the next step.
  4. Click the Add button to display the Component Selector dialog box. Depending on your system, this dialog box may take a moment or two to load.
  5. On the COM tab, scroll down and click the Microsoft Office InfoPath 1.0 Type Library entry.
  6. Click the Select button to move the library to the Selected Components list.
  7. Click OK to return to the Selected Components dialog box. Microsoft Office InfoPath 1.0 Type Library is now listed.
  8. Click OK to close the dialog box and return to the Object Browser.
The left pane in the Object Browser lists the library's objects. The three categories of objects — classes, interfaces, and enumerations — are identified by the icon next to the object name. When you click an item in the object list, the pane on the right lists the object's members. The object's properties, methods, and events are distinguished by icons in the Members list.

When you select an item in the Members list, the panel at the bottom of the Object Browser window displays details about the selected member. For example, Figure 6-5 shows the details about the GetDataVariable method of the XDocument object. This information includes the method's argument and return value.


SCRIPTS AND SECURITY



A script has the potential to cause a lot of mischief on a user's system. For example, a script can use the FileSystemObject to read, write, and delete files. Clearly you do not want to allow just any script to run — you need some way to differentiate forms whose scripts should be allowed access to the system's files and settings from other forms. The InfoPath security model is similar to that used by Internet Explorer browser; it uses the concept of trusted versus standard forms.

To use an InfoPath form, InfoPath must have access to the template on which the form is based. By default, the form definition file contains the URL of the template. A form that's URL-based this way is said to be sandboxed. When it is filled out, the form is placed in the local cache and its permissions are based on the domain in which it is opened. Thus, script in a sandboxed or standard form typically cannot access system files or resources. Any attempt to do so will result in a permission denied error.

A form can be created so that is it based on a URN (Uniform Resource Name) rather than a URL. This, combined with a custom installation program for the form template, makes a form fully trusted. As such, the script in the form has access to the system's settings and files. Trusted forms are listed on the Custom Installed Forms tab in the Forms dialog box (displayed when the user selects More Forms on the Fill Out a Form task pane).

InfoPath provides a command-line utility called RegForm that you use to convert a standard form into a trusted form. This utility makes the necessary changes to the form and creates the installation program. Please refer to InfoPath help for more information on trusted forms and using this utility.


DEBUGGING SCRIPTS



Scripts, particularly more complex ones, almost never work right the first time. You can use the Script Editor to debug your script. The debugging tools that are available greatly simplify the task of locating and fixing problems in your script code.

To use script debugging, you must make sure that it is not disabled in Internet Explorer. To do so:
  1. Start Internet Explorer.
  2. Choose Tools→Internet Options to display the Internet Options dialog box.
  3. Click the Advanced tab.
  4. If present, clear the check next to the Disable Script Debugging option.
  5. Click OK.
Debugging is based on the concept of suspending the execution of the script. While execution is paused you can examine the value of variables and execute subsequent code a line at a time (called single stepping) to find the source of the problem. A script pauses on two conditions: when an actual error occurs, and when a break statement is encountered. The break statement is debugger in JScript and Stop in VBScript. For example, here are Load event procedures in both languages with a break statement:
function XDocument::OnLoad(eventObj)
{
debugger;
}
Sub XDocument_OnLoad(eventObj)
Stop
End Sub
You would not, of course, use a break statement by itself in a Load event procedure (or elsewhere). You would place it with other code that you suspect might be the location of the problem you are trying to fix. You can have multiple break statements in a form's script.

When an executing script encounters an error or a break statement, the Just-In- Time Debugging dialog box (see Figure 6-6) is displayed.

Select New Instance of Microsoft Script Editor and click Yes. The next dialog box asks you the program type that you want to debug. Put a check mark next to Script, and click OK.

At this point the Script Editor opens and displays the script code where the error occurred or where the break statement is located. A yellow arrow in the left margin indicates the line of code at which execution is paused. You can now use the Script Editor's debugging commands to examine program variables and control execution to try to locate the problem. When you are finished debugging, choose Debug→Stop Debugging.



Page: 1, 2

next page

Rate this:
Recent Comments
There are currently no comments. Be the first to make a comment.