You are on page 1of 324

IBM Software Services for Lotus

Using LotusScript® in IBM® Lotus® Domino™ Applications


Instructor Guide

Preview
Copyright, Disclaimer of Warranties and Limitation of Liability

© Copyright IBM Corporation 2003.

Lotus software, IBM Software Group


One Rogers Street
Cambridge, MA 02142

All rights reserved. Printed in the United States.

IBM, LearningSpace, Lotus, Lotus Notes, LotusScript, Sametime, and TeamRoom are registered trademarks and
Domino, Domino.Doc, Domino Extended Search, Domino Workflow, K-station, Notes, QuickPlace, and the e-business
logo are trademarks of International Business Machines Corporation. All other product or brand names may be
trademarks of their respective companies.

You must purchase one copy of the appropriate kit for each student and each instructor. For all other education products
you must acquire one copy for each user.

You may not copy, reproduce, translate, or reduce to any electronic medium or machine-readable form, in whole or in
part, any documents, software, or files provided to you without prior written consent of IBM Corporation, except in the
manner described in the documentation.

While every reasonable precaution has been taken in the preparation of this manual, the author and publishers assume
no responsibility for errors or omissions, nor for the uses made of the material contained herein and the decisions based
on such use. Neither the author nor the publishers make any representations, warranties, or guarantees of any kind,
either express or implied (including, without limitation, any warranties of merchantability, fitness for a particular purpose,
or title). Neither the author nor the publishers shall be liable for any indirect, special, incidental, or consequential
damages arising out of the use or inability to use the contents of this book, and each of their total liability for monetary
damages shall not exceed the total amount paid to such party for this book.

The term ‘Preview’ in the document header, denotes that this education manual has not been copyedited,
formatted or otherwise quality tested for final print production. This manual has been prepared for the purpose
of providing you with a preliminary version of the final courseware. This manual shall become obsolete with the
availability of the final version of the courseware.

IBM offers the widest range of server platforms for Lotus Domino, including the Intel processor-based Netfinity server
family. With Netfinity servers, solutions ranging from simple e-mail to unified messaging to Web site hosting and
collaborative applications such as distance learning and knowledge management are confidently executed. Both the
Quality Assurance Engineering and Curriculum Development departments, within Lotus' education line of business,
utilize Netfinity servers to develop and test the company's education offerings. Domino's functionality combined with the
IBM mark of reliability on the Netfinity product family differentiates Lotus from its competition. With more than 70% of
the world’s data residing on IBM systems, and with the innovative software products and services from Lotus
Development, IBM and Lotus are taking connectivity to a new level in all aspects of business — from document
management to e-business.
Preview

Table of Contents

T o pi c Page #

Course Description and Strategy ..........................................................1


Course Description ........................................................................................... 2
Course Strategy ................................................................................................ 4

Instructor Preparation ............................................................................7


Course Materials .............................................................................................. 8
Preparation Checklist ....................................................................................... 9
CLI Certification Requirements ....................................................................... 12

Classroom Setup ..................................................................................13


Machine Requirements ................................................................................... 14
Classroom Setup Overview ............................................................................ 16
Classroom Setup Instructions ......................................................................... 17

Module A: Using LotusScript to Access and Modify


Databases Programmatically ...............................................................21
Lesson 1 Introducing LotusScript ............................................................... 22
Introducing LotusScript ................................................................................ 24
Declaring Variables in LotusScript ............................................................... 28
Choosing a Data Type Exercise .................................................................. 32
Assigning Variables in LotusScript .............................................................. 34
Commenting Code ....................................................................................... 42
Using the LotusScript Debugger .................................................................. 44
Lesson 2 Accessing Database Information ................................................. 52
Exploring the Domino Objects ..................................................................... 54
Creating Objects in LotusScript ................................................................... 58
Accessing Object Properties ....................................................................... 64
Adding Simple Error Checking to Code ....................................................... 68
Accessing the Current Database ................................................................. 72
Creating a Database Based on Another Database ..................................... 74
Creating a New Copy of a Database Exercise ............................................ 76
Lesson 3 Navigating the Domino Object Model to Access ACL Information 78
Retrieving the Access Level of an ACL Entry .............................................. 80
Retrieving Your Access Level Exercise ....................................................... 92

Module B: Navigating the User Interface Classes .............................93


Lesson 4 Working with NotesUIWorkspace ................................................ 96
Programming the Notes User Interface ....................................................... 98
Adding a Database to the Workspace ....................................................... 102
Gathering User Input ................................................................................. 108
Asking for User Input Exercise .................................................................. 112
Lesson 5 Working with NotesUIDocument ............................................... 114
Accessing the Current Document .............................................................. 116
Composing a New Document with LotusScript ......................................... 120
Preview

Table of Contents

T o pi c Page #

Retrieving Field Values from the Current Document ................................. 122


Changing Field Values on the Current Document ..................................... 124
Accessing the Current Document Through NotesUIDocument Events ..... 128
Interacting with Users Programmatically Exercise .................................... 134

Module C: Creating and Modifying Documents ...............................137


Lesson 6 Accessing Data in Documents .................................................. 138
Accessing Documents with LotusScript ..................................................... 140
Retrieving Document Properties ................................................................ 144
Retrieving Item Values from a Document .................................................. 146
Looping Through Documents in a View ..................................................... 152
Accessing Data Directly from the View ...................................................... 162
Lesson 7 Writing Data to Documents ....................................................... 170
Adding and Replacing Items ...................................................................... 172
Saving the Document ................................................................................ 178
Synchronizing with the User Interface ....................................................... 180
Adding Author and Reader Items .............................................................. 190
Creating New Documents .......................................................................... 194
Creating a Report Document Exercise ...................................................... 200
Lesson 8 Using ViewEntry and Document Collections ............................. 202
Building Arrays .......................................................................................... 204
Building Dynamic Arrays ........................................................................... 208
Using the NotesViewEntryCollection Class ............................................... 216
Using NotesViewNavigator ........................................................................ 222
Using the NotesDocumentCollection Class ............................................... 230

Module D: Reusing Code and Processing Run-Time Errors ..........239


Lesson 9 Reusing Code ........................................................................... 240
Defining the Scope of a Variable ............................................................... 242
Setting Global Variables ............................................................................ 246
Exercise: Modify code to run more efficiently ............................................ 250
Building Functions ..................................................................................... 252
Building Subroutines .................................................................................. 256
Building Script Libraries ............................................................................. 258
Using Script Libraries ................................................................................ 260
Lesson 10 Processing Run-Time Errors ..................................................... 264
Processing Run-Time Errors ..................................................................... 266
Processing Individual Errors ...................................................................... 274

Appendix A: Exercise Solutions

Appendix B: Exam Competencies

Appendix C: Learning Processes and Instructor Guide Conventions


Preview
C ou rse De scrip tio n an d Strateg y

Course Description and


Strategy
„ Course Description
„ Course Strategy

U s i ng Lo tu s S c r ip t i n I B M L o tu s D o m in o A p pl i c a t i on s 1
© Cop yr ig ht IB M Co rpo ratio n 200 2. All rig hts re serv ed.
Preview
Cou rs e D escr ip tio n an d Strate gy

Course Description

Target audience

The target audience for Using LotusScript in IBM Lotus Domino Applications is
Application developers who will be using LotusScript in their Domino applications.

Summary description

Students will learn the techniques of programming in LotusScript while they learn
to access and work with objects in the Domino Object Model.
This course:
„ Introduces students to the LotusScript language
„ Instructs how to retrieve properties of a database
„ Introduces the use of the LotusScript Debugger
„ Uses methods of NotesDatabase
„ Traverses down the Document Object Model to ACL classes.
The skill of navigating the Document Object Model is continuously reinforced
throughout the course as students learn to work with front-end and back-end
classes.

Course format and duration

This is a three day classroom course.

2 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
C ou rse De scrip tio n an d Strateg y

Course Description...(continued)

Course goals

By the end of this course, students should be able to:


„ Write LotusScript code that navigates the Domino Object Model and retrieves
object data.
„ Write LotusScript code that modifies and adds data in Domino applications.
„ Select the best mechanism for executing LotusScript code.
„ Use the LotusScript debugger and error trapping to debug code.
„ Use Script Libraries to reuse code efficiently.

Topics covered

The Using LotusScript in IBM Lotus Domino Applications course covers the following
topics:

„ Introducing LotusScript: where and when to use it


„ Using programming skills such as:
„ declaring variables
„ assigning values
„ using looping statements
„ using arrays
„ using conditional statements
„ converting data types
„ Instantiating objects
„ Retrieving database information
„ Using the LotusScript Debugger
„ Trapping errors in code
„ Working with the front-end classes to manipulate objects in the user interface
„ Working with back-end classes to retrieve and add data to documents
„ Creating and sending report documents
„ Prompting users for data and processing the data
„ Using Script Libraries

U s i ng Lo tu s S c r ip t i n I B M L o tu s D o m in o A p pl i c a t i on s 3
Preview
Cou rs e D escr ip tio n an d Strate gy

Course Strategy

Approach

Using LotusScript in IBM Lotus Domino Applications is designed to introduce


Domino developers to the powerful LotusScript programming language. The
course and its examples should work equally well with developers using Domino
Designer 5 or higher.

Recommended agenda

The tables on the following two pages describe the recommended agenda for
delivering the material over the three days.

4 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
C ou rse De scrip tio n an d Strateg y

Course Strategy...(continued)

Day 1

The following table shows the recommended agenda for Day 1.

Time Lessons or Topics

30 minutes Course and Student Introductions

Module A: Using LotusScript to Access and Modify Databases Programmatically

1 hour, 40 min- Lesson 1: Introducing LotusScript


utes

1 hour, 15 Lesson 2: Accessing Database Information


minutes

1 hour Lunch

50 minutes Lesson 3: Navigating the Domino Object Model to Access ACL


Information

Module B: Navigating the User Interface Classes

50 minutes Lesson 4: Working with NotesUIWorkspace

Day 2

The following table shows the recommended agenda for Day 2.

Time Lessons or Topics

Module B: Navigating the User Interface Classes

1 hour, 30 Lesson 5: Working with NotesUIDocument


minutes

Module C: Creating and Modifying Documents

1 hour, 35 Lesson 6: Accessing Data in Documents


minutes

1 hour Lunch

2 hours, 30 Lesson 7: Writing Data to Documents


minutes

U s i ng Lo tu s S c r ip t i n I B M L o tu s D o m in o A p pl i c a t i on s 5
Preview
Cou rs e D escr ip tio n an d Strate gy

Course Strategy...(continued)

Day 3

The following table shows the recommended agenda for Day 3.

Time Lessons or Topics

Module C: Creating and Modifying Documents

1 hour, 50 Lesson 8: Using ViewEntry and Document Collection


minutes

Module D: Reusing Code and Processing Run-Time Errors

1 hour, 20 Lesson 9: Reusing Code


minutes

1 hour Lunch

50 minutes Lesson 10:Processing Run-Time Errors

6 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Instr ucto r Prep ara tio n

Instructor Preparation
„ Course Materials
„ Preparation Checklist
„ CLI Certification Requirements

U s i ng Lo tu s S c r ip t i n I B M L o tu s D o m in o A p pl i c a t i on s 7
© Cop yr ig ht IB M Co rpo ratio n 200 2. All rig hts re serv ed.
Preview
In stru cto r Pr ep aration

Course Materials

Instructor kit

The following table lists and describes the content of the instructor kit.

Instructor Kit Content Description

Instructor Guide for Using LotusScript in Contains the following:


IBM Lotus Domino Applications „ Course description and strategy
„ Recommended agenda
„ Course materials
„ Preparation checklist
„ CLI certification requirements
„ Classroom setup
„ Hints and tips for successfully teaching
the learning processes that will help the
students accomplish the lesson
objectives.

Course files „ Supports delivery of the course. The


Classroom Setup section describes
these files in further detail.

Student kit

The following table lists and describes the content of the student kit.

Student Kit Content Description

Student Guide for Using LotusScript in Contains the following:


IBM Lotus Domino Applications „ Course description
„ Recommended agenda
„ Lotus professional certification
„ Learning processes
„ Instructional content of the course,
including the activities and exercises
that will enable the students to
accomplish the lesson objective.

8 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Instr ucto r Prep ara tio n

Preparation Checklist

When preparing to teach this course, consider doing the following:


„ Read through the Student Guide and Instructor Guide.
„ Perform all activities and exercises in the Student Guide.
„ Perform all demonstrations and walkthroughs described in the Instructor
Guide.
„ Refer to the Interactive Instructor Guide (IIG) to get updated information on the
course.
„ Refer to the Instructor Lounge to gather useful teaching tips and techniques
that other instructors have used to teach this course.
„ Use the information in this section to find additional resources to further your
knowledge of the subject.
„ Practice the classroom setup.

Learning processes definition

A learning process is a method for presenting course information to students. If


you are unfamiliar with the learning processes defined by Lotus software, please
refer to Appendix B: Learning Processes and Instructor Guide Conventions for
further clarification.

U s i ng Lo tu s S c r ip t i n I B M L o tu s D o m in o A p pl i c a t i on s 9
Preview
In stru cto r Pr ep aration

Preparation Checklist...(continued)

CLI Private Site

For more information on how to teach this course, refer to the CLI Private Site
locate at http://www.lotus.com/cli.
If you have already registered, enter your user name and password to access the
Instructor Lounge and other private areas of the Web site to gain additional
information for teaching this course.
If you have not registered, visit the Education Zone located at http://
www.lotus.com/educationzone and follow the instructions to register for the
certified community. After registering, you will be able to access the CLI Private
Site using your user name and password.

Interactive Instructor Guide (IIG)

The Interactive Instructor Guide (IIG) is an IBM® Lotus® Domino™ database that
contains constructive comments from Certified Lotus Instructors (CLIs) who have
taught this course. Consult the IIG to learn about courseware issues, resolutions,
tips, and techniques for teaching this course. If you have insights you would like to
share with other CLIs after teaching this course, please include your comments in
the IIG so that other instructors may benefit from your experience.
The IIG is structured so that instructors can:
„ Provide feedback on courseware.
„ Submit courseware problem reports.
„ Share course delivery tips and tools.
Lotus software monitors this site to provide:
„ Responses to feedback.
„ Solutions to courseware problems.
„ Courseware updates.
You can access the link to the IIG from the CLI Private Site located at http://
www.lotus.com/cli.

10 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Instr ucto r Prep ara tio n

Preparation Checklist...(continued)

Additional instructor preparation information

In the table below, list and describe any additional resources the instructor can
use to prepare to teach this course. Information can include Web sites, white
papers, Redbooks, and so on.

Go to... And Look Through Articles Under...

„ http://www-10.lotus.com „ Domino 6
„ Go to LDD Today „ Domino Designer 6
„ Iris Today Archives
„ By Product Version

U s i ng Lo tu s S c r ip t i n I B M L o tu s D o m in o A p pl i c a t i on s 11
Preview
In stru cto r Pr ep aration

CLI Certification
Requirements

CLI Web site

To learn about the requirements for becoming a CLI or to upgrade your current
certification, visit the IBM Software Services for Lotus Certification Web site at
http://www.lotus.com/certification.

12 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Clas sro om Setu p

Classroom Setup
The following system specifications and setup procedures were used to
develop and test this course. If the classroom setup does not match these
specifications, Lotus software makes no guarantee that the learning processes
in this course will perform as stated.

U s i ng Lo tu s S c r ip t i n I B M L o tu s D o m in o A p pl i c a t i on s 13
Preview
Classr oo m Se tup

Machine Requirements

Instructor machine requirements

The following table identifies the number of Notes/Domino license types required
for the instructor machine(s) for this class.

Notes/Domino # of Instructor # of Instructor


License Type Server Machines Client Machines

IBM Lotus Domino 6 1


Enterprise Server

IBM Lotus Domino 1


Designer 6

Student machine requirements

The following table identifies the number of Notes/Domino license types required
for the student machines for this class.

Notes/Domino # of Student # of Student


License Type Server Machines Client Machines

IBM Lotus Domino 1 per student


Designer 6

14 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Clas sro om Setu p

Machine Requirements...(continued)

Software and hardware requirements

The following table lists the software and hardware required per instructor and
student machine to deliver this course.

Software Requirements Minimum Hardware Recommended


Requirements per Hardware
Machine Requirements per
Machine

Network TCP/IP using either Hosts file Internet access


or DNS with server and
domain names defined in the
TCP/IP protocol configuration.

Instructor „ Microsoft® Windows® 2000 „ Memory: 256 MB „ Memory: 512 MB


servers Server with Service Pack 3 „ Disk space: 500 MB „ Disk space 1 G
Or „ CD-ROM drive or
Microsoft Windows NT® 4 access to network file
Server with Service Pack 6a server for installation
„ IBM Lotus Domino Server 6 „ Support for 256
colors, 800 x 600
resolution

Instructor „ Microsoft Windows 2000 „ Memory: 128 MB „ Memory: 256 MB


and with Service Pack 3 „ Disk space: 250 MB „ Disk space: 300 MB
student Or „ CD-ROM drive or
clients Windows NT 4 with Service access to network file
Pack 6a server for installation
„ IBM Lotus Domino „ Support for 256
Designer 6 colors, 800 x 600
resolution
„ Synchronize system
time with all
classroom machines

U s i ng Lo tu s S c r ip t i n I B M L o tu s D o m in o A p pl i c a t i on s 15
Preview
Classr oo m Se tup

Classroom Setup Overview

List of course files

The following table describes the course files.

Title File name Function

Demos and Activities- DemActLS-inst.nsf This instructor database will be


Instructor used for a majority of the
demonstrations and guided
practices.

Inventory-Instructor Inventory-inst.nsf This instructor database contains


the exercises students will work
on throughout the course.

Demos and Activities DemActLS.nsf Students will use this database


for the guided practices.

Inventory Inventory.nsf Students will use this database


for the exercises.

16 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Clas sro om Setu p

Classroom Setup
Instructions

Checklist of classroom setup tasks

Complete the tasks in the following table to set up the classroom prior to the start
of class. Detailed procedures for each task appear on the following pages.

Task Procedure

‰ 1 Set up the operating system.

‰ 2 Install the course setup files.

‰ 3 Install Lotus Domino 6.

U s i ng Lo tu s S c r ip t i n I B M L o tu s D o m in o A p pl i c a t i on s 17
Preview
Classr oo m Se tup

Classroom Setup Instructions...(continued)

Task 1: Set up the operating system

Follow these steps to properly set up the server machines for this class.

Step Action

1 Install Windows 2000 Professional and Service Pack 3.

2 Create a system user ID by choosing StartÆProgramsÆControl


PanelÆAdministrative ToolsÆComputer Management.

3 Expand Local Users and Groups. Select the Users folder.

4 Choose ActionÆNew User and set the following properties:


„ Enter a user name.
„ Enter password for the password.
„ Uncheck the User Must Change Password at Next Logon option.
„ Check the Password Never Expires option.

5 Assign the new user to the Administrators group by doing the following:
„ Select Groups.
„ Double-click the Administrators group.
„ Click ADD.
„ Double-click db2admin. Click OK.
„ Click OK.

6 Enable local security policies for the new user, db2admin.


„ Choose StartÆProgramsÆControl PanelÆAdministrative
ToolsÆLocal Security Policy.
„ Expand Local Policies.
„ Choose User Rights Assignment.
„ Double-click Act as part of the operating system.
„ Click Add.
„ Select the Administrators group.
„ Click Add.
„ Click OK.
„ Click OK.

18 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Clas sro om Setu p

Classroom Setup Instructions...(continued)

Task 1: Set up the operating system...

Step Action

7 Assign workstation names of DomWeb1 through DomWebXX to each server


in the room.

8 Edit the hosts file on each machine. Add domweb1 and


domweb1.HlthSystemsIntl.com to the line: 127.0.0.1 localhost.

Task 2: Install the course files

Follow these steps to install the configuration and data files for this course.

Step Action

1 On the Instructor’s server, extract the databases, located in ND540_dbs.zip


file.
Result: The files listed in the List of courses files section are extracted to
Lotus/Notes/Data.

2 Extract the ND540_dbs.zip file to each student machine.

U s i ng Lo tu s S c r ip t i n I B M L o tu s D o m in o A p pl i c a t i on s 19
Preview
Classr oo m Se tup

Classroom Setup Instructions...(continued)

Task 3: Install Lotus Domino 6 (clients and server)

Follow these steps to set up the Lotus Domino 6 server and client applications on
the same system.

Step Action

1 Install Lotus Domino Server 6.0.1 in the default directories.

2 Install Lotus Notes, Domino Designer, and Domino Administrator clients in


the default directories.

3 Setup the Domino Server using the recommended naming:


„ Host: domweb1
„ Fully qualified internet host name: domweb1.HlthSystemsIntl.com
„ Minimize services ensure that the following are enabled: routing, LDAP,
DIIOP

4 Start the Domino server and verify that it works. Verify that the DIIOP task
runs.
Note: It is recommended that you start the Lotus Domino R5 server as an NT
service.

5 Register a fictitious user for the students to work with in the labs.

6 Register a user named Servlet Client, password: lotusnotes.

7 Add Servlet Client to the Run unrestricted Java/Javascript/COM field of


the server document.

8 Once you verify that the server works, shut it down for the remainder of the
setup procedures.

20 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


A
Using LotusScript to
Access and Modify
Databases
Programmatically
Lesson 1 Introducing LotusScript
Lesson 2 Accessing Database Information
Lesson 3 Navigating the Domino Object Model to Access
ACL Information

© Cop yr ig ht IB M Co rpo ratio n 200 2. All rig hts re serv ed.


Preview
Le sso n 1 „ In t r o du ci ng L ot u sScr ip t

1
Introducing LotusScript

22 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L ess on 1 „ I n tr od uc in g Lo tus Scri pt

1
Introducing LotusScript

This lesson describes LotusScript and introduces some basic syntax. It describes
how to store data in variables, how to comment code, and how to use the
LotusScript debugger to track down errors in the code.

Objectives

After completing this lesson, you should be able to:


9 Define LotusScript.
9 List the advantages of LotusScript.
9 Identify where you can write and run LotusScript in Domino applications.
9 Declare variables.
9 Assign values to variables.
9 Use MessageBox to display text to users.
9 Run the LotusScript debugger.

Stud ent Gu ide Page No. 18 23


Preview
Le sso n 1 „ In t r o du ci ng L ot u sScr ip t

Introducing LotusScript

Start by asking students why they want to use LotusScript. Discuss where, when,
and why to use LotusScript. If students suggest using it to access objects, ask
what Domino objects are.

24 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L ess on 1 „ I n tr od uc in g Lo tus Scri pt

Introducing LotusScript

LotusScript is an embedded scripting language that enables object-oriented


application development within and across Lotus products. Its interface to Lotus
products is through pre-defined object classes.

Advantages of LotusScript

LotusScript offers developers several advantages:


„ LotusScript is a superset of BASIC and is generally easy to learn.
„ LotusScript is platform-independent, so scripts developed on one platform will
execute on any other supported platform.
„ LotusScript provides access to the whole Domino application through a set of
object-oriented classes.
„ LotusScript supports OLE, which allows Notes documents to use other
OLEenabled applications.
„ The LotusScript Integrated Development Environment allows developers to
create, edit, and debug scripts.
„ Developers can create functions and libraries to reuse in other applications.
„ Developers can create new classes and objects.

When to use LotusScript

Developers should use LotusScript for Domino applications when they need to do
the following:
„ Develop sophisticated scripts with conditions, branches, loops, and
subroutines.
„ Place scripts in a variety of objects and events.
„ Debug complex code.
„ Use OLE to access other applications.

Stud ent Gu ide Page No. 19 25


Preview
Le sso n 1 „ In t r o du ci ng L ot u sScr ip t

Introducing LotusScript...(continued)

LotusScript and Web applications

Explain that LotusScript does not run in Web browser. There are other options for
applications that will be run in both the Notes Client and Web browsers.

26 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L ess on 1 „ I n tr od uc in g Lo tus Scri pt

Introducing LotusScript...(continued)

Where to use LotusScript in Domino applications

Domino Designer allows developers to add LotusScript code to elements and


events so the code executes when appropriate. The following table describes
where code can be written and when it runs.

Element When Code Runs

Agent „ Manually from Actions menu


„ On a schedule (daily, weekly, monthly)
„ Before or after new mail arrives
„ If documents are created/modified or pasted

Action „ Manually from Actions menu, or by clicking a


button on a form or view

Form, view, events „ When a page, form, or view opens or closes


„ When the cursor enters or exits a field

LotusScript and Web applications

LotusScript does not run in Web browsers, but a Web user can invoke LotusScript
code that runs on the Domino server. Using events or a Domino URL command,
users can execute LotusScript agents that access data stored in the application,
but cannot manipulate the user interface of the application.

Stud ent Gu ide Page No. 20 27


Preview
Le sso n 1 „ In t r o du ci ng L ot u sScr ip t

Declaring Variables in LotusScript

LotusScript datatypes

Ask students the following types of questions as you present the table from the
Student Guide.
„ What types of data contain text?
„ What types of data contain numbers?
„ What is the difference between integer and long?
„ What is the difference between integer and single or double? What is the
difference between currency and single or double? Answer: There are only
four significant digits in the decimals.

28 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L ess on 1 „ I n tr od uc in g Lo tus Scri pt

Declaring Variables in LotusScript

Scripts use variables to store values and work with the data. A variable is a named
location in memory. Each variable is declared as a certain data type. The data
type determines how much space is reserved for the data. Once the variable is
declared, data can be stored in it.

Data types available in LotusScript

Before declaring a variable, consider what type of data it will hold, then choose the
best available data type. Data types can be scalar (numeric and string) or more
complex types like an array, variant, or an object reference. We will discuss these
more complex data types later in this course.
The following table describes the scalar data types available in LotusScript.

Data Type Suffix Description

Integer % „ Whole number between –32,768 and 32,767.


„ Initial value: zero (0)
„ Size: 2 bytes

Long & „ Whole number between –2,147,483,648 and


2,147,483,647
„ Initial value: zero (0)
„ Size: 4 bytes

Single ! „ Real number between -3,402823E+38 and


3,402823E+38
„ Initial value: zero (0)
„ Size: 4 bytes

Double # „ Real number between -1.7976931348623158E+308


and 1.7976931348623158E+308
„ Initial value: zero (0)
„ Size: 8 bytes

Currency @ „ Real number between -922,337,203,685,477.5807 to


922,337,203,685,477.5807
„ Initial value: zero (0)
„ Size: 8 bytes

String $ „ 0 – 32K alphanumeric characters


„ Initial value: null string (“”)
„ Size: 2 bytes per character

Stud ent Gu ide Page No. 21 29


Preview
Le sso n 1 „ In t r o du ci ng L ot u sScr ip t

Declaring Variables in LotusScript...(continued)

Declaring variables

You cannot name variables using keyword names, such as string and integer.
Address case sensitivity

30 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L ess on 1 „ I n tr od uc in g Lo tus Scri pt

Declaring Variables in LotusScript...(continued)

Explicit variable declarations

To declare a variable in LotusScript explicitly, use the Dim keyword to define the
name and type of the variable. Dim stands for dimension. When you declare a
variable, you are reserving a piece of memory. The amount of memory you
reserve depends on the data type you use to declare the variable.
Syntax
Dim varName as data type
Examples
The following examples define the variable partNumber as an integer and the
variable firstName as a string of text.
Dim partNumber As Integer
Dim firstName As String
Note: When using the Dim statement, you can specify the data type with either
the appropriate keyword (Single) or suffix (!). Data type suffixes are listed in the
data types table on the previous page.
Example
Dim counter As Integer
or
Dim counter%

Rules for naming variables

The following rules apply to constructing a valid name or identifier for a variable:
„ The first character must be a letter.
„ The remaining characters must be letters, digits, or underscores ( _ ).
„ The maximum length of a name is 40 characters.
„ Names are not case-sensitive. For example, firstName is the same name as
FIRSTname.

Stud ent Gu ide Page No. 22 31


Preview
Le sso n 1 „ In t r o du ci ng L ot u sScr ip t

Choosing a Data Type Exercise

Review the answers with students by doing one or more of the following:
„ Ask students to provide answers and generate a discussion. Each description
may have more than one correct answer.
„ Write answers on the whiteboard.
„ Ask students if currency automatically formats the result or not.

32 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L ess on 1 „ I n tr od uc in g Lo tus Scri pt

Choosing A Data Type Exercise

In this exercise, choose the best data type to represent the variable described.
Then, write the declaration in the space provided.

Determine the appropriate data types for variables

Write the declaration statement for the following variable descriptions.

Variable Description Variable Declaration


The number of days a discussion
topic is active

A message to alert users of an error

The price of a piece of merchandise

The distance between two cities

The name of a form in a Domino


database

Stud ent Gu ide Page No. 23 33


Preview
Le sso n 1 „ In t r o du ci ng L ot u sScr ip t

Assigning Variables in LotusScript

Assigning values to a variable

Describe the assignment operator and explain the example from the Student
Guide.

Assign values to variables

Present the Guided Practice by:


„ Identifying what variables students will declare.
„ Identifying what values students will assign to the variables.
„ Asking students what the message box will display.
„ Discussing the ampersand (&) as the concatenation operator in LotusScript,
possibly comparing it to Formula, which automatically converts a numeric to a
string.
„ Telling students what the underscore means within a script statement.
„ Asking if students have any questions before starting the guided practice.
Note: The spacing and line breaks indicated in the code on the Student Guide
might not necessarily represent the spacing students will use. Be sure to point this
out as they are inputting the LotusScript code.
You may also need to demonstrate how to:
„ Create a button.
„ Switch to LotusScript in the Script pane.
„ Enter code within the sub.
„ Preview the form in Notes.
Review the guided practice with students to make sure they understand.

34 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L ess on 1 „ I n tr od uc in g Lo tus Scri pt

Assigning Variables in LotusScript

Once a variable is declared, you can assign it a value.

Assigning a value to a variable

Use the assignment operator (=) to set the value of a variable. The data type of
the value and the variable must be compatible.
Example
'Declare variables
Dim partNumber As Integer
Dim msg As String
Dim msg2 As String

'Assign values to variables


partNumber = 37
msg = "this is a string"

Assign values to variables

In this Guided Practice, you will write LotusScript code that declares variables and
assigns values to them. Add the code to a button and use the built-in MessageBox
function to display the values of the variables.
Follow these steps to assign values to variables.

Step Action
1 Open the Demos and Activities database in Domino Designer. Open the
Variables Activity form.

2 Choose Create Æ Hotspot Æ Button to create a button. Name it Declare


and Assign Variables.

3 In the Programmers pane, select the Click event of the button and select
LotusScript from the Run menu.

4 Enter the following code, under Sub Click(Source As Button), to


declare the variables.
Dim MyFavMovie As String
Dim rating As Integer

(continued on next page...)

Stud ent Gu ide Page No. 24 35


Preview
Le sso n 1 „ In t r o du ci ng L ot u sScr ip t

Assigning Variables in LotusScript...(continued)

36 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L ess on 1 „ I n tr od uc in g Lo tus Scri pt

Assigning Variables in LotusScript...(continued)

Assign values to variables...

Step Action

5 Enter the following code to assign each variable a value. (You may substitute
any valid value for those given here.)
MyFavMovie = "Metropolis"
rating = 5

6 Enter the following code to display the variables.


Messagebox "My favorite movie is " & MyFavMovie & _
". I give it a rating of " & rating & " stars."
Note: The underscore at the end of the first line indicates that the statement
continues on the next line. If you enter this entire statement on a single line,
omit the underscore.

7 Choose File Æ Save to compile the script and save the form.
If any compile-time errors are found, fix them and repeat this step.

8 Preview the form in Notes and click the button. Observe the values as the
message box appears.

Stud ent Gu ide Page No. 25 37


Preview
Le sso n 1 „ In t r o du ci ng L ot u sScr ip t

Assigning Variables in LotusScript...(continued)

Illustrate declaring implicit variables

Use the Variables Demo form in the Demos and Activities-Instructor database
to illustrate implicit variable declarations.
„ Show how the suffix, $, declares the variable for the phone number.
myphone$="617-123-9876"
„ Uncomment the statement that changes the phone number. Save the form
and explain the compiler error that results because the suffix is missing.
'myphone="941-472-2112"
Ask students why implicitly declaring variables can be difficult to troubleshoot.

Comparing implicit and explicit variable declarations

Use the table to compare the two ways of declaring variables.

38 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L ess on 1 „ I n tr od uc in g Lo tus Scri pt

Assigning Variables in LotusScript...(continued)

Implicit variable declarations

Implicit variable declarations are a shorthand way to declare a variable in the


same line of code as the variable assignment.
Implicit declarations do not use the Dim statement, and they always use the suffix
character for a data type. For example, the percent sign (%) indicates an integer,
and the dollar sign ($) indicates a string.
The data type suffix becomes part of the variable name and must be carried
though the script every time the variable is used.
Syntax
varName<data type suffix> = value
Examples
The following example returns the message: First name is Joseph.
firstName$ = "Joseph"
Messagebox "First name is " & firstName$

Comparing implicit and explicit variable declarations

The following table compares implicit and explicit variable declarations.

Implicit Declaration Explicit Declaration


partNumber% = 37 Dim partNumber As Integer
partNumber = 37

message$ = "Warning" Dim msg As String


msg = "Warning"

radius! = 42.37/(2*PI) Dim radius!


radius! = 42.37/(2*PI)

Note: Data type suffixes are listed in the Data Types table on page 7 or use
Domino Designer Help to find the suffix for each data type.

Stud ent Gu ide Page No. 26 39


Preview
Le sso n 1 „ In t r o du ci ng L ot u sScr ip t

Assigning Variables in LotusScript...(continued)

Forcing an explicit variable declaration

„ Open the (Options) Event for the Variables Demo button on the Variables
Demo form and add the following line of code:
Option Declare.
„ Show how Designer automatically puts the statement in the Options event of
the button.
„ Save the form to show that the compiler does not allow the implicit declaration
for the variable myphone$.
„ Add the explicit declaration and preview the form.

40 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L ess on 1 „ I n tr od uc in g Lo tus Scri pt

Assigning Variables in LotusScript...(continued)

Forcing a script to declare variables explicitly

Although implicit variable declarations may save some time and typing, they are
not recommended for large or complex code because it is easy to forget the suffix
character. If you omit the suffix, the LotusScript compiler will think the variable is of
type Variant. A variant is a general-purpose data type that can hold almost any
type of data (such as a string, number, array, or object reference).
To force code to use explicit variable declarations, specify the following statement
in the (Options) script of an object:
Option Declare
This statement causes the compiler to flag any variable that is not explicitly
declared. This helps eliminate potential data type mismatches at run time.

Stud ent Gu ide Page No. 27 41


Preview
Le sso n 1 „ In t r o du ci ng L ot u sScr ip t

Commenting Code

Explain why comments are useful.

Add the three types of comment indicators

Add each type of LotusScript comment to an existing form, like the Variables
Demo form. Explain why students might pick one method over another.

42 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L ess on 1 „ I n tr od uc in g Lo tus Scri pt

Commenting Code

It is important to add comments to code for easier maintenance of the application.

LotusScript comment indicators

LotusScript provides three ways of adding comments to code, as described in the


following table.

Comment Indicator Function


Rem Anything following the indicator and before a
new line is started, is a comment.
' (apostrophe) Anything following the apostrophe and before a
new line is started, is a comment.
%Rem…%End Rem Anything between the two directives is a
comment.

Examples of comments

The following are examples of comments in LotusScript code:


Rem Declare variables
Dim z as Single

'Calculate commission
commission = totalSales * commissionRate

%Rem
msg$ = "hello world"
Messagebox msg$
%End Rem

Stud ent Gu ide Page No. 28 43


Preview
Le sso n 1 „ In t r o du ci ng L ot u sScr ip t

Using the LotusScript Debugger

LotusScript errors

Describe the two types of errors that occur when working with LotusScript.

44 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L ess on 1 „ I n tr od uc in g Lo tus Scri pt

Using the LotusScript Debugger

LotusScript recognizes two types of errors: compile-time errors and run-time


errors.

Types of errors

The following table describes the two types of errors that LotusScript recognizes.

Type of Error Description


Compile-time errors „ These types of errors are found and reported
when the compiler attempts to compile a
script.
„ They must be corrected before the script can
be run.
„ For example, incorrect syntax of a statement
is a compiler error.

Run-time errors „ These types of errors are found when a script


is executed.
„ These errors cannot be predicted at compile
time and may prevent the script from running
to completion.
„ For example, trying to open a file that does
not exist is a run-time error.

The LotusScript debugger

The LotusScript debugger helps find errors in an application. If the application


code compiles but does not perform as expected, use the debugger to locate the
place where something went wrong.

Stud ent Gu ide Page No. 29 45


Preview
Le sso n 1 „ In t r o du ci ng L ot u sScr ip t

Using the LotusScript Debugger...(continued)

Describe the LotusScript debugger

„ Open the LotusScript debugger.


„ Choose FileÆ ToolsÆ Debug LotusScript from either the Notes client or
Domino Designer.
„ Execute the code. For example, click the button on the Variables Demo form.
„ Explain the three panes that comprise the LotusScript debugger.
„ Describe the purpose of the three tabs in the Utilities pane.

46 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L ess on 1 „ I n tr od uc in g Lo tus Scri pt

Using the LotusScript Debugger...(continued)

Parts of the debugger

The following diagram shows the LotusScript debugger.

Debug pane

Script area

Utilities pane

The following table describes the parts of the LotusScript debugger.

Part Function

Debug pane Displays the script currently being debugged.

Continue button Runs the current script and stops only if an error
is found.

Step Into button Steps through a script one line at a time.

Step Over button Executes the current statement and steps to the
next.

Step Exit button Executes the current subroutine and, upon exit,
resumes debugging.

Stop button Stops all scripts and closes the debugger.

Script area Displays the script currently being debugged.

Utilities pane Contains tabs that display information about the


script, including variable assignments and
output.

Stud ent Gu ide Page No. 30 47


Preview
Le sso n 1 „ In t r o du ci ng L ot u sScr ip t

Using the LotusScript Debugger...(continued)

Use the LotusScript debugger

Describe how to enable and disable the LotusScript debugger.


„ Examine the Debug Variables Demo form in the Demos and Activities-inst
database.
„ The code contains a new statement in the Variables Demo button. This new
statement sets the value of myaddress.
„ Preview the form in Notes and point out the fact that the address does not
appear.
„ Close the new document without saving.
„ Enable the LotusScript debugger.
„ Preview the form again and step through the code showing the values of each
variable.
„ Explain why there is a myaddress and a myaddres.
„ In Designer, add the Option Explicit statement to the button and save the form.
Now the compiler tells you where the error is.
„ Fix the code and preview the form again.

48 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L ess on 1 „ I n tr od uc in g Lo tus Scri pt

Using the LotusScript Debugger...(continued)

Using the LotusScript debugger

Follow these steps to start the LotusScript debugger.

Step Action

1 Enable the debugger by choosing FileÆ ToolsÆ Debug LotusScript from


either the Notes client or Domino Designer.

2 Click OK when the LotusScript debugging started message displays.

3 Execute the code. For example, run the agent or click the button.
Result: The script pauses and the debugger opens.

4 Use the contents of the debugger window and its functions to identify
problems in the code.

5 Disable the debugger by choosing FileÆ ToolsÆ Debug LotusScript


again.

6 Click OK when the LotusScript debugging terminated message displays.

Stud ent Gu ide Page No. 31 49


Preview
Le sso n 1 „ In t r o du ci ng L ot u sScr ip t

Using the LotusScript Debugger...(continued)

View variables in the debugger

Present the guided practice by:


„ Identifying which database and form students will use.
„ Asking if students have any questions before starting the guided practice.
You may have to also demonstrate how to:
„ Start and stop the debugger.
Review the guided practice with students to make sure they understand.
Note: If this is the first time the debugger has been opened in the client, it will run
through debugging the process of copying BOOKMARKS.NSF.

50 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L ess on 1 „ I n tr od uc in g Lo tus Scri pt

Using the LotusScript Debugger...(continued)

View variables in the debugger

In this guided practice, you will:


„ Add comments to the code created in the previous Assign values to
variables guided practice,
„ Recompile the code,
„ Enable the debugger, and
„ Explore the variable assignments.
Follow these steps to view variables in the debugger.

Step Action

1 Open the Variables Activity form in your Demos and Activities database.

2 Select the Variables Activity button and add the following code before the
first Dim statement:
'Declare movie and rating variables

3 Add the following code before the first assignment statement


(MyFavMovie = ...):
'Assign values to movie and rating

4 Add the following code before the messagebox statement:


'Display the values of movie and rating

5 Compile and save the modified action.

6 Choose FileÆToolsÆDebug LotusScript.

7 Preview the form and click Declare and Assign Variables.

8 The debugger will automatically stop processing the script at the first
assignment statement. In the Utilities pane, click the Variables tab and
notice that the variables have default values.

9 Click Step Over and examine the Variables tab again. Notice that after the
statement executed, the MyFavMovie variable has a new value.

10 Continue to click Step Over and notice the values of the variables change.
Once the message box displays, click OK.

11 Click Continue in the LotusScript Debugger to complete the script.

12 Choose FileÆToolsÆDebug LotusScript to disable the debugger.

Stud ent Gu ide Page No. 32 51


Preview
Le sso n 2 „ Acc essin g Datab ase In fo rma tio n

2
Accessing Database
Information

Present the objectives from the Student Guide.

52 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Les so n 2 „ Acce ssing Datab ase Info rma tio n

2
Accessing Database
Information

In this lesson, you will start using LotusScript to access a NotesDatabase object.
At the same time, you will learn more LotusScript techniques, such as using an
If...Then statement to check the value of a method or property.

Objectives

After completing this lesson, you should be able to:


9 Identify NotesDatabase properties.
9 Declare object reference variables.
9 Instantiate new objects.
9 Access and display database properties.
9 Perform simple error checking.
9 Use NotesSession to access the current database.
9 Modify the database title with LotusScript.
9 Create a new database from a template.

Stud ent Gu ide Page No. 33 53


Preview
Le sso n 2 „ Acc essin g Datab ase In fo rma tio n

Exploring the Domino Objects

Use this section to review the concept of the Domino Object Model that students
learned in Domino Application Architecture.

Describe Domino objects

Ask students to name Domino objects. Ask students what an object is. LotusScript
lets you write a program to work with these discrete entities just as a user works
with the discrete entities through Notes and Domino Designer. For example, a
user or a LotusScript program can open a document and change a field value.
The NotesDatabase class represents a Domino database, its properties, and
things that it can do, such as open or create a copy of itself.
Ask students to describe the difference between the back-end and front-end
classes, reviewing what they learned in Domino Application Architecture.

The Domino object containment model

Present the concept of containment in the Domino Object Model. You want
students to be able to identify that the containment model identifies the path they
need to use to access their objects.

54 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Les so n 2 „ Acce ssing Datab ase Info rma tio n

Exploring the Domino Objects

LotusScript uses a predefined set of object classes known as the Domino


objects. The Domino objects represent the Domino database, its elements, and
its data. You can create objects based on these classes and manipulate the
application through script.

Domino objects

Domino objects are a set of classes that represent the elements of a Domino
application. Each class has properties and methods that allow developers to script
their behavior.
The Domino objects are grouped into the following two sets of classes:
„ Back-end classes represent databases and elements as they appear on-disk,
without regard for what users are doing.
„ Front-end, or user interface (UI), classes represent the database or element as
it appears to the current user.

Domino object containment model

A containment hierarchy is the relationship that the Domino object classes share.
Certain classes contain other classes. This relationship provides a path through
the objects that a script can take to access the object data or function it needs.
Consider the Domino containment model. A Domino server contains Domino
databases. Domino databases contain notes, and notes contain items. To access
an item value, you must access a database, and a note. You cannot access
document or a view without a database.

Stud ent Gu ide Page No. 34 55


Preview
Le sso n 2 „ Acc essin g Datab ase In fo rma tio n

Exploring the Domino Objects...(continued)

Describe the Domino object hierarchy

Use the diagram to illustrate how to identify the path and containment.

Describe the NotesDatabase class

Describe common properties and methods of the NotesDatabase class.


Open Domino Designer Help and show the complete syntax and description of the
NotesDatabase class. Point out that Help shows the classes that contain the
current class and the classes contained by the current class.

56 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Les so n 2 „ Acce ssing Datab ase Info rma tio n

Exploring the Domino Objects...(continued)

Domino object hierarchy

The following diagram shows a portion of the Domino object containment


hierarchy.

The NotesDatabase class

The NotesDatabase class represents a Domino database. It has several


properties that scripts can access or change.
NotesDatabase is contained by the following classes:
„ NotesSession
„ NotesDbDirectory
„ NotesUIDatabase
NotesDatabase contains classes representing design elements, including:
„ NotesACL
„ NotesDocument
„ NotesDocumentCollection
„ NotesView

Stud ent Gu ide Page No. 35 57


Preview
Le sso n 2 „ Acc essin g Datab ase In fo rma tio n

Creating Objects in LotusScript

Declaring an object

To avoid confusion, do not combine declaring and instantiating an object in the


same line. It is important that students feel comfortable doing these actions
separately, to differentiate when they use New and when they do not.
The variable is being assigned to something more complex than a string or
integer.

58 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Les so n 2 „ Acce ssing Datab ase Info rma tio n

Creating Objects in LotusScript

In addition to the scalar data types described in the previous section, LotusScript
also provides more complex data types. For example, the Domino objects
represent sets of different data types and procedures that are wrapped into a
particular type of class. To use the Domino objects in a script, define object
reference variables and assign them values through documented properties and
methods.

Declaring an object reference variable

Use the Dim keyword to declare an object reference variable in the same way you
declared scalar values.
The following statements are examples of declaring object reference variables:
Dim db As NotesDatabase 'declare a NotesDatabase object
Dim doc As NotesDocument 'declare a NotesDocument object
Dim v As NotesView 'declare a NotesView object

Use consistent variable names

Develop a set of standard variable names for referencing Domino object classes,
and use them consistently. It will make your code easier to read and maintain.

Stud ent Gu ide Page No. 36 59


Preview
Le sso n 2 „ Acc essin g Datab ase In fo rma tio n

Creating Objects in LotusScript...(continued)

Using the Set keyword

Instantiation is the process of assigning an object to a variable.


Emphasize that New does not create a new object. It is instantiating the object so
that you can work with it. It is similar to assigning an initial value to a variable.

60 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Les so n 2 „ Acce ssing Datab ase Info rma tio n

Creating Objects in LotusScript...(continued)

Using the Set keyword to instantiate an object

To set the value of an object, use the Set keyword. Set works with a method or
property of one of the Domino objects that contains the class you want to create.
Syntax
Set objectRef = classMethod or classProperty
Examples
'use property from the session object
Set db = s.CurrentDatabase

'use New method and object constructor


Set db = New NotesDatabase("server01", "names.nsf")

'use method of existing database object


Set newDb = oldDb.CreateCopy ("server02", "records.nsf")

Stud ent Gu ide Page No. 37 61


Preview
Le sso n 2 „ Acc essin g Datab ase In fo rma tio n

Creating Objects in LotusScript...(continued)

Instantiating a NotesDatabase object

If an object has a method called New, you can use it to construct an instance of
the object. You do not have to use other properties or methods from other classes.
In other words, it is a shortcut to that point in the containment path.
Describe the various methods of instantiating a NotesDatabase as listed in the
table from the Student Guide.
Open Domino Designer Help to the NotesDatabase class. Scroll through its
methods and locate New.
In order to use New, you need to know enough information about the object. For
example, with NotesDatabase, you need to know the server and file names.

Demonstrate instantiating a database

In the Demos and Activities-instructor database, use the DB Properties form.


Concentrate on the Dim and Set statements.
Note: Instantiating a database with the New method and no parameters gives you
a blank database that you can then fill using other methods and properties. If you
specify a server and file name, you get a database filled with the content of that
particular database. You can then use other methods and properties to modify
those contents.
Ask students why they would want to have an object in script, to lead into the next
section in which they access properties of the object.

62 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Les so n 2 „ Acce ssing Datab ase Info rma tio n

Creating Objects in LotusScript...(continued)

Instantiating a NotesDatabase object

There are several ways to instantiate a NotesDatabase object depending on


whether the database exists or you want to create a new database. The following
table describes some of these methods.

For a Database Object to… Use These Methods for Instantiation

Access an existing database „ New object constructor of NotesDatabase


„ GetDatabase method and CurrentDatabase
property of NotesSession
„ OpenByReplicaID method of
NotesDatabase

Create a new database. Create method of NotesDatabase

Create a new database based on an The following NotesDatabase methods:


existing database. „ CreateCopy
„ CreateFromTemplate
„ CreateReplica

Stud ent Gu ide Page No. 38 63


Preview
Le sso n 2 „ Acc essin g Datab ase In fo rma tio n

Accessing Object Properties

Identifying properties of an object

Ask students to provide examples of database properties that they might want to
access programmatically.

Accessing property values

Explain how to access properties of an object.

Accessing the name of a database

Explain that the Title property contains the name of the database.

64 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Les so n 2 „ Acce ssing Datab ase Info rma tio n

Accessing Object Properties

Identifying properties of an object

Object properties store values that describe characteristics of an object. For


example, the NotesDatabase object has properties that describe its title, when it
was last modified, and if it is open.
Use Domino R5 Designer Help for a complete list of all properties for all of the
Domino classes.

Accessing property values

To read a property value, use the following syntax:


variable = object.property
Where:
„ variable is declared as the same (or compatible) data type as the object
property.
„ object is the name of an instantiated object.
„ property is the name of a property of the instantiated object.

Accessing the name of a database

To access the name of a database, create a NotesDatabase object and access


the Title property.
The following code sample accesses the title of an existing database:
'Declare NotesDatabase object
Dim db As NotesDatabase
'Declare a string to hold title of db
Dim dbtitle As String
'Instantiate database object
Set db=New NotesDatabase("","My Database.nsf")
'Access the title of the db and store it in a string
dbtitle=db.Title

Stud ent Gu ide Page No. 39 65


Preview
Le sso n 2 „ Acc essin g Datab ase In fo rma tio n

Accessing Object Properties...(continued)

Displaying database properties

Using the DB Properties form in the Demos and Activities-inst database:


„ Add statements to the Using Properties button that display the following
properties in message boxes:
„ db.Title
„ db.Server
„ db.Filename
„ db.IsOpen
„ Preview the DB Properties form while running the debugger. Show the
following results in the Variables tab:
„ Which objects are instantiated
„ Data about the instantiated objects
„ The properties of the instantiated database
„ Now add code to change the title of the database and display the new title in a
message box. For example:
db.Title = "Test"
„ Preview the form and click the button.

Display database properties

Present the guided practice by:


„ Identifying what variables students will declare.
„ Identifying what objects students will instantiate.
„ Asking students what the message box will display.
Note: The auto completion mode is enabled by default. It can be turned off in the
Programmer’s Pane properties box in the Auto Complete tab.

66 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Les so n 2 „ Acce ssing Datab ase Info rma tio n

Accessing Object Properties...(continued)

Display database properties

Follow these steps to write a button script to display some properties of a


NotesDatabase object.

Step Action

1 On the DB Properties form in your database, create a button named


Properties Activity.

2 In the Programmers pane, select LotusScript from the Run drop-down list.

3 In the click event of the button, add the following code to create the object
reference variable for the database:
Dim db As NotesDatabase
Set db = New NotesDatabase ("","Inventory.nsf")

4 Continue adding the following code to the button script to display the
database title:
Messagebox "Database title is " & db.Title

5 Continue adding the following code to display the name of the server
containing the database:
Messagebox "Database server is " & db.Server
Note: This will be blank if the server is local.

6 Continue adding the following code to display the file name of the database:
Messagebox "Database filename is " & db.FileName

7 Add the following code to change the title of the database and to display the
new title:
db.Title = "My Local Directory"
Messagebox "Database title is " & db.Title

8 Choose File Æ Save to compile the code and save the form.

9 Turn on the LotusScript Debugger

10 Preview the form in Notes and click Properties Activity.


Observe the properties of the database.

Stud ent Gu ide Page No. 40 67


Preview
Le sso n 2 „ Acc essin g Datab ase In fo rma tio n

Adding Simple Error Checking to Code

Using the If...Then...Else statement

Explain the If...Then construct and syntax.

Using the Exit Sub statement

Ask for reasons why it might be necessary to exit a subroutine.

Add an If...Then statement

Use the DB Properties form for this Demonstration.


„ Add an If...Then statement to the Using Properties button that checks if the
database is opened before displaying the properties.
„ If the database is not opened, exit the subroutine.

68 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Les so n 2 „ Acce ssing Datab ase Info rma tio n

Adding Simple Error Checking to Code

Code should always check for errors and have a route to exit gracefully. You can
check the results of actions performed by the script by using an If…Then
statement. If something goes wrong, you can notify the user, try again, or stop the
script.

Using the If…Then…Else statement

The If…Then…Else statement executes a block of statements based on a


specified condition.
Syntax
If condition Then
statements
Else
statements
EndIf

Example
The following example will show the first message if the value for x is greater than
zero or the second message if the value is less than zero.
If x > 0 Then
Messagebox "The number is positive. "
Else
Messagebox "The number is not positive."
EndIf

Stud ent Gu ide Page No. 41 69


Preview
Le sso n 2 „ Acc essin g Datab ase In fo rma tio n

Adding Simple Error Checking to Code...(continued)

Verify that a database is open before using it

Present the guided practice by:


„ Identifying which database and form students will use.
„ Showing IsOpen in Help.
„ Asking what happens if the database is open.
„ Asking if students have any questions before starting the guided practice.
You may also need to demonstrate how to:
„ Switch to LotusScript in the Script pane.
„ Enter code within the sub.
„ Preview the form in Notes.

70 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Les so n 2 „ Acce ssing Datab ase Info rma tio n

Adding Simple Error Checking to Code...(continued)

Using the Exit Sub statement

The Exit Sub statement stops the execution of the current subroutine. If there is an
error that prohibits the script from continuing (such as not finding the specified
database), you can use this statement to stop the subroutine before it starts to
open views and documents.
Example
If db.IsOpen = False Then Exit Sub

Verify that a database is open before using it

In this guided practice, you will add code to the DB Properties form to verify that
the database opens before displaying the properties. You will use the IsOpen
property of the NotesDatabase class to determine if the database opened
successfully. You will also use an If…Then statement that exits the subroutine if
the database is not open.
Follow these steps to complete this guided practice.

Step Action

1 Open the DB Properties form in your database and click the Properties
Activity button you created in the last guided practice.

2 After the code statement that instantiates the database (set db = ...), add the
following statements:
'if database is not opened, exit the sub
If (db.IsOpen = False) Then
Messagebox "Could not open database"
Exit Sub
End If

3 Choose File Æ Save to compile the code and save the form.

4 Preview the form in Notes and click Properties Activity.

5 To verify the new code, do the following:


„ Change the file name of the database referenced in the script.
„ Run the code again.
Result: The subroutine should display the message that the database could
not be opened.

6 Change the database back to its original file name.

Stud ent Gu ide Page No. 42 71


Preview
Le sso n 2 „ Acc essin g Datab ase In fo rma tio n

Accessing the Current Database

Describe the NotesSession class

Open Domino Designer Help and point out some commonly used properties and
methods.

Present the code for accessing the current database

Show the code in the Using Properties button on the DB Properties form.
Preview the form with the debugger running. Show the Variables tab in the
debugger.

72 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Les so n 2 „ Acce ssing Datab ase Info rma tio n

Accessing the Current Database

When writing a script that manipulates data in the same database, use the
NotesSession class to access it. Once you have the current database, you can
access all of its data.

Examining the NotesSession class

NotesSession is an important class that represents the current script. It provides


access to environment variables, Address Books, and information about the
current user. It also contains several other classes, including NotesDatabase,
NotesLog, and NotesTimer.
The ability of NotesSession to access the database in which the current script
resides without specifying the particular name and server is especially useful. This
allows code to be more easily portable among databases.

Accessing the current database

To access the current database, use the CurrentDatabase property of a


NotesSession object reference variable.
Example
'Declare objRef variable for the NotesSession
Dim s as NotesSession
'Declare objRef variable for the NotesDatabase
Dim db as NotesDatabase
'Instantiate the objRef variable for the NoteSession
Set s = New NotesSession
'Instantiate the objRef variable for the current database
Set db = s.CurrentDatabase

Stud ent Gu ide Page No. 43 73


Preview
Le sso n 2 „ Acc essin g Datab ase In fo rma tio n

Creating a Database Based on Another


Database

Use a method of NotesDatabase

Explain the code in the Using Methods button of the DB Properties form.
Preview the form and click the button.

Examining the CreateCopy method

Ask students how many database references exist when a copy of the database is
created, to reinforce the idea that variables are references to an object.

Explain the CreateCopy method

„ The user opens the database, and then chooses a menu option to create a
New Copy.
„ Then the user enters the server and file name of the new database.
„ The program must also open the database, but instead of using a menu, it
uses a method to create the new copy.

Students will use this method in the next exercise, Creating a New Copy of a
Database.

74 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Les so n 2 „ Acce ssing Datab ase Info rma tio n

Creating a Database Based on Another


Database

The NotesDatabase class provides a method for creating a new database based
on another database. The other database may or may not be a template.

Examining the CreateCopy method

The CreateCopy method of the NotesDatabase class creates a new, empty


database. The new database contains all of the design elements, an identical
ACL, and the same title. The database copy does not contain any documents and
has a different Replica ID.

Using the CreateCopy method

Use the following syntax to use the CreateCopy method to create a new
database based on an existing one.
Syntax
Set newNotesDatabase = currentNotesDatabase.CreateCopy
(newServer$, newDbFile$, [, maxsize% ])
Example
The following example creates a copy of discuss.nsf, located on the Anchorage
server. The new copy, named suggest.nsf, will be placed on the Juno server and
its title will be changed.
'Declare object reference variables
Dim db As NotesDatabase
Dim newDb As NotesDatabase
'Instantiate object reference variables
Set db = New NotesDatabase("Anchorage", "discuss.nsf")
Set newDb = db.CreateCopy ("Juno", "suggest.nsf")
'change the title of the new database
newDb.Title = "Suggestions for Giving Campaign 2001"

Stud ent Gu ide Page No. 44 75


Preview
Le sso n 2 „ Acc essin g Datab ase In fo rma tio n

Creating a New Copy of a Database


Exercise

In this exercise, students will create a button that copies the Inventory database
from the server to their local machines. Students will use this database in future
exercises.
Present the exercise by:
„ Identifying which database and form students will use.
„ Asking if students have any questions before starting the exercise.
„ (Optional) Demonstrating the completed code using the Create a database
button on the Create DB form in the Demos and Activities-Instructor database.
You must add the name of your server to the code before it will work.

After completing the exercise: Have students copy the course documents from the
Inventory - Instructor database and paste them into their student Inventory
databases. This action will:
„ Illustrate the point that no documents are copied when using the CreateCopy
method.
„ Prepare the student Inventory database for use in the Interacting with Users
Programmatically Exercise in Lesson 5: Working with NotesUIDocument.

76 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Les so n 2 „ Acce ssing Datab ase Info rma tio n

Creating a New Copy of a Database


Exercise

In this exercise, you will create a new database and access its properties. Then,
you will open it in the Notes client and examine its contents.

Create a button that copies a database

Perform the following tasks to complete the exercise.


„ Open the Inventory database on the server and explore its contents.
„ In your local Demos and Activities database, create a button on the
CreateDB form with a script that does the following:
„ Creates a copy of the Inventory database on your local machine.
„ Changes the title of the new database to Inventory.
„ Displays a message box stating that the database has been copied and
the name has been changed.
„ Test the code.
„ Open the new database, bookmark it, and verify that it is a copy of the original
database.

Stud ent Gu ide Page No. 45 77


Preview
Le sso n 3 „ Nav ig ati ng th e Domi n o Ob je ct Mo de l to Acc ess ACL In for matio n

3
Navigating the Domino
Object Model to Access
ACL Information

Present the lesson objectives.

78 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L ess on 3 „ N aviga tin g the Do mino Objec t Mod el to Acce ss ACL Info rma tio n

3
Navigating the Domino
Object Model to Access
ACL Information

This lesson focuses on finding a path through the Domino object hierarchy to
access the data you need. The lesson uses the NotesACL and NotesACLEntry
classes as an example. While explaining how to access the ACL, the lesson
introduces LotusScript techniques such as constants and Select...Case
statements.

Objectives

After completing this lesson, you should be able to:


9 Navigate the Domino objects class hierarchy.
9 Retrieve and display the access levels of ACL entries.

Stud ent Gu ide Page No. 46 79


Preview
Le sso n 3 „ Nav ig ati ng th e Domi n o Ob je ct Mo de l to Acc ess ACL In for matio n

Retrieving the Access Level of an ACL


Entry

Describe the path to NotesACLEntry

Explain the diagram showing a part of the object model.


Ask students to provide the path to retrieving ACL levels by looking at the diagram
or using Domino Designer Help.

80 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L ess on 3 „ N aviga tin g the Do mino Objec t Mod el to Acce ss ACL Info rma tio n

Retrieving the Access Level of an ACL


Entry

Use properties of the NotesACLEntry class to retrieve the access level of an ACL
entry using LotusScript.

Finding the path to NotesACLEntry

The following diagram shows the path for accessing the NotesACLEntry class.

Stud ent Gu ide Page No. 47 81


Preview
Le sso n 3 „ Nav ig ati ng th e Domi n o Ob je ct Mo de l to Acc ess ACL In for matio n

Retrieving the Access Level of an ACL Entry...(continued)

Diagram navigating the object model

Work out the path of an object using the object model. Explain what to look for and
how to get started. It may be best to work backwards, starting with ACLEntry and
working up the hierarchy. Draw the path on the whiteboard.

Retrieving ACL levels

Ask students to identify the methods and properties for retrieving the ACL levels.
Add the answers to the path you drew on the whiteboard.

82 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L ess on 3 „ N aviga tin g the Do mino Objec t Mod el to Acce ss ACL Info rma tio n

Retrieving the Access Level of an ACL Entry...(continued)

Navigating the object model

When you examine the object hierarchy, notice the following:


„ The NotesACLEntry class is contained by only one other class: NotesACL.
„ The NotesACL class is contained by only one class: NotesDatabase.
„ The NotesDatabase class is contained by three classes. If you want the
database that is currently executing the script, use the CurrentDatabase
property of the NotesSession class.
The following is the object path for accessing an ACL entry for the current
database:
NotesSessionÆ NotesDatabaseÆ NotesACLÆ NotesACLEntry

Identifying the methods and properties needed

Once you determine the object path, search the list of properties and methods of
each class that retrieve each object in the path.

To Access… Use This Property or Method

The session New method of NotesSession

The current database CurrentDatabase property of NotesSession

The Access Control List ACL property of NotesDatabase

An ACL entry GetEntry method of NotesACL

An Access level for an entry Level property of NotesACLEntry

Stud ent Gu ide Page No. 48 83


Preview
Le sso n 3 „ Nav ig ati ng th e Domi n o Ob je ct Mo de l to Acc ess ACL In for matio n

Retrieving the Access Level of an ACL Entry...(continued)

Retrieve an ACL entry

In this demonstration, first show what the GetEntry method does in the Notes
Client, then show the code behind the method in Designer.
„ In the Notes Client, open the Select and ACL Access form.
„ Click the Get the first ACL Entry-demo button.
„ Open the Select and ACL Access form in Domino Designer.
„ Select the Get the first ACL entry-demo button.
„ Explain each line of the code
„ Relate the path on the whiteboard that retrieves the ACL entry to the
LotusScript statements.

Retrieving the access level of an entry

Add the code that retrieves the level of the ACL entry to the Get the first ACL
Entry-demo button.
Ask how you get the name of the current user.
For example:

84 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L ess on 3 „ N aviga tin g the Do mino Objec t Mod el to Acce ss ACL Info rma tio n

Retrieving the Access Level of an ACL Entry...(continued)

Retrieving an ACL entry

The NotesACL class represents an access control list of a database. It provides


properties and methods for retrieving and manipulating data in the ACL.
The GetEntry method retrieves a particular ACL entry, given the name.
Syntax
The following is the syntax for instantiating a NotesACLEntry object:
Set notesACLEntry = notesACL.GetEntry(name$)
Example
The following code sample accesses the ACL entry for the LocalDomainServers
in the current database:
Dim s As NotesSession
Dim db As NotesDatabase
Dim acl As NotesACL
Dim aclentry As NotesACLEntry
Set s = New NotesSession
Set db = s.CurrentDatabase
Set acl = db.ACL
Set aclentry = acl.GetEntry ("LocalDomainServers")

Retrieving the access level of an entry

The NotesACLEntry represents an entry in the access control list. Each entry is
identified by the name of the user or group.
To retrieve the level associated with the user or group, use the Level property. The
Level property returns a constant.

Stud ent Gu ide Page No. 49 85


Preview
Le sso n 3 „ Nav ig ati ng th e Domi n o Ob je ct Mo de l to Acc ess ACL In for matio n

Retrieving the Access Level of an ACL Entry...(continued)

Introduce constants

Introduce constants and how to use them.

Using constants

Explain where constants are defined and how to incorporate them in scripts.

86 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L ess on 3 „ N aviga tin g the Do mino Objec t Mod el to Acce ss ACL Info rma tio n

Retrieving the Access Level of an ACL Entry...(continued)

Constants

A constant is a named, fixed value. It specifies a location in memory that contains


a value that is known at compile time. This value cannot be changed while the
application is running. Using constants in scripts makes the code easier to read
and allows the value to be centrally maintained.
For example, instead of using if (db.IsOpen = -1), it is easier to read if you use if
(db.IsOpen = True). Later, if you want to change the value that represents True,
you can change it once and all code that uses it will continue to run.

Defining constants

Constants are defined as follows:


„ Internally in LotusScript. For example, the following constants are always
available to scripts: TRUE, FALSE, PI, NULL.
„ Externally in files, and imported using the %Include directive. For example, the
LSCONST.LSS file contains constants defined for use with certain LotusScript
functions like Messagebox .
„ By the developer, using the CONST keyword. For example,
Const Pending = 0.

Stud ent Gu ide Page No. 50 87


Preview
Le sso n 3 „ Nav ig ati ng th e Domi n o Ob je ct Mo de l to Acc ess ACL In for matio n

Retrieving the Access Level of an ACL Entry...(continued)

Interpreting the access levels

Ask what should be returned instead of an integer.

88 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L ess on 3 „ N aviga tin g the Do mino Objec t Mod el to Acce ss ACL Info rma tio n

Retrieving the Access Level of an ACL Entry...(continued)

Interpreting the access levels

The ACLEntry class provides a set of constants that represent each possible
access level. You do not need to include LSCONST.LSS or any other file to use
these constants.
The following table describes the constant and integer values for each access
level.

Access Level Constant (Integer Value)

No Access ACLLEVEL_NOACCESS (0)

Depositor ACLLEVEL_DEPOSITOR (1)

Reader ACLLEVEL_READER (2)

Author ACLLEVEL_AUTHOR (3)

Editor ACLLEVEL_EDITOR (4)

Designer ACLLEVEL_DESIGNER (5)

Manager ACLLEVEL_MANAGER (6)

Stud ent Gu ide Page No. 51 89


Preview
Le sso n 3 „ Nav ig ati ng th e Domi n o Ob je ct Mo de l to Acc ess ACL In for matio n

Retrieving the Access Level of an ACL Entry...(continued)

Using the Select Case statement

This construct is like an iterative If statement. We will use the Select Case
construct to convert integer constants to strings that hold meaningful text for a
user.

Run the Select Case statement

Use the Select and ACL Access form and explain the code in the Select Case
button. The code is also the example in the Student Guide.
„ In the Notes Client, open the Select and ACL Access form.
„ Click the SelectCase-demo button.
„ Open the form in Designer and change the value of num to 2.
„ Preview the form in the Client and re-select the SelectCase-demo button.

Find the path to another object or piece of information

As a review, and to get students more familiar with traversing the object model,
ask students to find the path to some other objects or piece of information. For
example, remove a form from the current database or access the creation date of
a view. Then, as a class discussion, determine the properties and methods of all
the objects.

90 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L ess on 3 „ N aviga tin g the Do mino Objec t Mod el to Acce ss ACL Info rma tio n

Retrieving the Access Level of an ACL Entry...(continued)

Using the Select Case statement

The Select Case statement is useful when you need to execute a block of
statements based on the value of an expression.
Syntax
Select Case selectExpr
[Case condList [statements]]
[Case condList [statements]]
...
[Case Else [statements ]]
End Select

Example
The following example displays a message with the num value and the
appropriate suffix, such as 1st or 2nd.
'Declare variable for number between 1 and 10
Dim num As Integer
'Declare variable for concatenation
Dim ord As String
'Set value of number
num = 1
Select Case num
Case 1
ord = "st"
Case 2
ord = "nd"
Case 3
ord = "rd"
Case Else
ord = "th"
End Select
Messagebox "You made the : & num & ord & " selection."

Stud ent Gu ide Page No. 52 91


Preview
Le sso n 3 „ Nav ig ati ng th e Domi n o Ob je ct Mo de l to Acc ess ACL In for matio n

Retrieving Your Access Level Exercise

Present the exercise by:


„ Identifying which database and form students will use.
„ Identifying the name of the classroom server.

92 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L ess on 3 „ N aviga tin g the Do mino Objec t Mod el to Acce ss ACL Info rma tio n

Retrieving Your Access Level Exercise

In this exercise, you will use LotusScript and the Domino objects to retrieve your
access level to a database on the instructor’s server and display it in a message
box.
For example, if Molly Kennedy has Author access to the database, the script
displays the following message:
The level of access for Molly Kennedy is Author.

Display the access level for the Students group

Perform the following tasks to complete the exercise.


„ In the Demos and Activities database, create a button on the ACL Entry
Exercise form. Add LotusScript to the button that does the following:
„ Opens the DEMACTLS-INST.NSF database on the classroom server.
„ Accesses the Students ACL entry.
„ Uses a select case statement to display text representing the ACL level.
„ Displays the name of the ACL entry and the access level with a message
box.
„ Test the code by previewing the form in Notes and clicking the button. Open
the ACL of the database and verify the access level your script retrieved.

Stud ent Gu ide Page No. 53 93


Preview
Le sso n 3 „ Nav ig ati ng th e Domi n o Ob je ct Mo de l to Acc ess ACL In for matio n

94 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


B
Navigating the User
Interface Classes

Lesson 4 Working with NotesUIWorkspace


Lesson 5 Working with NotesUIDocument

© Cop yr ig ht IB M Co rpo ratio n 200 2. All rig hts re serv ed.


Preview
Le sso n 4 „ Wo r k i ng wi t h N o te s U I Wo r k s pac e

4
Working with
NotesUIWorkspace

Present the objectives from the Student Guide.

96 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Le sso n 4 „ Wo rkin g with No tesUIWo rks pa ce

4
Working with
NotesUIWorkspace

This lesson introduces the user interface (UI) or front-end classes. It focuses on
interacting with the user through the NotesUIWorkspace class. It also
differentiates between functions and subroutines.

Objectives

After completing this lesson, you should be able to:


9 Describe the user interface classes.
9 Use methods of the NotesUIWorkspace class.
9 Gather user input using the prompt method.

Stud ent Gu ide Page No. 56 97


Preview
Le sso n 4 „ Wo r k i ng wi t h N o te s U I Wo r k s pac e

Programming the Notes User Interface

Explain the user interface class hierarchy

Use the diagram from the Student Guide.

98 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Le sso n 4 „ Wo rkin g with No tesUIWo rks pa ce

Programming the Notes User Interface

The user interface classes define information and functionality available to the
Notes client. Using these classes, application developers can write scripts that run
as users interact with the application and manipulate the elements that users
actually see.

The user interface class hierarchy

The following diagram shows the user interface (UI) class hierarchy.

Stud ent Gu ide Page No. 57 99


Preview
Le sso n 4 „ Wo r k i ng wi t h N o te s U I Wo r k s pac e

Programming the Notes User Interface...(continued)

LotusScript and Web browsers

It is important to note that LotusScript does not work in Web browsers, but it can
be invoked on the server based on a Web client request.

The NotesUIWorkspace class

The NotesUIWorkspace class is like the NotesSession class. It provides content


within the application and is used to access and create the other objects available
in the user interface.

100 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Le sso n 4 „ Wo rkin g with No tesUIWo rks pa ce

Programming the Notes User Interface...(continued)

Programming the Web user interface

LotusScript does not affect the Web user interface, because browsers do not
interpret LotusScript. To manipulate the user interface of a Web browser, use
JavaScript. Lotus Notes and Domino Designer support JavaScript, which allows
application developers to work with one language when developing applications
that exist on the Web and in Notes.

The NotesUIWorkspace class

NotesUIWorkspace represents the current workspace window in the Notes client.


It includes the current database, current document, and current view. For
example, when a user is looking at a view, the workspace contains the database
and the view.
The workspace class also provides methods for changing the user interface. For
example, opening a database, adding a database to the workspace, or composing
a new document.

Stud ent Gu ide Page No. 58 101


Preview
Le sso n 4 „ Wo r k i ng wi t h N o te s U I Wo r k s pac e

Adding a Database to the Workspace

AddDatabase method

Ask students to give you the code to add a database to the workspace.

Describe the OpenDatabase method

Describe how this method works.

102 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Le sso n 4 „ Wo rkin g with No tesUIWo rks pa ce

Adding a Database to the Workspace

Many user functions can be scripted using the NotesUIWorkspace class. For
example, adding a database to the workspace and opening a database.

AddDatabase method

The AddDatabase method of the NotesUIWorkspace class adds the database


icon to the workspace (or to the list of bookmarks).
Syntax
Call notesUIWorkspace.AddDatabase (server$, filename$)
Example
The following example adds an icon for the discuss.nsf database, located on
server01, to the Notes workspace.
Dim uiws As NotesUIWorkspace
Set uiws = New NotesUIWorkspace
Call uiws.AddDatabase ("server01", "discuss.nsf")

OpenDatabase method

The OpenDatabase method opens an existing database to a specific view. This


method does not return any value. If the database opens correctly, use the
CurrentDatabase property to access it.
Syntax
Call notesUIWorkspace.OpenDatabase (server$, file$, view$, key$,
newInstance, temp)
Example
The following example opens the discuss.nsf database to the All by Category
view.
Dim uiws As NotesUIWorkspace
Set uiws = New NotesUIWorkspace
Call uiws.OpenDatabase ("server01", "discuss.nsf", “All by
Category”)

Stud ent Gu ide Page No. 59 103


Preview
Le sso n 4 „ Wo r k i ng wi t h N o te s U I Wo r k s pac e

Adding a Database to the Workspace...(continued)

How functions differ from subroutines

We are about to introduce the AddDatabase method of NotesUIWorkspace. This


method is a subroutine, and it is important to note the differences.

Invoking subroutines

Describe the two ways of invoking subroutines. The course manual typically uses
the Call statement because it is easier to read. Advise students to pick a way and
be consistent.

104 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Le sso n 4 „ Wo rkin g with No tesUIWo rks pa ce

Adding a Database to the Workspace...(continued)

How functions differ from subroutines

Methods can be either functions or subroutines. The difference between functions


and subroutines is:
„ Subroutines do not return a value.
„ Functions always return a value of a specific data type.
„ That data type can be an integer, a string, an array, or an object.
Generally, when a function is invoked, it must be set equal to a variable of a
compatible data type.

Invoking subroutines

To invoke a subroutine in LotusScript, use either of the following syntax options:


Call subName (arglist)
subName arglist

Use the Call statement to invoke LotusScript subroutines. For example, use Call
to invoke the AddDatabase and OpenDatabase methods of the
NotesUIWorkspace class.

Stud ent Gu ide Page No. 60 105


Preview
Le sso n 4 „ Wo r k i ng wi t h N o te s U I Wo r k s pac e

Adding a Database to the Workspace...(continued)

Add a database to the workspace

„ Identify which database and form students will use.


„ Remind students to delete their copy of the Inventory database and its
bookmark before running the code again.

106 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Le sso n 4 „ Wo rkin g with No tesUIWo rks pa ce

Adding a Database to the Workspace...(continued)

Add a database to the workspace

In this guided practice, write a small script to add the database created in the
Creating a New Copy of a Database Exercise in Lesson 2 to the workspace.
Follow these steps to complete this guided practice.

Step Action

1 Open the CreateDB form in your Demos and Activities database.

2 Click Create a database.

3 Add the following code after the statement that sets the database title and
before the End Sub statement:
Dim w As NotesUIWorkspace
Set w = New NotesUIWorkspace
Call w.AddDatabase ("", "Inventory.nsf")

4 Save and compile the form.

5 Delete the Inventory database you copied during the exercise in Lesson 2.

6 Remove the icon and/or bookmark for this database in your Notes client.

7 Preview the form in Notes and click Create a Database. Check the
workspace (or list of bookmarks) for the new icon.

Stud ent Gu ide Page No. 61 107


Preview
Le sso n 4 „ Wo r k i ng wi t h N o te s U I Wo r k s pac e

Gathering User Input

The prompt method

Describe the prompt method. It works the same as the @prompt function. It is a
good way to gather small amounts of information from users.

108 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Le sso n 4 „ Wo rkin g with No tesUIWo rks pa ce

Gathering User Input

The NotesUIWorkspace provides a method to capture information from the user


through a pop-up dialog box.

The prompt method

The prompt method is an interface to the @Prompt function. It displays a dialog


box with a title, message, and buttons so the user can make decisions about the
flow or content of the script. The prompt method returns a value based on the
user’s action in the dialog box.
Syntax
variant = NotesUIWorkspace.Prompt (type%, title$, prompt$,
[default ] [, values ] )
Example
The following example displays a prompt box, named Message, with three
buttons, Yes, No, and Cancel along with the message, Do you wish to save the
document?
result = NotesUIWorkspace.Prompt (PROMPT_YESNOCANCEL,_
"Message", "Do you wish to save the document?")

Stud ent Gu ide Page No. 62 109


Preview
Le sso n 4 „ Wo r k i ng wi t h N o te s U I Wo r k s pac e

Gathering User Input...(continued)

Types of prompt dialog boxes

Briefly explain the table of dialog box options. The types of dialog boxes available
to the prompt method are the same as the @prompt function.

Illustrate the functionality of using the prompt method.

Either explain the code behind the NotesUIWorkspace, Prompt Practice button or
delete the code before class and enter it in front of the students. Preview the form
and click the button.

110 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Le sso n 4 „ Wo rkin g with No tesUIWo rks pa ce

Gathering User Input...(continued)

Types of Prompt dialog boxes

The Prompt dialog box can be one of several types. The types are defined by
constants. Each type of prompt allows the user different options and returns
values to indicate the user’s choice.
The following table shows the types of Prompt dialog boxes and their return
values.

Type of Dialog Return Value

PROMPT_OK „ 1

PROMPT_YESNO „ 1 if user clicks Yes


„ 0 if user clicks No

PROMPT_YESNOCANCEL „ 1 if user clicks Yes


„ 0 if user clicks No
„ -1 if user clicks Cancel

PROMPT_OKCANCELEDIT „ Text value user enters if the user clicks OK


„ Empty string if user clicks Cancel

PROMPT_OKCANCELLIST „ Text value user selects if the user clicks OK


„ Empty string if user clicks Cancel

PROMPT_OKCANCELCOMBO „ Text value user selects (from drop-down


list) if the user clicks OK
„ Empty string if user clicks Cancel

PROMPT_OKCANCELEDITCOMBO „ Text value user selects or enters if the user


clicks OK
„ Empty string if user clicks Cancel

PROMPT_OKCANCELLISTMULT „ List of text values the user selects if the


user clicks OK
„ Empty string if user clicks Cancel

PROMPT_PASSWORD „ Text value user enters if the user clicks OK


„ Empty string if user clicks Cancel

Stud ent Gu ide Page No. 63 111


Preview
Le sso n 4 „ Wo r k i ng wi t h N o te s U I Wo r k s pac e

Asking for User Input Exercise

In this exercise, students use the prompt method and If...Then...Else statements
to ask users a question and confirm the response.
The goal of the exercise is to use the prompt and capture the user response. How
to mail the description is of no concern at this point.

112 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Le sso n 4 „ Wo rkin g with No tesUIWo rks pa ce

Asking for User Input Exercise

In this exercise, you will add a button requesting that a course description be
delivered by mail or by e-mail.

Create a button that prompts users for information

To complete this exercise, create a button on the Course form in the Inventory
database. Add code to the button that does the following:
„ Displays a message asking if the course description should be sent by mail,
and three buttons (Yes, No, and Cancel).
„ Displays another message based on the button the user clicks.
The following table describes the desired behavior of the script.

If the User Initially Clicks… Then…


Yes Display a prompt confirming that the course
description will be sent by mail.
No Display a prompt confirming that the course
description will be sent by e-mail.
Cancel Display a prompt confirming that the
request has been canceled.

Note: In the final application, the document would be sent to the user's e-mail
address. We will examine how to do that later in this course.

Stud ent Gu ide Page No. 64 113


Preview
Le sso n 5 „ Wo r k i ng wi t h N o te s U I D oc ume nt

5
Working with
NotesUIDocument

Present the lesson objectives.

114 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Le sso n 5 „ Wo r k i ng wi t h N o te s U I D oc ume nt

5
Working with
NotesUIDocument

This lesson introduces the NotesUIDocument class. It focuses on accessing and


modifying data in the document that is currently opened in the Notes client. At the
end of the lesson, a new document will be created and populated with items and
data so that it can be displayed with an existing form.

Objectives

After completing this lesson, you should be able to:


9 List commonly used properties of the current document.
9 Access the current document.
9 Create a new document.
9 Retrieve field values from the current document using the FieldGetText
method.
9 Change field values on the current document using the FieldSetText method.

Stud ent Gu ide Page No. 65 115


Preview
Le sso n 5 „ Wo r k i ng wi t h N o te s U I D oc ume nt

Accessing the Current Document

Retrieving the current document

Ask the students to identify the path to the NotesUIDocument.


The NotesUIDocument does not have the New methods to instantiate itself. It
must come from the method or property of another class. The first place to look for
a UI object is NotesUIWorkspace.

Using the CurrentDocument Property of the


NotesUIWorkspace

Ask students to provide the code to access the Current Document property and
write their answers on the whiteboard.

116 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Le sso n 5 „ Wo r k i ng wi t h N o te s U I D oc ume nt

Accessing the Current Document

The current document is the one being displayed in the Notes client at the time the
script executes. It is accessible through the NotesUIWorkpace and is represented
by the NotesUIDocument class.

Retrieving the current document

To access the current document, use any of the following from the
NotesUIWorkspace class:
„ CurrentDocument property
„ ComposeDocument method
„ EditDocument method

Using the CurrentDocument property of the


NotesUIWorkspace

Use the CurrentDocument method of the NotesUIWorkspace class to access the


document currently open in the Notes client.
This property returns an object reference to the document currently opened in the
Notes client. This property refers only to an open document, not a document that
is selected in a view.
Syntax
Use the following syntax for instantiating the current document:
Set notesUIDocument = notesUIWorkspace.CurrentDocument
Example
The following code sample accesses the current document:
Dim w As NotesUIWorkspace
Dim uidoc As NotesUIDocument
Set w = New NotesUIWorkspace
Set uidoc = w.CurrentDocument

Stud ent Gu ide Page No. 66 117


Preview
Le sso n 5 „ Wo r k i ng wi t h N o te s U I D oc ume nt

Accessing the Current Document...(continued)

The NotesUIDocument class

Define NotesUIDocument. Open Domino Designer Help to show the complete list
of properties and methods.

118 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Le sso n 5 „ Wo r k i ng wi t h N o te s U I D oc ume nt

Accessing the Current Document...(continued)

The NotesUIDocument class

The NotesUIDocument class contains properties and methods representing the


in-memory document in a Notes client.
Some commonly used properties include:
„ IsNewDoc
„ WindowTitle
„ EditMode
Some commonly used methods include:
„ GotoField
„ Refresh
„ Save
„ Send

Stud ent Gu ide Page No. 67 119


Preview
Le sso n 5 „ Wo r k i ng wi t h N o te s U I D oc ume nt

Composing a New Document with


LotusScript

Display ComposeDocument in Help

Open Domino Designer Help and display the document describing the
ComposeDocument method of the NotesUIWorkspace class. Describe the
parameters.
Ask students about the benefits of windowWidth and windowHeight. The answer
is that you can simulate a dialog box, which uses a form that you have already
built.

Using the Call statement to invoke functions

The ComposeDocument method is a function that returns an object reference to


the new document. To simply compose the document and allow the user to enter
data and save it, you do not need that object reference. To avoid having
LotusScript return it, use the Call keyword as you would with a subroutine.

120 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Le sso n 5 „ Wo r k i ng wi t h N o te s U I D oc ume nt

Composing a New Document with


LotusScript

Using the ComposeDocument method

The ComposeDocument method of the NotesUIWorkspace class allows a script


to create a new document. This method is the same as choosing a form name
from the Create menu of the Notes client. The specified form is opened and a new
document is created in memory.
Syntax
Set notesUIDocument = notesUIWorkspace.ComposeDocument( [ server$ [,
dbfile$ [, form$ [, windowWidth# [, windowHeight# ]]]]] )
Example
The following statement creates a new document. It has the same effect as
choosing Create Æ Main Topic from the Notes client menu.
Set uidoc = w.ComposeDocument ("server01", "discuss.nsf", "Main
Topic")

Using the Call statement to invoke functions

Use the Call statement to invoke a function when the function’s return value is not
important. The Call statement does not return the function’s value.
Example
The following example creates a new document based on the Main Topic form
located in the discuss.nsf database
Call w.ComposeDocument ("server01", "discuss.nsf", "Main
Topic")

Stud ent Gu ide Page No. 68 121


Preview
Le sso n 5 „ Wo r k i ng wi t h N o te s U I D oc ume nt

Retrieving Field Values from the Current


Document

The FieldGetText method

Present the syntax and the example from the Student Guide. Note that the field
can be referenced with a variable.
Ask students to find the method for updating a field value. They will have to refer
to the NotesUIDocument class in Help. Ask them to identify the arguments.
Point out that the method returns a string value. Regardless of what field type the
data is coming from, it is returned to LotusScript as text.

Converting to different data types

Open Domino Designer Help and show some examples of the conversion
functions.

122 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Le sso n 5 „ Wo r k i ng wi t h N o te s U I D oc ume nt

Retrieving Field Values from the Current


Document

LotusScript can read values from the currently displayed document by referencing
the fields.

Using the FieldGetText method

As the name implies, this method returns a text value from a specified field. If the
value needs to be used in a calculation it must be explicitly converted to a numeric
or datetime data type.
Syntax
textValue$ = notesUIDocument.FieldGetText([fieldName$])
Example
The following example returns data entered in the FirstName field.
fname$ = uidoc.FieldGetText("FirstName")

Converting to different data types

LotusScript provides several built-in functions for explicitly converting a value’s


data type. These functions include the following:
„ Ccur converts a numeric value or string into currency.
„ Cdat converts a numeric value or string to a date/time value.
„ CDbl converts a numeric value or string to a Double data type.
„ Cint converts a numeric value or string to an Integer data type.
„ CStr converts a numeric value, date value, or string to a String data type.

Stud ent Gu ide Page No. 69 123


Preview
Le sso n 5 „ Wo r k i ng wi t h N o te s U I D oc ume nt

Changing Field Values on the Current


Document

Switching the document to edit mode

Before you can set the value of a field on the current document, you must place it
in edit mode. To do this in LotusScript, set the EditMode property to True.

Using the FieldSetText method

Point out that variables can represent the argument values, which allows you to
pull data from other sources and automatically update the document.

Display the CurrentDocument Demo code

Open the UIDocument-Demo form and display the code in the


CurrentDocument Demo button. Ask students to tell you what the button will do
and then show them.
Note: You do not need to refresh the form to retrieve the field value.

124 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Le sso n 5 „ Wo r k i ng wi t h N o te s U I D oc ume nt

Changing Field Values on the Current


Document

The current document must be in edit mode in order to change its field values.
Once the document is in edit mode, the script can modify the field values with text.

Switching the document to edit mode

Enable the EditMode property of the NotesUIDocument class before modifying


fields.
Example
The following statement places the current document in edit mode.
uidoc.EditMode = True

Using the FieldSetText method

The FieldSetText method sets the value of a specified field. The value must be a
text value.
Syntax
Use the following syntax to set a field value on the current document.
Call notesUIDocument.FieldSetText(fieldName$, textValue$)
Example
The following code statement sets the value of the FirstName field, on the current
document, to Molly.
Call uidoc.FieldSetText("FirstName", "Molly")

Stud ent Gu ide Page No. 70 125


Preview
Le sso n 5 „ Wo r k i ng wi t h N o te s U I D oc ume nt

Changing Field Values on the Current Document...(continued)

Set field values

In this guided practice, students will concatenate two field values together and
place the result in a third field.
„ Review the purpose of the Entering event.
„ Review the guided practice with students to make sure they understand. Make
sure they understand why they used the plus sign instead of the ampersand.
If some students finish early or need an additional challenge, have them add a
Salary field of type currency. Assign a value to it in its Entering event to
demonstrate FieldSetText and how to convert the value to a string.

126 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Le sso n 5 „ Wo r k i ng wi t h N o te s U I D oc ume nt

Changing Field Values on the Current Document...(continued)

Set field values

In this guided practice, you will write a script that concatenates the values in the
first and last name fields and places that value in the FullName field.
Follow these steps to set the field values.

Step Action

1 In the Demos and Activities database, open the Concatenate field-


Activity form.
2 Select the FullName field.
3 In the Programmers pane, select the Entering event
4 Add the following code to the event:
'get the uiworkspace
Dim w As NotesUIWorkspace
Set w = New NotesUIWorkspace
'get current document
Dim uidoc As NotesUIDocument
Set uidoc = w.CurrentDocument
'populate fullname field with values
'from firstname and lastname field
Call uidoc.FieldSetText ("FullName", _
uidoc.fieldgettext("FirstName")& " " _
& uidoc.fieldgettext("LastName"))

5 Choose File Æ Save to compile the code and save the form.
6 Preview the form in Notes.
7 Enter text in the FirstName and LastName fields.
8 Place the cursor in the FullName field (click or tab) and observe the
results of the Entering script.

Stud ent Gu ide Page No. 71 127


Preview
Le sso n 5 „ Wo r k i ng wi t h N o te s U I D oc ume nt

Accessing the Current Document


Through NotesUIDocument Events

Describe NotesUIDocument events

Describe the NotesUIDocument events and provide some examples for using
them.

Adding code to NotesUIDocument events

Code is added to the events through the form in Domino Designer.


Explain the Source parameter. Each event provides an instantiation of the current
document. Domino passes into the event as a parameter and you can use it in
code. This saves a step of instantiating a NotesUIWorkspace object to access the
current document.

128 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Le sso n 5 „ Wo r k i ng wi t h N o te s U I D oc ume nt

Accessing the Current Document


Through NotesUIDocument Events

Events occur when the user performs an action within the user interface. The
NotesUIDocument provides several events that can be used to trigger scripts.

NotesUIDocument events

The following NotesUIDocument events are triggered in the Notes client and
accept LotusScript code:
„ Queryopen
„ PostOpen
„ Querymodechange
„ Postmodechange
„ Postrecalc
„ QuerySave
„ Postsave
„ Queryclose

Adding code to NotesUIDocument events

NotesUIDocument events are exposed through the form design elements in


Domino Designer. All of the NotesUIDocument events pass an object reference
for the current document into the subroutine as the parameter Source. This
means that the NotesUIWorkspace does not need to be accessed in order to
retrieve the current document.

Stud ent Gu ide Page No. 72 129


Preview
Le sso n 5 „ Wo r k i ng wi t h N o te s U I D oc ume nt

Accessing the Current Document Through


NotesUIDocument Events...(continued)

Describe the QuerySave event

Describe the QuerySave event and explain the example.

Running code to validate a field

Use code from the ValidateField-demo form, the QuerySave event, to illustrate a
simple field validation routine that runs when the form is saved.

Describe the PostOpen event

Describe the PostOpen event and explain the example.

130 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Le sso n 5 „ Wo r k i ng wi t h N o te s U I D oc ume nt

Accessing the Current Document Through


NotesUIDocument Events...(continued)

Using the QuerySave event

Use the QuerySave event for functionality that must run before the document is
saved. This event is commonly used to validate several field values before
allowing the user to save a document.
Example
The following script checks the value in the LastName field before saving the
document. If the value is null, it displays a message to the user and stops the save
procedure.
Sub QuerySave(Source As NotesUIDocument,Continue As Variant)
Dim lname As String
lname = Source.FieldGetText ("LastName")
If lname = "" Then
Messagebox "Please enter your last name. "
Continue = False
End If
End Sub

Using the PostOpen event

Use the PostOpen event for functionality that should run before the user has
access to the document but after it is loaded into memory. This event is commonly
used to inform the user about the document or to warn of any restrictions for using
the document.
Example
The following script examines the CheckedOut field of the current document and
displays a message to the user if the document being opened has already been
checked out.
Sub PostOpen (Source As NotesUIDocument)
If (Source.FieldGetText ("CheckedOut") = "Yes") Then
Messagebox "This document is currently checked out. "
End If
End Sub

Stud ent Gu ide Page No. 73 131


Preview
Le sso n 5 „ Wo r k i ng wi t h N o te s U I D oc ume nt

Accessing the Current Document Through


NotesUIDocument Events...(continued)

Display the state of a document when it opens

In this guided practice, students will write code that displays a prompt if the
document is new.
„ Review the purpose of the PostOpen event.
„ Describe the behavior of the IsNew property.

132 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Le sso n 5 „ Wo r k i ng wi t h N o te s U I D oc ume nt

Accessing the Current Document Through


NotesUIDocument Events...(continued)

Display the state of a document when it opens

In this guided practice, you will write a script to determine if the document that the
user is opening is a new document. If the document is new, display a message to
the user that this is a new document.
Follow these steps to complete this guided practice.

Step Action

1 In the Demos and Activities database open the Movie form.

2 Add the following code to the PostOpen event of the form:


'instantiate the workspace for prompts
Dim w As NotesUIWorkspace
Set w = New NotesUIWorkspace
'use source to test the current document,
'if it is new, display a prompt
If Source.IsNewDoc Then
Call w.Prompt(PROMPT_OK, "New", _
"This document is new.")
End If

3 Choose File Æ Save to compile the code and save the form.

4 Preview the form in Notes.


Result: The PostOpen event triggers and because you previewed it, the
prompt displays, stating that the document is new.

5 Add some data. Save and close the document.

6 Open the Movies view.

7 Open the document you just created.


Result: The prompt should not display this time because the IsNewDoc
property has been set to False.

Stud ent Gu ide Page No. 74 133


Preview
Le sso n 5 „ Wo r k i ng wi t h N o te s U I D oc ume nt

Interacting with Users


Programmatically Exercise

In this exercise, students will display a personalized thank you message when a
user saves a document.
„ Demonstrating the completed exercise.
„ You may elect to perform the first three bullet items in the exercise as a group
discussion.
„ Review the exercise with students by displaying and reviewing the answer to
make sure they understand.

134 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Le sso n 5 „ Wo r k i ng wi t h N o te s U I D oc ume nt

Interacting with Users


Programmatically Exercise

In this exercise, add some user interaction to the Student form in the Inventory
database. Add code displaying a message to the users, thanking them for signing
up for a particular course. For example:
Thank you Frank Grimes for signing up for the Ceramics course.
The message should use the current user’s name and the course name from the
current document. When they test the code, students should be told to open a
course document in the Course Summary view, and click Add a student.

Display a message when users save a document

Perform the following tasks to complete this exercise:


„ Determine the event where the code should be placed.
„ Determine the needed classes.
„ Determine the methods and properties of those needed classes.
„ Write the code.
„ Test the code.

Stud ent Gu ide Page No. 75 135


Preview
Le sso n 5 „ Wo r k i ng wi t h N o te s U I D oc ume nt

136 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


C
Creating and Modifying
Documents
Lesson 6 Accessing Data in Documents
Lesson 7 Writing Data to Documents
Lesson 8 Using ViewEntry and Document Collections

© Cop yr ig ht IB M Co rpo ratio n 200 2. All rig hts re serv ed.


Preview
Le sso n 6 „ Acc essin g Data in Doc ume nts

6
Accessing Data in
Documents

Present the lesson objectives.

138 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L es son 6 „ Acce ssing D ata in D ocu men t s

6
Accessing Data in
Documents

This lesson starts by showing how to retrieve a document and how to locate its
properties and item values. It then moves on to looping through a view to find a
particular document. Then, the lesson introduces the NotesViewEntry class for a
more direct route to application data.

Objectives

After completing this lesson, you should be able to:


9 Retrieve data from a document.
9 Retrieve data from multiple documents in a view.
9 Search documents in a view for specific item values.
9 Retrieve data displayed in a view.
9 Retrieve multiple values from an item.

Stud ent Gu ide Page No. 78 139


Preview
Le sso n 6 „ Acc essin g Data in Doc ume nts

Accessing Documents with LotusScript

Ask students to give you the steps that a user would use to access a document in
a client.
The steps a program must execute are essentially the same.

The NotesSession class

Describe the NotesSession class and how to instantiate it.

CurrentDatabase and GetDatabase

Describe the CurrentDatabase property and GetDatabase method of


NotesSession and when to use each.

140 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L es son 6 „ Acce ssing D ata in D ocu men t s

Accessing Documents with LotusScript

When accessing documents with LotusScript, consider the process a user


typically follows to select a document in the Notes Client.
„ The user must be in the Notes client.
„ From the Notes client, the user opens a database.
„ Inside the database, the user opens a view.
„ The user then scans the view and selects the document based on the data in
the view columns.

Creating a session

The NotesSession class represents the environment in which the script runs. It is
very similar to a user being in the Notes client. From the session, a script can
open a database and read information about the environment (such as the current
user name and the version of Notes).
To create a session object, use the following syntax:
Dim s As NotesSession ' declare variable for the session
Set s = New NotesSession ' instantiate object

Opening a database

There are several options for opening a database in LotusScript. From a session
object, you can use the CurrentDatabase property to retrieve the database in
which the script is currently executing. To open another database, use the
GetDatabase method.
Example
' Declare object ref variables
Dim s As NotesSession
Dim db As NotesDatabase
Dim db2 As NotesDatabase
' Instantiate session object
Set s = New NotesSession
' Instantiate database objects
Set db = s.CurrentDatabase
Set db2 = s.GetDatabase ("server01", "discuss.nsf")

Stud ent Gu ide Page No. 79 141


Preview
Le sso n 6 „ Acc essin g Data in Doc ume nts

Accessing Documents with LotusScript...(continued)

The GetView method

Describe the GetView method and how to access a view from a database.

Accessing a document by its column value

Explain that using the GetDocumentByKey method of NotesView is similar to


using @DBColumn.

142 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L es son 6 „ Acce ssing D ata in D ocu men t s

Accessing Documents with LotusScript...(continued)

Opening a view

Once a database object is instantiated, you can use the GetView method of the
NotesDatabase class to open any view within the database.
Example
The following code retrieves the Topics view from the current database.
' Declare object ref variables
Dim s As NotesSession
Dim db As NotesDatabase
Dim v As NotesView
' Instantiate session object
Set s = New NotesSession
' Instantiate database object
Set db = s.CurrentDatabase
' Instantiate view object
Set v = db.GetView ("Topics")

Accessing a document by its column value

The GetDocumentByKey method of the NotesView class returns a document


based on its column value(s) in the view.
Example
The following code retrieves the document that displays Introduction to XML in
the first column of the White Papers view.
' declare object ref variables
Dim s As NotesSession
Dim db As NotesDatabase
Dim v As NotesView
Dim doc As NotesDocument
' instantiate session object
Set s = New NotesSession
' instantiate database object
Set db = s.CurrentDatabase
' instantiate view object
Set v = db.GetView ("White Papers")
' retrieve the document based from the view
Set doc = v.GetDocumentByKey ("Introduction to XML")

Stud ent Gu ide Page No. 80 143


Preview
Le sso n 6 „ Acc essin g Data in Doc ume nts

Retrieving Document Properties

The NotesDocument class

Describe the NotesDocument class and its properties and methods.


Open Domino Designer Help for a complete list of methods and properties.

Retrieving document properties

Discuss the example from the Student Guide.

Accessing document properties

„ Open the Document Retrieval form, in the Demos and Activities-Instructor


database to illustrate how to access a document property.
„ Explain the code behind the Get Document By Key button.
„ Show the results by selecting the button in the Notes Client.
Result: You will see the document’s UNID
„ Leave the form open in Designer.

144 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L es son 6 „ Acce ssing D ata in D ocu men t s

Retrieving Document Properties

The NotesDocument class provides access to the information that appears in the
Document Properties box.

Properties of the NotesDocument class

The properties of the NotesDocument class represent the data available through
the Document Properties box. For example:
„ NoteID
„ Created
„ LastModified
„ Size
The NotesDocument class provides other properties that describe the document.
For example:
„ IsNewNote
„ IsResponse
„ ParentDocumentUNID

Retrieving document properties

The following code displays document properties in message boxes.


' Declare object ref variables
Dim s As NotesSession
Dim db As NotesDatabase
Dim v As NotesView
Dim doc As NotesDocument
' Instantiate objects
Set s = New NotesSession
Set db = s.CurrentDatabase
Set v = db.GetView ("White Papers")
Set doc = v.GetDocumentByKey ("Introduction to XML")
' Display document properties
Messagebox doc.IsNewNote
Messagebox doc.Created

Stud ent Gu ide Page No. 81 145


Preview
Le sso n 6 „ Acc essin g Data in Doc ume nts

Retrieving Item Values from a Document

Accessing item values

Before we can access item values, review with students that items (with the
exception of rich text) are stored as lists or arrays. That means there could be
multiple values. To read item values, we must first look at reading array elements.
Then we will examine the extended class syntax for accessing items and, finally,
the GetItemValue method.

146 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L es son 6 „ Acce ssing D ata in D ocu men t s

Retrieving Item Values from a Document

Each item (except rich text items) may contain multiple values. For this reason, all
items store their values as arrays, even if there is only one value.

Accessing item values

The following diagram shows the structure of items and how the items are
accessed.

Stud ent Gu ide Page No. 82 147


Preview
Le sso n 6 „ Acc essin g Data in Doc ume nts

Retrieving Item Values from a Document...(continued)

Reading array elements

Make sure that students understand that even if the item is not a multi-value field,
Domino still stores the value as an array. Therefore, always refer to the value in a
single-value item as fieldname(0).
Make sure that students understand that when reading an item, you do not need
to build arrays.

Explain the Get Item in Document code

„ Use the Document Retrieval form.


„ Explain the code behind the Get Item in Document button
„ Show the results by selecting the button in the Notes Client.
„ Leave the form open in Designer.
Optional: Show that if you do not address the first element of the array (remove
the (0) from MovieTitle), a Type Mismatch error results.
„ Use the debugger to identify why the Type mismatch error message appears
when you preview the form.
„ Expand DOC in the Variables tab
„ Expand ITEMS
„ Expand the Movie Title field, ([1])
„ The error occurred because the item was not treated as part of an array.

148 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L es son 6 „ Acce ssing D ata in D ocu men t s

Retrieving Item Values from a Document...(continued)

Reading array elements

Access array elements using an index. The first element of an array has an index
of 0.
Example
The following code displays the 1st, 5th and 37th elements in the Students array.
Dim myList As Variant
' code to retrieve document object
myList = doc.GetItemValue ("Students")
' display first (1st) element of array
Messagebox myList(0)
' display fifth (5th) element of array
Messagebox myList(4)
' display thirty-seventh (37th) element of array
Messagebox myList(36)

Using the extended class syntax to read item values

The extended class syntax provides a shorthand method for reading the values of
an item. The following code sample displays the value of the LastName item.
Dim lname As Variant
' read value of LastName item and copy into variable
lname = doc.LastName
' display last name
Messagebox lname(0)

Stud ent Gu ide Page No. 83 149


Preview
Le sso n 6 „ Acc essin g Data in Doc ume nts

Retrieving Item Values from a Document...(continued)

The GetItemValue method

Explain that GetItemValue and the extended class syntax provide the same
functionality, but the extended class syntax is easier to deal with. Later in the
course, students will learn that it can be used to set item values as well.

Modify the Get Item in Document button

„ Use the Document Retrieval form.


„ Modify the code in the Get Item in Document button to use the GetItemValue
method to display another item from the document.
„ For example, replace Messagebox doc.MovieTitle(0) with the following
code
Dim mtitle As Variant
mtitle=doc.GetItemValue("MovieTitle")
Messagebox mtitle(0)

Note: When demonstrating this method, show that to access the value, you can
index the variant as an array. For example, the following code will display the
value of the LastName field:
Messagebox lname(0)

150 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L es son 6 „ Acce ssing D ata in D ocu men t s

Retrieving Item Values from a Document...(continued)

Using the GetItemValue method

The GetItemValue method of the NotesDocument class returns the value of a


specified item from a document.
For items that are text, number, and time-date values, GetItemValue always
returns an array of that type. Even if there is only one value in the item, the
method returns an array. The first value in the array is the value of the item.
Syntax
valueArray = notesdocument.GetItemValue (itemName$)
Example
The following code retrieves the value of the LastName item.
Dim lname As Variant
lname = doc.GetItemValue ("LastName")

Stud ent Gu ide Page No. 84 151


Preview
Le sso n 6 „ Acc essin g Data in Doc ume nts

Looping Through Documents in a View

The GetFirstDocument and the GetNextDocument methods

Introduce the methods we will focus on in this section.


„ The GetFirstDocument method gives you a starting point in the view.
„ The GetNextDocument method continues the loop.

Introduce LotusScript loop constructs

Introduce the Do While and Do Until loops. The loops are basically the same. The
difference is how you write the loop condition.

152 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L es son 6 „ Acce ssing D ata in D ocu men t s

Looping Through Documents in a View

Using methods of the NotesView class, you can search each document in a view
one by one. This is effective if the information you need to access in the document
does not appear in a view. If the data appears in a view, it is more efficient to use
the NotesViewEntry class to access the data.

Methods to step through documents in a view

The NotesView class provides the following methods for stepping through the
documents represented in the view:
„ GetFirstDocument
„ GetNextDocument

LotusScript loop constructs

LotusScript provides several loop structures for executing a block of statements


based on a condition. When scanning a view for particular documents, use one of
the following loops:
„ Do While
„ Do Until

Stud ent Gu ide Page No. 85 153


Preview
Le sso n 6 „ Acc essin g Data in Doc ume nts

Looping Through Documents in a View...(continued)

Introduce Do While loops

Present the syntax and example from the Student Guide.

Introduce Do Until loops

Present the syntax and example from the Student Guide.


To help students understand how to build a loop, give them a problem to define
the While loop and the Until loop.
„ If you want to loop a set number of times, for example 10 times, answer
While n<11 Until n=10.
Explain that the condition for the loop can also be placed at the bottom of the loop.
Describe how this alters the functionality of the loop.

154 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L es son 6 „ Acce ssing D ata in D ocu men t s

Looping Through Documents in a View...(continued)

Using Do While loops

The Do…While construct allows you to execute a block of statements for as long
as a condition is true.
Syntax
Do While <condition>
[statements]
Loop

Example
The following code moves through a list of documents and stops at the first
document without data.
Set doc = v.GetFirstDocument
Do While Not (doc Is Nothing)
count = count + 1
Set doc = v.GetNextDocument (doc)
Loop

Using Do Until loops

The Do Until loop is another construct that executes a block of statements. This
loop iterates as long as the condition is false, or until the condition is true.
Syntax
Do Until <condition>
[statements]
Loop

(continued on next page...)

Stud ent Gu ide Page No. 86 155


Preview
Le sso n 6 „ Acc essin g Data in Doc ume nts

Looping Through Documents in a View...(continued)

156 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L es son 6 „ Acce ssing D ata in D ocu men t s

Looping through Documents in a View...(continued)

Using Do Until loops...

Example
The following code displays the value of the Subject item from each document in
the Examples view.
Dim s As NotesSession
Dim db As NotesDatabase
Dim v As NotesView
Dim doc As NotesDocument
Set s = New NotesSession
Set db = s.CurrentDatabase
Set v = db.GetView ("Examples")
Set doc = v.GetFirstDocument
Messagebox doc.Subject(0)
Do Until doc Is Nothing
Set doc = v.GetNextDocument(doc)
Messagebox doc.Subject(0)
Loop

Stud ent Gu ide Page No. 87 157


Preview
Le sso n 6 „ Acc essin g Data in Doc ume nts

Looping Through Documents in a View...(continued)

Count the documents in a view

In this guided practice, students will create a button on the Document Retrieval
form. When clicked the button will count all the movies stored in the database and
display the value in a messagebox.

158 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L es son 6 „ Acce ssing D ata in D ocu men t s

Looping Through Documents in a View...(continued)

Count the documents in a view

In this guided practice, you will count the number of documents in a view that
contain an item that matches a certain value. You will use a loop construct,
NotesView methods, and extended class syntax to read item values from the
documents in a view.
Follow these steps to complete this guided practice.

Step Action

1 In the Demos and Activities database, open the Document Retrieval


form.

2 Create a button named Count Movies and add the following code button to
access the current database:
'We are accessing a document in the same
'database the script lies.
'Therefore, get the session, and
'the current database.
Dim s As NotesSession
Set s = New NotesSession
Dim db As NotesDatabase
Set db = s.CurrentDatabase

3 Add the following code to access the Get Document By Key View (alias
GDBK):
'locate the GDBK view to get the document
Dim v As NotesView
Set v = db.GetView("GDBK")

(continued on next page...)

Stud ent Gu ide Page No. 88 159


Preview
Le sso n 6 „ Acc essin g Data in Doc ume nts

Looping Through Documents in a View...(continued)

160 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L es son 6 „ Acce ssing D ata in D ocu men t s

Looping Through Documents in a View...(continued)

Count the documents in a view

Step Action

4 Add the following code to count each document in the view:


'Count the Documents by scrolling through
'using a do while and a count
Dim count As Integer
Dim doc As NotesDocument
'get the first document
Set doc = v.GetFirstDocument
'increment counter by one as the loop iterates
'successfully
Do Until doc Is Nothing
count = count + 1
Set doc = v.GetNextDocument(doc)
Loop

5 Add the following code to display the final count:


'display the final count
Messagebox "The number of movies is: " & count

6 Choose FileÆSave to compile the code and save the form.

7 Preview the form in Notes and click Count Movies.

Stud ent Gu ide Page No. 89 161


Preview
Le sso n 6 „ Acc essin g Data in Doc ume nts

Accessing Data Directly from the View

This section offers a more efficient way to access application data if it is displayed
in a view. You can pull the data directly from the view rather than accessing the
document first. If the data you need does not reside in a view, you may consider
building a new view to contain it (if that is practical), or you must access the
document as discussed previously in this lesson.

Introduce the NotesViewEntry class

Ask students what class contains the NotesViewEntry class. Then, ask them what
NotesView method gives them access to the NotesViewEntry.

Describe the GetNotesViewEntry method

Describe the GetNotesViewEntry method and explain the example.

162 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L es son 6 „ Acce ssing D ata in D ocu men t s

Accessing Data Directly from the View

If data appears directly in a view it is more efficient to use this data than to open a
document to access the item value.

NotesViewEntry class

The NotesViewEntry class represents a single row in a view. This class contains
properties that represent the column values displayed in the entry and the
document represented by the entry. It also contains properties indicating if the
entry is a document, category, or total.

Accessing a view entry

Use the GetEntryByKey method of the NotesView class to access a view entry.
Given a key (or array of keys), this method returns the first view entry found that
matches the keys.
Example
The following code retrieves the view entry whose first sorted column displays the
value Dogs.
Dim s As NotesSession
Dim db As NotesDatabase
Dim v As NotesView
Dim ventry As NotesViewEntry
Set s = New NotesSession
Set db = s.CurrentDatabase
Set v = db.GetView("By Category")
' Access the view entry
Set ventry = v.GetEntryByKey("Dogs")

Stud ent Gu ide Page No. 90 163


Preview
Le sso n 6 „ Acc essin g Data in Doc ume nts

Accessing Data Directly from the View...(continued)

Introduce the ColumnValues property

Explain that the ColumnValues property allows you to retrieve data from a view
column or columns.

Using the ChildCount property

Make sure students realize that child documents are considered part of the
returned view entry.

Counting the number of children documents

„ Use the Document Retrieval form


„ The Count Movies in a Category button retrieves the number of children for
one of the categories in the Movies view and displays the result in a message
box.
„ Identify the view entries in the view. This view organizes the movies by genre
(such as Drama, Black Comedy, and so on.)
„ Preview the form using the debugger to see what the Variables tab returns.
„ Confirm that the result in the message box is correct by opening and
displaying the view in the client.

164 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L es son 6 „ Acce ssing D ata in D ocu men t s

Accessing Data Directly from the View...(continued)…(continued)

Using the ColumnValues property

The ColumnValues property of the NotesViewEntry class contains the column


values of a view entry.
Example
The following code would display the first three column values in the Cars view
entry in the By Category view.
' Declare object variables
Dim s As NotesSession
Dim db As NotesDatabase
Dim v As NotesView
Dim ventry As NotesViewEntry

' Instantiate objects


Set s = New NotesSession
Set db = s.CurrentDatabase
Set v = db.GetView("By Category")
Set ventry = v.GetEntryByKey("Cars")

' Display first three column values


Messagebox ventry.ColumnValues(0)
Messagebox ventry.ColumnValues(1)
Messagebox ventry.ColumnValues(2)

Using the ChildCount property

The ChildCount property is an integer that identifies the number of immediate


children belonging to the current view entry.
Example
The following code displays the number of response documents for the Dogs view
entry in the By Category view.
Dim s As NotesSession
Dim db As NotesDatabase
Dim v As NotesView
Dim ventry As NotesViewEntry
Set s = New NotesSession
Set db = s.CurrentDatabase
Set v = db.GetView("By Category")
Set ventry = v.GetEntryByKey("Dogs")
Messagebox ventry.ChildCount

Stud ent Gu ide Page No. 91 165


Preview
Le sso n 6 „ Acc essin g Data in Doc ume nts

Accessing Data Directly from the View...(continued)

Count movies in a different media

In this guided practice, students create a button to count the number of movies
listed under a particular media type. This information is gathered from the View
Entry View (VEV).
This code will use the NotesViewEntry class to count the responses of a particular
media type.

166 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L es son 6 „ Acce ssing D ata in D ocu men t s

Accessing Data Directly from the View...(continued)

Count movies in a different media

In this guided practice, write a script that


„ Displays the number of movies listed under a particular media type in the View
Entry View (VEV) of the Demos and Activities database.
„ Instead of manually scanning each document for item values matching the
media, this code uses the NotesViewEntry class to count the responses of a
particular media type.
Follow these steps to complete this guided practice.

Step Action

1 In the Demos and Activities database, open the View Entry form.

2 Add the following code to the Count Movies in Media button:


'get back-end objects to collect the information
Dim s As notessession
Set s = New NotesSession
Dim db As NotesDatabase
Set db = s.CurrentDatabase
Dim v As NotesView
Set v = db.GetView("VEV")

3 Continue adding the following code to read the media type from the current
document.
'get objects to get information from current document
Dim w As NotesUIWorkspace
Set w=New NotesUIWorkspace
Dim uidoc As NotesUIDocument
Set uidoc=w.CurrentDocument
Dim doc As NotesDocument
Set doc=uidoc.Document
Dim ventrydef As String
ventrydef=doc.MRef(0)

(continued on next page...)

Stud ent Gu ide Page No. 92 167


Preview

7
Le sso n 7 „ Acc essin g Data in Doc ume nts

Accessing Data Directly from the View...(continued)

Count movies in a different media

168 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview

7
L es son 7 „ Acce ssing D ata in D ocu men t s

Accessing Data Directly from the View...(continued)

Count movies in a different media

Step Action

4 Continue adding the following code to access the view entry that matches the
media type and display the number of children.
'get view entry
Dim ventry As NotesViewEntry
Set ventry=v.GetEntryByKey(ventrydef)
'display result
Messagebox "The total number of movies in " & __
ventrydef & " is: " &ventry.siblingcount

5 Choose FileÆSave to compile the script and save the form.

6 Preview the form in Notes.

7 Select a media type, and click Count Movies in Media.

Stud ent Gu ide Page No. 93 169


Preview
Le sso n 7 „ Wri t i ng D a t a to D oc um e nt s

7
Writing Data to Documents

Present the lesson objectives.

170 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Les so n 7 „ Wri t i ng D a t a t o D oc u m e n t s

7
Writing Data to Documents

This lesson focuses on adding data to existing documents and creating new
documents. It begins with adding and replacing item values in a document using
the extended class syntax as well as the AppendItemValue and ReplaceItemValue
methods. The lesson covers saving a document and synchronizing any changes
with the user interface. This lesson also presents a procedure for creating a new
document with LotusScript, in which items for the application and for Domino
(such as authors, readers, and forms) are added.

Objectives

After completing this lesson, you should be able to:


9 Update items in a document.
9 Create new items in a document.
9 Set item properties to indicate Authors and Readers of a document.
9 Create a new document.
9 Send a document.

Stud ent Gu ide Page No. 94 171


Preview
Le sso n 7 „ Wri t i ng D a t a to D oc um e nt s

Adding and Replacing Items

Add new items or setting existing item values

Explain the extended class syntax for creating new items or setting existing item
values.

172 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Les so n 7 „ Wri t i ng D a t a t o D oc u m e n t s

Adding and Replacing Items

Use LotusScript to add a new item to a document. Whenever the document is


modified it must be saved for the changes to take effect.

Using the extended class syntax to add new items

The extended class syntax provides a shorthand method for adding new item
values. The following LotusScript statements add new items to documents and set
their values, if the item name does not already exist on the document.
' add Region item and set value to Asia Pacific
doc.Region = "Asia Pacific"
' add Author item and set value to the current user
doc.Author = s.UserName

If the item already exists in the document, the above statements will
overwrite the original value of those items.

Caution

Tip: Effects of adding a new item


„ The new item will not be displayed unless you add a corresponding field to the form
used to display the document. However, the new item appears in the Document
Properties box.

Stud ent Gu ide Page No. 95 173


Preview
Le sso n 7 „ Wri t i ng D a t a to D oc um e nt s

Adding and Replacing Items...(continued)

The AppendItemValue method

Explain the example from the Student Guide to make sure students know what
each line of the code is doing. Caution students to make sure that their code
appends values of the correct data type.

174 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Les so n 7 „ Wri t i ng D a t a t o D oc u m e n t s

Adding and Replacing Items...(continued)

Using the AppendItemValue method

The AppendItemValue method of the NotesDocument class adds a new item to a


document and sets its value. If an item of the same name already exists, a new
item of the same name is created with the value you specify. You must call the
Save method of the document to retain the new item.
Syntax
Call notesdocument.AppendItemValue (itemName$, value)
Example
The following code adds an item named Region and saves the document.
Dim s As NotesSession
Dim db As NotesDatabase
Dim v As NotesView
Dim doc As NotesDocument
Set s = New NotesSession
Set db = s.CurrentDatabase
Set v = db.GetView ("By Location")
Set doc = v.GetDocumentByKey ("Brazil")
Call doc.AppendItemValue ("Region", "Latin America")
Call doc.Save (False, True)

Tip: Effects of AppendItemValue


„ The AppendItemValue sets the IsSummary property of the new item to True. This
means that the new item can appear in a view.

Stud ent Gu ide Page No. 96 175


Preview
Le sso n 7 „ Wri t i ng D a t a to D oc um e nt s

Adding and Replacing Items...(continued)

The ReplaceItemValue method

Ask students to tell you what the example code from the Student Guide is doing.

The ReplaceItemValue

Discuss the results of using the ReplaceItemValue method to create a new item.

176 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Les so n 7 „ Wri t i ng D a t a t o D oc u m e n t s

Adding and Replacing Items...(continued)

Using the ReplaceItemValue method

The ReplaceItemValue method overwrites the value of an existing item with the
value specified. If the item name specified does not exist in the document, a new
item is added to the document.
Syntax
Call notesdocument.ReplaceItemValue (itemName$, value)
Example
The following code changes the value of the item named Region and saves the
document.
Dim s As NotesSession
Dim db As NotesDatabase
Dim v As NotesView
Dim doc As NotesDocument
Set s = New NotesSession
Set db = s.CurrentDatabase
Set v = db.GetView ("By Location")
Set doc = v.GetDocumentByKey ("Korea")
Call doc.ReplaceItemValue ("Region", "Asia Pacific")
Call doc.Save (False, True)

Results of ReplaceItemValue

Unlike AppendItemValue, the ReplaceItemValue method does not set the


IsSummary property of the item to True. If ReplaceItemValue creates a new item
(because the specified item does not exist in the document), the IsSummary
property is False, which means that the new item cannot appear in a view.
The ReplaceItemValue method does not change the IsSummary property of an
existing item.

Stud ent Gu ide Page No. 97 177


Preview
Le sso n 7 „ Wri t i ng D a t a to D oc um e nt s

Saving the Document

The Save method

Explain that changes do not appear in the database until the document is saved.

Save method parameters

Describe the effect of the different combinations of parameters in the save


method.
You may need to briefly review save conflicts and how they occur.

178 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Les so n 7 „ Wri t i ng D a t a t o D oc u m e n t s

Saving the Document

Once you make changes to a document in script, you must save the document for
those changes to take effect in the application.

Saving a document

The Save method of the NotesDocument class saves any changes made to the
document.
Syntax
flag = notesDocument.Save (force, createResponse)
Example
The following code saves the document even if another user edits and saves the
document while the script is running.
Call doc.Save (True, True)

Using the save method

When saving a document, you must consider that another user may have edited
the document while the script was running. The parameters of the save method
allow you to control how the document is saved in this case.
„ If the force parameter is True, the createResponse parameter has no effect.
„ If the force parameter is False and another user edits and saves the
document, the createResponse parameter determines how the document is
saved:
„ If createResponse is True, the current document becomes a response to
the original document.
„ If createResponse is False, the save is canceled.

„ If the document is saved successfully, the method returns a value of True. If


the document is not saved, the return value is False.

Stud ent Gu ide Page No. 98 179


Preview
Le sso n 7 „ Wri t i ng D a t a to D oc um e nt s

Synchronizing with the User Interface

Working with the back-end document

Describe reasons why it is sometimes necessary or easier to work with the back-
end document.

The Document property

Describe the Document property of NotesUIDocument and how to use it.

Updating the UI document

Describe situations when changes made to the back-end must be reflected in the
UI.

180 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Les so n 7 „ Wri t i ng D a t a t o D oc u m e n t s

Synchronizing with the User Interface

When document stored in the database (NotesDocument) are accessed through


the document in the user interface (NotesUIDocument), the two versions of the
document must be synchronized. In some cases, the synchronization happens
automatically. In others, code forces the synchronization.

Why change the back-end document from the front-end


document?

Scripts that execute in the current document may have to access the version of
the document stored in the database.
„ Work with numeric and time variables. (You can only use text to update a
document in the UI.)
„ Changing item values in the document is faster than changing fields and
saving the document from the front end.

Accessing NotesDocument from NotesUIDocument

Use the Document property of the NotesUIDocument class to access the


corresponding document, since it is stored in the database.
Syntax
Set NotesDocument = NotesUIDocument.Document
Example
'instantiate uidoc
'…
'instantiate doc
Dim doc As NotesDocument
Set doc = uidoc.Document

Updating the UI document

Update the current UI document when a script does both of the following:
„ Executes from the UI document (by means of a form action, button, or event).
„ Changes values in the document (NotesDocument).

Stud ent Gu ide Page No. 99 181


Preview
Le sso n 7 „ Wri t i ng D a t a to D oc um e nt s

Synchronizing with the User Interface...(continued)

Automatic synchronization

Describe when synchronization is automatically handled by Domino.


Ask students when they would not want automatic synchronization.

Forcing synchronization

Describe when synchronization should be handled manually.

Using the Reload method of NotesUIDocument

Explain the Reload method.


Explain the code example from the Student Guide.

182 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Les so n 7 „ Wri t i ng D a t a t o D oc u m e n t s

Synchronizing with the User Interface...(continued)

Automatic synchronization

The UI document is updated automatically when a script changes non-rich text


items in NotesDocument because:
„ AutoReload property of NotesUIDocument is enabled.
„ NotesDocument was accessed through the Document property of
NotesUIDocument. (In this case, the setting of AutoReload does not matter.)

Forcing synchronization

You must call the Reload method of the NotesUIDocument when a script changes
items in NotesDocument that were not accessed through the Document property
of NotesUIDocument, and the AutoReload property is disabled.

Using the Reload method of NotesUIDocument

The Reload method of the NotesUIDocument class updates the current document
with any changes made to the corresponding document stored in the database.
Example

Dim ws As NotesUIWorkspace
Dim uidoc As NotesUIDocument
Set ws = New NotesUIWorkspace
Set uidoc = ws.CurrentDocument
uidoc.EditMode = True
Set doc = uidoc.Document
doc.Subject = "New Subject"
doc.Save (False, True)
uidoc.Reload

Stud ent Gu ide Page No. 100 183


Preview
Le sso n 7 „ Wri t i ng D a t a to D oc um e nt s

Synchronizing with the User Interface...(continued)

Disabling AutoReload

Explain why and how to disable AutoReload.

184 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Les so n 7 „ Wri t i ng D a t a t o D oc u m e n t s

Synchronizing with the User Interface...(continued)

Disabling AutoReload to increase performance

When a script uses both the NotesDocument class and the NotesUIDocument
class, the interactions between the user interface and the database can slow
down the script’s execution. When AutoReload is enabled in the
NotesUIDocument, every time a script changes an item in the document (using
the NotesDocument class), the values are automatically loaded into the user
interface.
If a script makes many changes to the document, you may improve the
performance of the script by doing the following:
„ Disable the AutoReload property of the NotesUIDocument before making the
changes to the NotesDocument with the following code statement:
uidoc.AutoReload = False
„ At the end of the script, enable the property again with the following statement:
uidoc.AutoReload = True

Stud ent Gu ide Page No. 101 185


Preview
Le sso n 7 „ Wri t i ng D a t a to D oc um e nt s

Synchronizing with the User Interface...(continued)

Update an item value in a movie document

In this guided practice, you will update an item in a movie document that indicates
the number of movies in the same category as the current movie. The code
determines the value by counting the responses of the view entry for the current
category. It then updates the item in the document and refreshes the user
interface.

186 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Les so n 7 „ Wri t i ng D a t a t o D oc u m e n t s

Synchronizing with the User Interface...(continued)

Update an item value in a movie document

In this guided practice, you will update an item in a movie document that indicates
the number of movies in the same category as the current movie. The code
determines the value by counting the responses of the view entry for the current
category. It then updates the item in the document and refreshes the user
interface.
Follow these steps to complete this guided practice.

Step Action

1 Open the Movie form in your database and create a button named Update
Number in Same Category.

2 Add the following code to initialize the session, database, and view
containing the documents to count:
'Declare variables
Dim s As NotesSession
Set s = New NotesSession
Dim db As NotesDatabase
Set db = s.CurrentDatabase
'get the M view to count documents
Dim v As NotesView
Set v = db.GetView ("M")

3 Add the following code to edit the UI document:


'get the UI document
Dim w As NotesUIWorkspace
Set w = New NotesUIWorkspace
Dim uidoc As NotesUIDocument
Set uidoc = w.CurrentDocument
'turn off autoreload, go into editmode
uidoc.EditMode = True
uidoc.AutoReload = False

(continued on next page...)

Stud ent Gu ide Page No. 102 187


Preview
Le sso n 7 „ Wri t i ng D a t a to D oc um e nt s

Synchronizing with the User Interface...(continued)

188 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Les so n 7 „ Wri t i ng D a t a t o D oc u m e n t s

Synchronizing with the User Interface...(continued)

Update an item value in a movie document

Step Action

4 Add the following code to access the corresponding back-end document:


'get back-end document of the current document
Dim doc As NotesDocument
Set doc = uidoc.Document

5 Add the following code to get the number of view entries for the current movie
category:
'get the viewentry for the current category
Dim viewkey As String
Dim ventry As NotesViewEntry
Viewkey = doc.MovieCategory(0)
Set ventry = v.GetEntryByKey (viewkey)
'get the number of children
Dim count As Integer
Count = ventry.SiblingCount

6 Add the following code to update both the back-end and user interface
versions of the document:
'update back-end document
doc.NumCategory = count
'save document
Call doc.Save (True,True)
'update the front end with the back end and save
uidoc.Reload
uidoc.Save
'turn autoreload back on
uidoc.AutoReload = True

7 Save the form and compile the code.

8 In the Notes client, open a movie document from the Movies view and click
Update Number in Same Category.
Result: The field value appears in the Number in this Category field.

Stud ent Gu ide Page No. 103 189


Preview
Le sso n 7 „ Wri t i ng D a t a to D oc um e nt s

Adding Author and Reader Items

The NotesItem class

Emphasize that there are few reasons to use the NotesItem class except for
setting special properties. This is why the first mention of AppendItemValue does
not show using NotesItem with it until this section.
Review retrieving and adding item values to lead to creating a new item with the
NotesItem New method.

Creating a new Authors item

Explain how to create an item that is an Authors type.


Discuss the example from the Student Guide.

Creating a new Readers item

Explain how to create an item that is a Readers type.


Discuss the example from the Student Guide.

190 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Les so n 7 „ Wri t i ng D a t a t o D oc u m e n t s

Adding Author and Reader Items

Some item properties tell Domino to pay special attention to the value of the item.
For example, properties that identify particular items list the allowable readers and
authors of a document. Also, the IsSummary property identifies items that Domino
can display in views.

Creating a new item

Create a new item on a particular document using the New object constructor of
the NotesItem class.
Syntax
Set notesItem = New NotesItem (doc, itemName$, value, Type%)
Example
Set nitem = New NotesItem (doc, "Subject", " ")

Creating a new Authors Item

The New object constructor of NotesItem accepts an optional parameter that


allows you to identify immediately that the item is an Authors type, and will store
the names of users allowed to edit the document.
Example
Set nitem = New NotesItem (doc, "Authors", " ", AUTHORS)

Creating a new Readers Item

The New object constructor of NotesItem accepts another optional parameter that
allows you to identify immediately that the item is a Readers type, and will store
the names of users allowed to access the document.
Example
Set notesItem = New NotesItem (doc, "Readers", " ", READERS)

Stud ent Gu ide Page No. 104 191


Preview
Le sso n 7 „ Wri t i ng D a t a to D oc um e nt s

Adding Author and Reader Items...(continued)

Using the Values property

Once you have an item, you can set the Value property.

192 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Les so n 7 „ Wri t i ng D a t a t o D oc u m e n t s

Adding Author and Reader Items...(continued)

Setting the value of a new item

Once you have instantiated an object from the NotesItem class, you can use the
Values property to populate the new item with data.
Example
The following code concatenates the first and last name into one, creates a new
Authors item called FullName, and populates it with the concatenation of the
FirstName and LastName items from the same document.
Set notesItem = New NotesItem (doc, "FullName", " ",AUTHORS)
notesItem.Values = doc.FirstName(0) & " " & doc.LastName(0)

Stud ent Gu ide Page No. 105 193


Preview
Le sso n 7 „ Wri t i ng D a t a to D oc um e nt s

Creating New Documents

Create a new document

Use the procedure listed on the Student Guide to explain the process of creating a
new document. When creating a document programmatically, you must add items
that Domino automatically adds when a document is saved using a form.

The CreateDocument method

Describe the CreateDocument method.


Discuss the syntax and explain the code from the Student Guide.

194 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Les so n 7 „ Wri t i ng D a t a t o D oc u m e n t s

Creating New Documents

You can use LotusScript to create a new document. The new document does not
contain any items; therefore, you must add all items programmatically.

Creating a new document

Follow these steps to write a LotusScript program to create a new document.

Step Action

1 Create a new document object.

2 Add items required by the application.

3 Add items required by Domino.

4 Save or send the document.

5 If the code is run from an opened view, update that current UI view object.

Creating a new document object

Use the CreateDocument method of the NotesDatabase class to create a new


document in that database. The new document does not exist in the database
until it is saved.
Syntax
Set notesDocument = notesDatabase.CreateDocument
Example
The following code creates and saves a new document in the current database.
Dim s As NotesSession
Dim db As NotesDatabase
Dim doc As NotesDocument
Set s = New NotesSession
Set db = s.CurrentDatabase
Set doc = db.CreateDocument
Call doc.save (True, True)

Stud ent Gu ide Page No. 106 195


Preview
Le sso n 7 „ Wri t i ng D a t a to D oc um e nt s

Creating New Documents...(continued)

Using the Send method

In addition to creating a document that is saved in the database, you can send it to
other people or applications.
Introduce the send method and how to use it.

196 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Les so n 7 „ Wri t i ng D a t a t o D oc u m e n t s

Creating New Documents...(continued)

Sending a document

Use the Send method of the NotesDocument class to route or mail a document to
another user or application. When calling the send method, specify the names of
the recipients in one of the following two ways:
„ Pass the list of recipients into the method.
„ Store the list of recipients in an item named SendTo (in the same document).
Example
The following code sends a document to Doctor Notes in two different ways.
Set doc1 = v.GetFirstDocument
' pass recipients into send method
Call doc1.Send (True, "Doctor Notes")
Set doc2 = v.GetNextDocument(doc1)
doc2.SendTo = "Doctor Notes"
' rely on SendTo item for recipients
Call doc2.Send (False)

Stud ent Gu ide Page No. 107 197


Preview
Le sso n 7 „ Wri t i ng D a t a to D oc um e nt s

Creating New Documents...(continued)

Create a new movie document

Timing: Give students 10 minutes to complete the guided practice.


Present the guided practice by:
Identifying which database and form students will use.
Asking if students have any questions before starting the guided practice.

198 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Les so n 7 „ Wri t i ng D a t a t o D oc u m e n t s

Creating New Documents...(continued)

Create a new movie document

In this guided practice, write code to create a new movie document. The script will
create all the items, supply the values of those items, and save the document.
Follow these steps to create the new document.

Step Action

1 In the Demos and Activities database open the Create Document form.

2 Add the following code to the Create a new movie button to create a new
document object:
'We are accessing a document in the same database the
'script lies.
'Therefore, get the session and the current database.
Dim s As NotesSession
Set s = New NotesSession
Dim db As NotesDatabase
Set db = s.CurrentDatabase
'Create a document in the db
Dim doc As NotesDocument
Set doc = db.CreateDocument

3 Continue adding the following code to create items for the application:
'Fill in application items
doc.MovieTitle = "add your own movie here"
doc.MovieCategory = "choose from one of the categories here"
doc.MovieDescription = "describe the movie here"

4 Continue adding the following code to set the items Domino needs:
'Set the form item
doc.Form = "M"
'assign authors:
' use username from session and notesitem
Dim nitem As NotesItem
Set nitem = New NotesItem(doc,"Authors", " ", AUTHORS)
Call doc.ReplaceItemValue ("Authors",s.username)

5 Continue adding the following code to save the document:


'save document
Call doc.save(True,True)

6 Choose FileÆSave to compile the code and save the form.

7 Preview the form and click Create a new movie. Check the view for the new
document. Select the new document and open the Document Properties box.
Examine the document contents.

Stud ent Gu ide Page No. 108 199


Preview

8
Le sso n 8 „ Wri t i ng D a t a to D oc um e nt s

Creating a Report Document Exercise

Present the exercise by:


„ Identifying which database and design element the students will use.
„ Demonstrating the completed exercise using the Create a Report for Ceramics
action in the Course Summary view of the Inventory-Instructor database.
„ Asking if students have any questions before starting the exercise.
„ Explain the Challenge part of the exercise.
„ Open Domino 5 Designer Help and display the description of the
CaretCategory property of NotesUIView.
„ A solution exists in the Create a Report for Any Course action in the Course
Summary view of the Inventory-Instructor database.

200 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview

8
Les so n 8 „ Wri t i ng D a t a t o D oc u m e n t s

Creating a Report Document Exercise

In this exercise, you will use the Inventory database. In the Course Summary
view, create an action that generates a report identifying the number of students
currently registered for a course.
Each student registered for a course is listed in the Course Summary view as a
child of the course name. Use this information to determine the total number of
students in the course.

Create a report for the Ceramics course

Perform the following tasks to complete this exercise:


„ Determine the number of students currently registered for the Ceramics
course.
Hint: Use the NotesViewEntry class.
„ Create a new document that can be displayed through the Report form.
„ Add the following data to the new document so that it is displayed in the
appropriate fields on the Report form:
„ Name of course for report
„ Number of students registered for the course
„ Your user name as an author of the document

„ Update the view to display the new report document.

Challenge

Modify your solution to this exercise so that the action generates the report for the
course of whichever document is currently selected in the view.
Hint: Use the CaretCategory property of the NotesUIView class to read the
category of the currently selected document.

Stud ent Gu ide Page No. 109 201


Preview
Le sso n 8 „ Using ViewEntr y a nd D ocu men t C olle ction s

8
Using ViewEntry and
Document Collections

Present the lesson objectives.

202 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L esso n 8 „ Us in g Vie wEn try an d Doc ume nt Collection s

8
Using ViewEntry and
Document Collections

LotusScript provides several classes for accessing data from multiple documents.
Lesson 6: Accessing Data in Documents introduced arrays and how to read data
from individual elements. This lesson begins with more information on building
arrays and iterating through their elements. The lesson then introduces three new
classes that, like arrays, contain several elements. But instead of a group of
integers or strings, these classes contain groups of objects like view entries and
documents. Building on the concept of arrays, you can group related objects
together and iterate through them to examine specific data.

Objectives

After completing this lesson, you should be able to:


9 Build an array.
9 Iterate through an array with For and ForAll loops.
9 Create a NotesViewEntryCollection.
9 Navigate a NotesViewEntryCollection.
9 Use the NotesViewNavigator class to access categories of a view.
9 Retrieve a collection of documents.
9 Create a NotesDocumentCollection.
9 Navigate a NotesDocumentCollection.

Stud ent Gu ide Page No. 110 203


Preview
Le sso n 8 „ Using ViewEntr y a nd D ocu men t C olle ction s

Building Arrays

Building a static array

Describe the difference between static arrays and dynamic arrays.

Using the For loop

Introduce the For loop and explain the example code from the Student GUide.

204 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L esso n 8 „ Us in g Vie wEn try an d Doc ume nt Collection s

Building Arrays

Arrays are useful programming elements when you have to hold multiple values or
lists. Arrays can be static or dynamic. A static array has a specific size that is
known at compile time. A dynamic array changes size at run time.

Building a static array

Declare a static array if you know the number of elements the array will contain.
Example
'declare fixed-length array
Dim firstnames(2) As String
'populate array elements
firstnames(0) = "Molly"
firstnames(1) = "Frank"
firstnames(2) = "Sean"

Using the For loop

A For loop is a programming construct that executes a block of statements a


specific number of times. It is useful when you need to perform the same action on
each element of an array.
Example
The following code displays the names from the static array example.
'display firstnames array (from example above)
Dim arraycount as Integer
For arraycount = 0 to 2
Messagebox firstnames(arraycount)
Next

Stud ent Gu ide Page No. 111 205


Preview
Le sso n 8 „ Using ViewEntr y a nd D ocu men t C olle ction s

Building Arrays...(continued)

Introduce the ForAll loop

Explain the example code from the Student Guide. Students will use this construct
later in this lesson.

Display a static array

„ Open the Building Arrays form in the Demos and Activities-Instructor


database.
„ Use the code behind the Build a Static Array to illustrate how to create a static
array.

206 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L esso n 8 „ Us in g Vie wEn try an d Doc ume nt Collection s

Building Arrays...(continued)

Using the ForAll loop

The ForAll loop is useful for iterating through arrays. One advantage this construct
has is that you do not need to know the number of elements in the array.
Syntax
Use the following syntax for the ForAll loop.
ForAll refVar In arrayName
statements
End ForAll

The reference variable refVar refers to each element in the array as the loop
iterates through the statements. The name refVar is declared by its appearance
in the ForAll statement. It is an alias for each individual element of the array. Its
data type is the data type of the element in the array for that iteration.
Example
The following code uses the ForAll statement to iterate through an array.
'display firstnames array
ForAll fnames In firstnames
Messagebox fnames
Next

Stud ent Gu ide Page No. 112 207


Preview
Le sso n 8 „ Using ViewEntr y a nd D ocu men t C olle ction s

Building Dynamic Arrays

Dynamic arrays

Describe why you would want to use a dynamic array.


Explain the syntax for declaring a dynamic array from the Student Guide.

Using the ReDim statement

Describe the purpose of the ReDim statement.


Have students open Domino Designer Help and look up ReDim.
Be sure students understand how and when to use the Preserve option of ReDim.

Building an array

Use the code behind the ReDim Example button on the Building Arrays-demo
form to illustrate how to create a dynamic array.

208 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L esso n 8 „ Us in g Vie wEn try an d Doc ume nt Collection s

Building Dynamic Arrays

Dynamic arrays are useful when the required size of the array is unknown. Initially,
you can declare the array without any size, and later in the program grow the size
to whatever is required.

Declaring a dynamic array

Declare a dynamic array if you do not know the number of elements the array will
contain. Initially, a dynamic array has no dimensions or elements, and no storage
is allocated for it.
Example
The following code declares a dynamic array.
'declare a dynamic array
Dim fnames() As String

Using the ReDim statement

A dynamic array is unusable until you specify its dimensions in a ReDim


statement. The ReDim statement defines the array size, allocates storage for the
elements, and initializes them.
The optional Preserve keyword instructs LotusScript to retain the current values
of the elements in the array. This is useful if you want to expand the size of the
array to accommodate additional elements and values.
Example
The following code builds a dynamic array of names.
'Declare the array without specifying the size
Dim fnames() as String
'for demonstration, set the size of the array to 3
ReDim Preserve fnames(0) As String
'add the data to the re-dimensioned array
fnames (0) = "Molly"
ReDim Preserve fnames(1) As String
'add the data to the re-dimensioned array
fnames (1) = "Sean"

Stud ent Gu ide Page No. 113 209


Preview
Le sso n 8 „ Using ViewEntr y a nd D ocu men t C olle ction s

Building Dynamic Arrays...(continued)

Create a dynamic array

„ Students will add a button to the BuildingDynamicArrays form.


„ This button continues to prompt users for the name of their favorite movie until
they click Cancel.
„ Another messagebox appears asking how many times the user viewed each
of the movies they listed.
„ When completed, the table on the form displays all the movies the user typed
and how often they saw each movie.

210 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L esso n 8 „ Us in g Vie wEn try an d Doc ume nt Collection s

Building Dynamic Arrays...(continued)

Create a dynamic array

In this guided practice, create a button that does the following:


„ Asks users to enter their favorite movies, and stores the data in an array.
„ Asks the users if they saw the movie more than once, and stores the results in
another array.
„ Stops prompting for input when the user enters nothing for the movie.
„ Displays the array values in the two fields on the open document.
Follow these steps to complete the guided practice.

Step Action

1 In the Demos and Activities database, open the BuildingDynamicArrays


Activity form.

2 Create a button named Build a Dynamic Array.

3 Add the following variable declarations and instantiations for the arrays and
other variables needed in the code.
'declare dynamic arrays
Dim favmovies() As String
Dim survey() As String
'declare counters
Dim arraycount As Integer
Dim i As Integer
'declare strings to capture results from prompts
Dim movieresult As String
Dim surveyresult As Integer

(continued on next page...)

Stud ent Gu ide Page No. 114 211


Preview
Le sso n 8 „ Using ViewEntr y a nd D ocu men t C olle ction s

Building Dynamic Arrays...(continued)

212 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L esso n 8 „ Us in g Vie wEn try an d Doc ume nt Collection s

Building Dynamic Arrays...(continued)

Create a dynamic array...

Step Action

4 Add the following code to access the workspace and the current document (UI
and back-end).
'access the workspace and current document
Dim w As NotesUIWorkspace
Set w = New NotesUIWorkspace
Dim uidoc As NotesUIDocument
Set uidoc = w.CurrentDocument
Dim doc As NotesDocument
Set doc = uidoc.Document

5 Add the following code to display a prompt for the user to enter a favorite
movie and store it in an array. The loop will run until the user enters nothing for
the movie.
Do
movieresult = w.prompt (PROMPT_OKCANCELEDIT, _
"Movies","Enter a favorite movie and click OK. " & _
"Click Cancel to exit.")
If movieresult <> "" Then
Redim Preserve favmovies(arraycount) As String
favmovies(arraycount) = movieresult
arraycount = arraycount + 1
End If
Loop Until movieresult = ""

(continued on next page...)

Stud ent Gu ide Page No. 115 213


Preview
Le sso n 8 „ Using ViewEntr y a nd D ocu men t C olle ction s

Building Dynamic Arrays...(continued)

214 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L esso n 8 „ Us in g Vie wEn try an d Doc ume nt Collection s

Building Dynamic Arrays...(continued)

Create a dynamic array...

Step Action

6 Add the following code to survey the user and store the result in another array.
Redim survey(arraycount-1) As String
For i = 0 To arraycount-1
Surveyresult = w.prompt (PROMPT_YESNO, _
"Question", "Did you see " & favmovies(i) & _
" more than once?")
If surveyresult = 1 Then
Survey(i) = "Yes"
Else
Survey(i) = "No"
End If
Next

7 Add the following code to update the current document.


doc.FavoriteMovies = favmovies
doc.SeenMoreThanOnce = survey

8 Save the form and preview it in Notes.

9 In Notes, click Build a Dynamic Array. Enter a movie title, and click OK. Add
a few more movie titles and then click Cancel. The information you entered
should appear on the document.

Stud ent Gu ide Page No. 116 215


Preview
Le sso n 8 „ Using ViewEntr y a nd D ocu men t C olle ction s

Using the NotesViewEntryCollection


Class

Creating a NotesViewEntryCollection

A collection is a non-indexed grouping of the same objects. A collection is


navigable.
Use the following procedure for working with collections:
„ Get the collection.
„ Navigate the collection.
NotesViewEntryCollection is a grouping of view entries.
At the end of this lesson, we will discuss NotesDocumentCollections which
contain a group of documents.

The Count property

Explain the count property of the NotesViewEntryCollection class. Because view


entry collections do not include totals or categories, the count property is a good
way to find the number of documents in a category.

Retrieving entries from the collection

Open Domino Designer Help and display the complete syntax for the retrieval
methods. They work similarly to the methods of NotesView.
Ask students to help you build the code to retrieve entries.

216 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L esso n 8 „ Us in g Vie wEn try an d Doc ume nt Collection s

Using the NotesViewEntryCollection


Class

The NotesViewEntryCollection class represents a group of entries (or rows) in a


view. A NotesViewEntryCollection only includes entries that represent documents;
it does not include categories and totals.

Creating a NotesViewEntryCollection

Create a collection of view entries from an existing NotesView object with the
following:
„ The AllEntries property provides access to all entries in the view.
Dim veCol As NotesViewEntryCollection
Set veCol = v.AllEntries

„ The GetAllEntriesByKey method returns only those entries of a sorted view


that match the specified key(s).
Dim veCol As NotesViewEntryCollection
Set veCol = v.GetAllEntriesByKey ("Asia Pacific")

The Count property

The Count property holds the number of entries in the collection. For example, if
there were three documents in the Asia Pacific category of a view, the following
code would display 3.
' v is instantiated as a view object
Dim veCol as NotesViewEntryCollection
Set veCol = v.GetAllEntriesByKey ("Asia Pacific")
Messagebox veCol.Count

Retrieving entries from the collection

Use the following methods to access specific entries in the collection:


„ GetFirstEntry
„ GetNextEntry
„ GetLastEntry
„ GetNthEntry

Stud ent Gu ide Page No. 117 217


Preview
Le sso n 8 „ Using ViewEntr y a nd D ocu men t C olle ction s

Using the NotesViewEntryCollection Class...(continued)

Navigating a collection

Navigate through a collection identifying each entry and each entry's column
values.
„ On the ViewEntryCollection Demo form, click the Navigate a
ViewEntryCollection button.
„ This button creates a collection of all the entries in the Movies view, and
displays every column value for each entry in a Messagebox.

Count movies in the Comedy category

Students will modify the Count Comedies button code.

218 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L esso n 8 „ Us in g Vie wEn try an d Doc ume nt Collection s

Using the NotesViewEntryCollection Class...(continued)

Count movies in the Comedy category

In this guided practice you will modify code to count the number of movies in the
Comedy category of the Movie view in the Demos and Activities database.
„ The code uses a NotesViewEntryCollection object to hold all the movies of the
specified category.
„ Because the view displays report documents along with the movie documents,
scan the column values so that the reports are not included in the count.
„ If there are no reports, you can use the Count property of the
NotesViewEntryCollection.
„ In this case, subtract the number of reports from the total count to get the
actual number of movies.
Follow these steps to complete this guided practice.

Step Action

1 Open the All Genre Report form in Domino Designer.

2 Click Count Comedies. Examine the LotusScript code that is already there.

3 Add the following code after the statement 'Add code here…
' Get the Movies view
Set v = db.GetView("M")
' Get a NotesViewEntryCollection for comedy
Set veCol = v.GetAllEntriesByKey("Comedy")
' set count to number of entries in the collection
comedyCount = veCol.Count
Note: If there are no report documents in the view, this is the number of
movies in the comedy category.

(continued on next page...)

Stud ent Gu ide Page No. 118 219


Preview
Le sso n 8 „ Using ViewEntr y a nd D ocu men t C olle ction s

Using the NotesViewEntryCollection Class...(continued)

220 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L esso n 8 „ Us in g Vie wEn try an d Doc ume nt Collection s

Using the NotesViewEntryCollection Class...(continued)

Count movies in the Comedy category...

Step Action

4 Continue to add the following code to the button.


'check for reports and subtract them from the count
Set ventry = veCol.GetFirstEntry()
Do Until ventry Is Nothing
If (ventry.ColumnValues(3) Like "Report: *") Then
comedyCount = comedyCount - 1
End If
Set ventry = veCol.GetNextEntry (ventry)
Loop
Note: For more information on the comparison operator Like, refer to Help.

5 Continue to add the following code to the button.


'display result
Messagebox "There are " & comedyCount & " movies in the Comedy
category."

6 Compile the code and save the form.

7 Preview the form in Notes and click Count Comedies.


Observe the results of the code.

Stud ent Gu ide Page No. 119 221


Preview
Le sso n 8 „ Using ViewEntr y a nd D ocu men t C olle ction s

Using NotesViewNavigator

Introduce the NotesViewNavigator object. Describe the differences between this


class and the NotesView class.
Open Domino Designer Help and display the syntax and usage of the
NotesViewNavigator class.

The NotesViewNavigator object

Use Domino Designer Help and the information from the Student Guide to explain
how to create a NotesViewNavigator object.

Retrieving entries from a view

Describe the different methods to retrieve entries as listed in the Student Guide.

222 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L esso n 8 „ Us in g Vie wEn try an d Doc ume nt Collection s

Using NotesViewNavigator

The NotesViewNavigator class provides access to entries in a view. Using the


methods of this class, you can read view entries that represent categories, totals,
and documents. A view navigator remains associated with the parent view. A
refresh of the parent view affects the view navigator.

Creating a NotesViewNavigator object

Create a NotesViewNavigator object using one of the following methods of the


NotesView class:
„ CreateViewNav
„ CreateViewNavFrom
„ CreateViewNavFromCategory
„ CreateViewNavFromChildren
„ CreateViewNavFromDescendants
Note: For more information on these methods, refer to Help.

Accessing entries using NotesViewNavigator

The NotesViewNavigator class provides several methods for retrieving entries


from a view.
Typically, you will start by retrieving the first entry using the GetFirst method. You
can also start by retrieving an entry in a specific position in the view using GetNth.
Once you have an entry as a starting point, NotesViewNavigator allows you to get
the next entry of interest. You can specify the kind of entry you want using the
following methods:
„ GetNext to retrieve the next entry as it appears in the view.
„ GetNextCategory to retrieve the next entry representing a category.
„ GetNextDocument to retrieve the next entry representing a document.
„ GetNextSibling to retrieve the next entry representing a sibling to the current
entry.

Stud ent Gu ide Page No. 120 223


Preview
Le sso n 8 „ Using ViewEntr y a nd D ocu men t C olle ction s

Using NotesViewNavigator...(continued)

Count all movies in each genre

Students will modify the button they worked on earlier in the Count movies in the
Comedy category guided practice. The new button should count movies in each
genre.
(Optional) Run the solution code in the instructor version of the Demos and
Activities database so students are clear about what the code is doing.
Review the guided practice with the students to be sure they understand what
each piece of code does.

224 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L esso n 8 „ Us in g Vie wEn try an d Doc ume nt Collection s

Using NotesViewNavigator...(continued)

Count all movies in each genre

In this guided practice, extend the functionality of the Count Comedies button
from the last guided practice. The modified button should:
„ count the number of movies for each genre and display them in a form.
„ use NotesViewNavigator to build an array of movie genres from the Movies
view.
„ use a NotesViewEntryCollection to access the entries for each genre and
subtract any reports from the total count.
Follow these steps to modify a button to count the number of movies in each
genre.

Step Action

1 In the Demos and Activities database, open the All Genre Report form.

2 Click Count Movies in Each Genre. Examine the code that is already there.

3 Add the following code after the comment ‘ Add code here…
' get movies view
Set v = db.GetView("M")
' create a view navigator
Set vNav = v.CreateViewNav
' get first entry of navigator
Set ventry = vNav.GetFirst
' get all categories in the view navigator
Do Until ventry Is Nothing
Redim Preserve gArray(count)
gArray(count) = ventry.ColumnValues(0)
count = count + 1
Set ventry = vNav.GetNextCategory (ventry)
Loop

(continued on next page...)

Stud ent Gu ide Page No. 121 225


Preview
Le sso n 8 „ Using ViewEntr y a nd D ocu men t C olle ction s

Using NotesViewNavigator...(continued)

226 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L esso n 8 „ Us in g Vie wEn try an d Doc ume nt Collection s

Using NotesViewNavigator...(continued)

Count all movies in each genre

Step Action

4 Continue adding the following code:


' Use the size of the genre array to
' redimension the array to hold movie counts
Redim mArray(count - 1)
' reset count variable to use below
count = 0
' get number of movies for each genre
Forall genre In gArray
' Get a view entry collection for each genre
Set veCol = v.GetAllEntriesByKey(genre)
' set initial count to collection count
mArray(count) = veCol.Count
' subtract any reports from the count
Set ventry = veCol.GetFirstEntry()
Do Until ventry Is Nothing
If (ventry.ColumnValues(3) Like _
"Report: *") Then
mArray(count)=mArray(count)-1
End If
Set ventry = veCol.GetNextEntry(ventry)
Loop
count = count + 1
End Forall

(continued on next page...)

Stud ent Gu ide Page No. 122 227


Preview
Le sso n 8 „ Using ViewEntr y a nd D ocu men t C olle ction s

Using NotesViewNavigator...(continued)

228 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L esso n 8 „ Us in g Vie wEn try an d Doc ume nt Collection s

Using NotesViewNavigator...(continued)

Count all movies in each genre

Step Action

5 Continue to add the following code:


' Add results to the current document
Dim doc As NotesDocument
Dim w As NotesUIWorkspace
Set w = New NotesUIWorkspace
' Get the back-end doc through the uidoc
Set doc = w.CurrentDocument.Document
'Add results to items in the document
doc.Genre = gArray
doc.NumberOfMovies = mArray

6 Save and compile the code.

7 Preview the form in Notes and click Count Movies in Each Genre. Verify the
result by examining the Movies view.

Stud ent Gu ide Page No. 123 229


Preview
Le sso n 8 „ Using ViewEntr y a nd D ocu men t C olle ction s

Using the NotesDocumentCollection


Class

The NotesDocumentCollectionclass

Describe the NotesDocumentCollection class and give examples of how it can be


used.
Explain the different ways to create a collection of documents.
If students want to try using the Search syntax in the demo database, they can
create and test a button containing the following code:
Dim s As New NotesSession
Dim db As NotesDatabase
Dim clx As NotesDocumentCollection
Set db=s.CurrentDatabase
Set clx=db.Search({MovieCategory="Drama"}, Nothing, 0)

Retrieving documents from the collection

Describe the retrieval methods and refer to Domino Designer Help for complete
syntax and details.

230 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L esso n 8 „ Us in g Vie wEn try an d Doc ume nt Collection s

Using the NotesDocumentCollection


Class

The NotesDocumentCollection class represents a group of documents


(NotesDocument) in a database.

Creating a NotesDocumentCollection

Create a collection of documents from NotesDatabase with the following


characteristics:
„ The AllDocuments property provides access to all the documents in the
database.
Set documents = db.AllDocuments
„ The Search method of NotesDatabase returns all documents that match the
specified criteria. The document collection returned from this method is
unsorted.
Set documents = db.Search({Region = "Asia Pacific"}, _ Nothing,
0)

Note: {} can be used as a string delimiter.


„ The FTSearch method of NotesDatabase conducts a full-text search of the
database.
Set documents = db.FTSearch ("Asia Pacific", 10)
„ The UnprocessedDocuments property provides access to the group of
documents that meet the selection criteria of the currently executing agent, but
have not yet been processed by that agent.
Set documents = db.UnprocessedDocuments

Retrieving documents from the collection

Use the following methods to access specific documents in the collection:


„ GetFirstDocument
„ GetNextDocument
„ GetLastDocument
„ GetNthDocument

Stud ent Gu ide Page No. 124 231


Preview
Le sso n 8 „ Using ViewEntr y a nd D ocu men t C olle ction s

Using the NotesDocumentCollection Class...(continued)

Use NotesDocumentCollection

Students will modify the code for an existing button so that it gathers the names of
stars in the listed movies and displays these names in the document.

232 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L esso n 8 „ Us in g Vie wEn try an d Doc ume nt Collection s

Using the NotesDocumentCollection Class...(continued)

Use NotesDocumentCollection

In this guided practice, you will add code to a button on the Movie form that lists all
the stars of that movie. The code:
„ uses a NotesDocumentCollection to gather the response documents of the
current movie.
„ loops through the collection, gathering the names of the stars listed in each of
the documents.
„ stores these names in an array.
„ displays the array of names in the document., after processing all the
documents in the collection.
Follow these steps to complete this guided practice.

Step Action

1 Open the Movie form and click List Actors.

2 Add the following code to the button after the statement: 'Add code here...
'turn off autoreload, go into editmode
uidoc.editmode=True
uidoc.autoreload=False
'get back-end document of the current document
Dim doc As notesdocument
Set doc=uidoc.document
'get the viewentry representing what is in the
' movie category, stored in viewkey
Dim viewkey As String
Dim ventry As notesviewentry
viewkey=doc.MovieTitle(0)
Set ventry=v.getentrybykey(viewkey)
'get the document of the view entry,
' kdoc for key document
Dim kdoc As notesdocument
Set kdoc=ventry.document

(continued on next page...)

Stud ent Gu ide Page No. 125 233


Preview
Le sso n 8 „ Using ViewEntr y a nd D ocu men t C olle ction s

Using the NotesDocumentCollection Class...(continued)

234 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L esso n 8 „ Us in g Vie wEn try an d Doc ume nt Collection s

Using the NotesDocumentCollection Class...(continued)

Use NotesDocumentCollection...

Step Action

3 Add the following code after the last statement in Step 2.


'get the responses in a collection
Dim rcol As notesdocumentcollection
Set rcol=kdoc.responses
'check to see if there are responses
If rcol.count=0 Then
Messagebox "There are no actors"
Exit Sub
End If

4 Add the following code after the last statement in Step 3.


'scroll through responses to get actors,
' populate the array
Dim actors() As String
Dim rdoc As notesdocument
Dim arraycounter As Integer
arraycounter=0
Redim actors(rcol.count-1)
Set rdoc=rcol.getfirstdocument
Do Until rdoc Is Nothing
actors(arraycounter)=rdoc.actor(0)
arraycounter=arraycounter+1
Set rdoc=rcol.getnextdocument(rdoc)
Loop

(continued on next page...)

Stud ent Gu ide Page No. 126 235


Preview
Le sso n 8 „ Using ViewEntr y a nd D ocu men t C olle ction s

Using the NotesDocumentCollection Class...(continued)

236 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L esso n 8 „ Us in g Vie wEn try an d Doc ume nt Collection s

Using the NotesDocumentCollection Class...(continued)

Use NotesDocumentCollection

Step Action

5 Add the following code after the last statement in Step 4.


'update document
doc.MovieActors=actors
'save document
doc.save True,True
'update the front end with the back end and save
uidoc.reload
uidoc.save
'turn autoreload back on
uidoc.autoreload=True
'go back to read mode
uidoc.editmode=False

6 Compile the code and save the form.

7 Open a movie document in the Notes client (from the Movies view).

8 Click List Actors and observe the effects of the code.

Stud ent Gu ide Page No. 127 237


Preview
Le sso n 8 „ Using ViewEntr y a nd D ocu men t C olle ction s

238 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


D
Reusing Code and
Processing Run-Time
Errors
Lesson 9 Reusing Code
Lesson 10 Processing Run-Time Errors

© Cop yr ig ht IB M Co rpo ratio n 200 2. All rig hts re serv ed.


Preview
Le sso n 9 „ R eu si ng C od e

9
Reusing Code

Present the lesson objectives.

240 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L esso n 9 „ R eu si ng C od e

9
Reusing Code

This lesson focuses on sharing code among the scripts of your application. It
begins with a discussion of variable scope and how to define and instantiate
global variables that can be used in multiple programs. It then introduces how to
create functions and subroutines to make code more modular. The lesson ends
with using a script library.

Objectives

After completing this lesson, you should be able to:


9 Describe the scope of a variable.
9 Define a LotusScript function and subroutine.
9 Write a function.
9 Write a subroutine.
9 Describe what a script library does.
9 Use a script library.

Stud ent Gu ide Page No. 130 241


Preview
Le sso n 9 „ R eu si ng C od e

Defining the Scope of a Variable

What is a code module?

Explain the concept of a code module. We have not been concerned about this
yet because all of our code has been written in single events. Now we will look at
declaring one set of global variables that can be accessible to multiple events.

The scope of a variable

Explain the diagram. It shows that variables declared in the Globals section of an
object are available to the events of that object. However, variables defined within
those events are not available to any other event.

242 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L esso n 9 „ R eu si ng C od e

Defining the Scope of a Variable

So far in this course, you have defined all variables within the script that uses
them. These variables are only accessible with the script that declares them. For
this reason, they are said to have procedure scope. LotusScript offers the ability to
define variables that have a module scope and are therefore accessible to all
scripts contained in that module.

What is a code module?

A module is a set of code that shares the same address space in memory. Each
element has its own module of code associated with it. Examples of modules
include forms, fields, and buttons. Declaring a variable in the form module makes
it accessible to all buttons and fields on the form.

The scope of a variable

The following diagram shows the relationship of options and variable declarations
defined in the (Globals) section of an object and the other events of the object.

Stud ent Gu ide Page No. 131 243


Preview
Le sso n 9 „ R eu si ng C od e

Defining the Scope of a Variable...(continued)

Declaring a variable with module scope

Open Domino Designer and show students where to place variable declarations
for an entire module.

Declare global variables for a view

Present the activity by:


„ Identifying which database and form students will use.
„ Asking if students have any questions before starting the activity.
„ Review the activity with students to make sure they understand.

244 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L esso n 9 „ R eu si ng C od e

Defining the Scope of a Variable...(continued)

Declaring a variable with module scope

To declare a variable with module scope, place the declaration statement outside
of a procedure. The Programmers pane in Domino Designer provides a place for
you to declare variables that have module scope.
For example, the Objects tab allows you to:
„ Declare variables that you want accessible to all scripts in the entire form in
Globals.
„ Declare variables that you want accessible to all scripts in a particular field or
button in Declarations.

Declare global variables for a view

In this activity, modify the code in the Movies view to declare commonly used
variables so they are accessible to all code modules in the view.
Follow these steps to declare global variables.

Step Action Result

1 In the Demos and Activities


database, Open the Movies view.
Select the Report on a Genre-
Update the UI action.

2 Find the following statements that


declare object variables for the
NotesView and the NotesUIView
classes:
Dim uiv As NotesUIView
Dim v As NotesView

3 Cut each declaration out of the The v and uiv object variables can
action code and paste it into the now be instantiated in any module in
Movies (Globals) module. the view.

4 Save the view and test the action. The action runs as it did before. The
advantage this activity illustrates is
that you do not have to declare
variables for the front-end view or the
back-end view for any other actions in
this view. You can use the global
variables.

Stud ent Gu ide Page No. 132 245


Preview
Le sso n 9 „ R eu si ng C od e

Setting Global Variables

Setting variables in the PostOpen event

Explain the advantage of setting variables in the PostOpen event of a form or


view. The variables are ready to use in actions or buttons or other events as soon
as the design element loads into memory.
Explain the example code from the Student Guide.

246 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L esso n 9 „ R eu si ng C od e

Setting Global Variables

Once variables are declared in a module, they can be set or instantiated


anywhere within that module. A common practice is to instantiate the front-end
and back-end objects for the form or view in the PostOpen event. This allows
actions or buttons to access the data contained in the view or form instantly.

Setting variables in the PostOpen event

Defining variables while the module loads can improve performance of the scripts
that use the variables. Each UI class has a PostOpen event that runs after the
object is loaded. You can place variable assignments in this event so that they are
ready when the scripts on the object run.
Example
The following code assigns object references, declared in the (Globals) script, in
the PostOpen event of the NotesUIDocument.
Sub PostOpen (Source As NotesUIDocument)
Set w = New NotesUIWorkspace
Set db = w.CurrentDatabase
Set uidoc = Source
End Sub

Stud ent Gu ide Page No. 133 247


Preview
Le sso n 9 „ R eu si ng C od e

Setting Global Variables...(continued)

Set object variables in the PostOpen event

Students will set the object variables in the PostOpen event.

248 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L esso n 9 „ R eu si ng C od e

Setting Global Variables...(continued)

Set object variables in the PostOpen event

In this activity, move the statements that instantiate the global variables declared
in the Movies view in the Inventory database.
Follow these steps to set the object variables in the PostOpen event.

Step Action Result

1 Open the Movies view in Domino


Designer and select the Report on
a Genre-Update the UI action.

2 Find the following statements that


set the global object variables for
the NotesView and the
NotesUIView classes:
Set uiv = w.CurrentView
Set v = uiv.View

3 Add the following statements to the Result: The v and uiv object
Movies (View) module in the variables will be instantiated when the
PostOpen event. view opens, which makes them
Set uiv = Source available to any module in the view.
Set v = uiv.View This speeds up the application and
avoids setting the same variables
repeatedly.

4 Save the view and test the action. Result: The action runs as it did
before. The advantage of this
activity is that you can now access
the object data for the front-end
and back-end views from
anywhere in the view, because the
global variables are set as soon as
the view opens.

Stud ent Gu ide Page No. 134 249


Preview
Le sso n 9 „ R eu si ng C od e

Exercise: Modify code to run more


efficiently

Students will modify the code on the Course form in the Inventory database

250 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L esso n 9 „ R eu si ng C od e

Modify code to run more efficiently

In this exercise, modify the code on the Course form in the Inventory database
so that the front-end document and back-end document are instantiated when the
form loads and are available to all the buttons.

Tasks

Perform the following tasks to complete this exercise:


„ Examine the Count Students and List Students button scripts.
„ Declare the common object variables doc and uidoc so that they are
accessible to the entire form. (Remove the declarations from the button code.)
„ Instantiate those two variables when the form loads. (Remove instantiation
from the button script.)
„ Save and test the code.

Stud ent Gu ide Page No. 135 251


Preview
Le sso n 9 „ R eu si ng C od e

Building Functions

Defining new functions

Show students some of the functions provided by LotusScript.


Give reasons for defining your own functions.
Illustrate that when you enter the Function declaration in Domino Designer, the
editor automatically appends the End Function statement.

252 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L esso n 9 „ R eu si ng C od e

Building Functions

Placing code in functions allows you to modularize your programs for easier
maintenance. A function is a named piece of code that performs a particular
action and returns a value. That value can be a scalar, variant, or object reference
data type.

Defining new functions

Use the Function keyword to define a new function.


Syntax
Function functionName (parameter1, parameter2) As datatype
' function statements
' set return value of function
End Function

Example
Function calcTotal (orderPrice As Single, orderAmt As Integer)
As Double
' calculate and return the total price
calcTotal = orderPrice# * orderAmt#
End Function

Stud ent Gu ide Page No. 136 253


Preview
Le sso n 9 „ R eu si ng C od e

Building Functions...(continued)

Using the Exit Function statement

Explain when and how to use the Exit Function statement.


Present the example from the Student Guide, which exits the function if the
database fails to open.

254 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L esso n 9 „ R eu si ng C od e

Building Functions...(continued)

Using the Exit Function statement

The Exit Function statement terminates execution of the current function.


Execution continues in the script that called the function.
Function getTitle (serverName as String, fileName as String)
Dim s As NotesSession
Set s = New NotesSession
Dim db As NotesDatabase
Set db = New NotesDatabase (serverName, fileName)
' If db is not open, stop the function
If db.IsOpen Is False Then
Exit Function
End If
' Return db title
getTitle = db.Title
End Function

Stud ent Gu ide Page No. 137 255


Preview
Le sso n 9 „ R eu si ng C od e

Building Subroutines

Subroutines and functions

Review the difference between a function and a subroutine.


Other than the return value, they are essentially the same.

The Exit Sub statement

The Exit Sub statement is equivalent to the Exit Function statement.

256 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L esso n 9 „ R eu si ng C od e

Building Subroutines

A subroutine is similar to a function, but it does not return any value.

Defining a subroutine

A subroutine starts with the Sub keyword and ends with the End Sub keyword. A
subroutine can accept parameters from the calling script.
Syntax
Sub subroutineName (parameter1, parameter2)
'
' subroutine statements
End Sub

Example
Sub alertForBlankField (fieldValue As Variant)
' Display a message to the user if the field is blank
If (fieldValue Is Nothing) Then
Messagebox "Please enter a value in the field"
End if

End Sub

Using the Exit Sub statement

The Exit Sub statement terminates execution of the current subroutine. Execution
continues in the script that called the subroutine.
Example
This example subroutine instantiates object variables for the UI document and the
back-end document when run in the PostOpen event of a form. It assumes that
the uidoc and doc variables are defined globally. If the variable passed to the
subroutine does not contain a UI document object, the subroutine exits.
Sub instantiateDoc (currentDoc As NotesUIDocument)
If (currentDoc Is Nothing) Then Exit Sub
uidoc = source
doc = uidoc.Document
End Sub

Stud ent Gu ide Page No. 138 257


Preview
Le sso n 9 „ R eu si ng C od e

Building Script Libraries

Create a script library

Open Domino Designer and show students how to create a script library.

258 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L esso n 9 „ R eu si ng C od e

Building Script Libraries

A script library is a module of code that you can reuse in the scripts of the
database that contains it. A script library may contain variable declarations,
functions, and subroutines that can be used in multiple forms, view, actions, and
agents. Using script libraries, you can avoid re-coding the same procedure in
many places.

Creating a script library

Follow these steps to create a script library.

Step Action

1 Open the database in Domino Designer.

2 Expand Shared Code in the Design list, and select Script Libraries.

3 Click New LotusScript Library.

4 In the Programmers pane, select the appropriate script from the Objects tab.

5 Add code to the script to define variables, functions, and subroutines that you
will use in other scripts of the database.

6 Choose FileÆSave to compile the code and save the script library.

Stud ent Gu ide Page No. 139 259


Preview
Le sso n 9 „ R eu si ng C od e

Using Script Libraries

Using a script library in another script

Introduce the Use statement as the mechanism for incorporating a script library in
your application.

Use statements

Describe the syntax of the Use statement.


Show the students where to enter the use statement in Domino Designer.

260 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L esso n 9 „ R eu si ng C od e

Using Script Libraries

Using a script library in another script

To incorporate a script library into another scriptable object, enter a Use statement
specifying the appropriate script library. Place the Use statement in the Options
script of the object.
Code contained in the (Options), (Declarations), Initialize, and Terminate
events of the library becomes available as though it were in the current objects.
User-defined functions and subroutines are also available as though they were in
the current object.

Use statements

At run time, the Use statement loads a module of script for use in the current
module being loaded. The external module is loaded before running the Initialize
subroutine of the current module.
Example
„ A script library named Error Checking contains the following subroutine:
errorCheck
„ The following statement placed in the (Options) script of a form makes the
errorCheck function available to the buttons and fields on the form:
Use "Error Checking"
„ The following statement invokes the subroutine:
Call errorCheck()

Stud ent Gu ide Page No. 140 261


Preview
Le sso n 9 „ R eu si ng C od e

Using Script Libraries...(continued)

Use the Error Checking script library

Students will modify the Movie form to display a message if errors are detected.

262 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
L esso n 9 „ R eu si ng C od e

Using Script Libraries...(continued)

Use the Error Checking script library

In this activity, use the function in the Error Checking script library to display a
common message when an error is detected. First you will define all global values
then you will define the form’s events.
Follow these steps to complete this activity.

Step Action

1 Open the Movie form in the Demos and Activities database.

2 Before using the script library, declare and instantiate a global variable for
the UI document.
In the Programmer’s Pane, select (Globals) M Æ(Declarations). Add the
following code:
Dim uidoc As NotesUIDocument

3 Load the script library so it can be used on the form. In the Programmer’s
Pane, select (Options) and add the following code:
Use "ErrorChecking"

4 Add the following code to the PostOpen event:


Set uidoc = Source

5 Add the following code to the QuerySave event to check that values were
entered into the fields on the form:
If (uidoc.FieldGetText("MovieTitle") = "") Then
Call errorcheck()
Continue = False
ElseIf (uidoc.FieldGetText("MovieCategory")="") Then
Call errorcheck()
Continue = False
ElseIf (uidoc.FieldGetText("Media") = "") Then
Call errorcheck()
Continue = False
End If

6 Save the form and preview it in Notes. Try to save a document without
entering any values.

Stud ent Gu ide Page No. 141 263


Preview
Le sso n 10 „ Pro ces sing Ru n-Time Errors

10
Processing Run-Time Errors

Present the objectives from the Student Guide.

264 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Le sso n 10 „ Pro ces sing Ru n-T im e Erro rs

10
Processing Run-Time Errors

The final lesson in this course discusses how to use the On Error statement and
set up error handling routines to process run-time errors. It introduces the error
constants and how to use them in your code.

Objectives

After completing this lesson, you should be able to:


9 Trap run-time errors using the On Error statement.
9 Write error handlers.
9 Define a run-time error.

Stud ent Gu ide Page No. 142 265


Preview
Le sso n 10 „ Pro ces sing Ru n-Time Errors

Processing Run-Time Errors

Run-time errors

Outline the procedure for processing run-time errors.

266 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Le sso n 10 „ Pro ces sing Ru n-T im e Erro rs

Processing Run-Time Errors

Run-time errors are found when a script is executed. The LotusScript compiler
cannot predict these errors when you save the code. Run-time errors generally
prevent the script from running to completion. The following are examples of run-
time errors:
„ Attempting to access a server that is down
„ Failing to instantiate an object before calling one of its methods
„ Running out of memory

Processing run-time errors

By default, when a run-time error occurs, LotusScript displays a message


informing the user of the error and the script terminates. You can override this
behavior by adding code to your scripts.
To process run-time errors, do the following:
„ Detect, or trap, the error with an On Error statement.
„ Write a routine to handle the error(s) appropriately.

Stud ent Gu ide Page No. 143 267


Preview
Le sso n 10 „ Pro ces sing Ru n-Time Errors

Processing Run-Time Errors...(continued)

Using On Error to detect run-time errors

Introduce the On Error statement.


Explain the syntax and the example from the Student Guide.

268 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Le sso n 10 „ Pro ces sing Ru n-T im e Erro rs

Processing Run-Time Errors...(continued)

Using On Error to detect run-time errors

The On Error statement intercepts run-time errors and passes control to an error
handling routine.
Syntax
The On Error statement has the following syntax:
On Error GoTo label
Example
The following code for a button uses On Error to invoke an error handling routine
called errHandler when any run-time error occurs.
Sub click (Source As Button)
On Error GoTo errHandler
%Rem
other statements
%End Rem
errHandler:
' code to process error
Exit Sub

Stud ent Gu ide Page No. 144 269


Preview
Le sso n 10 „ Pro ces sing Ru n-Time Errors

Processing Run-Time Errors...(continued)

Parts of an error handling routine

Describe the parts of the error handling routine (or error handler).

Using the Resume statement

Explain that the Resume statement is one way to return from an error handling
routine.
Open Domino Designer Help to display more details about this statement.

270 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Le sso n 10 „ Pro ces sing Ru n-T im e Erro rs

Processing Run-Time Errors...(continued)

Parts of an error handling routine

An error handling routine is designed to resolve run-time errors. How the routine
handles the error can depend on the error and the application.
The following table describes the parts of an error handling routine.

Part Description

Label Names the routine.

Statements to process the error LotusScript statement to process the error that
invoked the routine.

Statement to end the error handling Determines how the script exits or continues.
routine This statement can be one of the following:
„ Resume
„ Exit Function
„ Exit Sub

Using the Resume statement

The Resume statement in an error handling routine directs LotusScript to continue


executing the script that caused the error. When a resume statement is executed,
LotusScript clears its error flags and prepares to trap the next error.
The following table describes the three options for where the script continues
executing.

Statement Function
Resume 0 Continues executing at the statement that
caused the current error.
Resume Next Continues executing at the statement following
the one that caused the current error.
Resume label Continues executing at the specified label.

Stud ent Gu ide Page No. 145 271


Preview
Le sso n 10 „ Pro ces sing Ru n-Time Errors

Processing Run-Time Errors...(continued)

Example of an error handling routine

Explain the code in the example from the Student Guide.

Identifying the error that was trapped

Describe the functions available to identify the error that Domino trapped.
Domino Designer Help contains the run-time error messages.

272 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Le sso n 10 „ Pro ces sing Ru n-T im e Erro rs

Processing Run-Time Errors...(continued)

Example of an error handling routine

The following is an example of an error handling routine that simply informs the
user that an error has occurred and continues executing the script.
ErrHandler:
Messagebox "An error has occurred."
Resume Next

Identifying the error that was trapped

Inside an error handling routine, you can identify what error has occurred using
built-in LotusScript functions. These functions return standard messages and
numbers describing the error.
The following table describes the functions that identify the error.

Part Function
Err Returns a number identifying the current error
Erl Returns the line number in the script source
code that caused the current error.
Error$ Returns a text message describing the current
error.

Note: Once a Resume statement executes, the error information is cleared and
these functions will return nothing until the next error occurs.

Stud ent Gu ide Page No. 146 273


Preview
Le sso n 10 „ Pro ces sing Ru n-Time Errors

Processing Individual Errors

Error constants

Open LSERR.LSS, usually located in the Lotus/Notes directory, in Notepad (or


similar editor) to show students the error constants.

Using predefined error constants

List benefits of using the error constants rather than the integer values they
represent.

Including lserr.lss in your code

Explain the %Include compiler directive.


Show students how to add the constant file in Domino Designer.

274 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Le sso n 10 „ Pro ces sing Ru n-T im e Erro rs

Processing Individual Errors

Error constants

Domino specifies standard error numbers as constants. The following table lists
some error constants and the errors they represent.

Constant Error Description

ErrOpenFailed A file could not be opened because it was not


found, it is locked by another program, or it is
corrupted.

ErrFileNotFound The file referred to cannot be found.

ErrObjectVariableNotSet The object reference variable was never


instantiated and therefore the property or
method cannot be executed.

ErrOutOfMemory There is not enough system memory to perform


the operation.

Using predefined error constants

Domino specifies standard error constants in the LSERR.LSS file. This file defines
names for the error codes LotusScript uses to identify all of the run-time errors
that can occur.
Programmers should use the constants to refer to the errors instead of the actual
number for the following reasons:
„ Your code is easier to read, since the names of the constants are more
descriptive than the numbers.
„ Your code will be unaffected if Lotus must change the error values.

Including lserr.lss in your code

To use the constants to identify errors, include the file in a script that loads before
the other scripts in the application.
To include the error constants, enter the following statement in the (Options) event
of a scriptable object:
%Include "lserr.lss"

Stud ent Gu ide Page No. 147 275


Preview
Le sso n 10 „ Pro ces sing Ru n-Time Errors

Processing Individual Errors...(continued)

Trapping individual errors

You can write code that traps for a specific error to occur. If that error occurs, it is
routed to a special error handling routine.

276 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Le sso n 10 „ Pro ces sing Ru n-T im e Erro rs

Processing Individual Errors...(continued)

Trapping individual errors

You can trap specific errors using the predefined constants and direct them to
particular error handling routines.
Syntax
Use the following syntax to invoke a particular error handling routine for a specific
error.
On Error errorConstant GoTo label
Example
The following code will invoke the noFileFound error handling routine if the
database file name does not exist on the server. If the script cannot open the
database for another reason, it will invoke the openFailed error handling routine.
(Options)
%Include "lserr.lss"
(Click)
Sub click (Source As Button)
On Error ErrFileNotFound GoTo noFileFound
On Error ErrOpenFailed GoTo openFailed
'other statements
Call db.Open ("","discuss.nsf")
'other statements
' there were no errors so exit the sub
Exit Sub
noFileFound:
' error handling routine for not finding the file
Messagebox "Could not find database file."
Resume Next
openFailed:
' error handling routine for failing to open the database
Messagebox "Could not open database file."
Resume Next
' finished subroutine
Exit Sub

Stud ent Gu ide Page No. 148 277


Preview
Le sso n 10 „ Pro ces sing Ru n-Time Errors

Processing Individual Errors...(continued)

Defining your own error conditions

You can create your own constants to represent errors that may occur in the
application. You can set up conditions that trigger the errors and invoke error
handling routines.

Processing your error conditions

Explain the example from the Student Guide.

278 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Le sso n 10 „ Pro ces sing Ru n-T im e Erro rs

Processing Individual Errors...(continued)

Defining your own error conditions

You can define your own error constants and messages to use in your scripts.
„ Declare a constant to represent the error condition.
CONST OutOfRange = 99037
„ Use the Error statement to signal the occurrence of the error.
If <error condition> Then
Error OutOfRange, "Number out of range"
End if

Processing your error conditions

You process your errors just as you process those that Domino recognizes by
default. The following code defines an OutOfRange error and invokes the
errorRange routine to process it.
'Define a constant
CONST OutOfRange = 99037
'Trap the error
On Error OutOfRange
'If the error condition occurs, trigger the error
If <error condition> Then
Error OutOfRange, "Number out of range"
End If

Stud ent Gu ide Page No. 149 279


Preview
Le sso n 10 „ Pro ces sing Ru n-Time Errors

280 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Appendix A
Exercise Solutions

© Cop yr ig ht IB M Co rpo ratio n 200 2. All rig hts re serv ed.


Preview
A pp en di x A „ E xerc is e S ol ut i on s

Lesson 1: Choosing a Data Type


Exercise

In this exercise, determine the appropriate data types for variables.

Determine the appropriate data types for variables

The following table shows the declaration statement for different variable
descriptions.

Variable Description Variable Declaration

The number of days a discussion Dim days As Integer


topic is active

A message to alert users of an error Dim msg As String

The price of a piece of merchandise Dim price As Currency

The distance between two cities Dim distance As Double

The name of a form in a Domino Dim formName as String


database

A „ 2 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Appendix A „ Exer cis e Solution s

Lesson 2: Creating a New Copy of a


Database Exercise

In this exercise, create a button to copy a database.

Create a button that copies a database

Follow these steps to complete this exercise.

Step Action

1 In the Demos and Activities database, create a button, named Create a


Database, on the CreateDB form.

2 Add the following code to the click event of the new button to create a copy of
the Inventory database on your local machine:
'dim object reference variables
' sdb is the source database,
' tdb is the target database
Dim sdb As NotesDatabase
Dim tdb As NotesDatabase
'point sdb to source db on server
'replace ?? with name of server, if necessary
Set sdb=New NotesDatabase("??","Inventory.nsf")
'create tdb from sdb
Set tdb = sdb.CreateCopy ("","NewInventory.nsf")

3 Add the following code to change the title of the new database to Inventory:
'change title
tdb.Title="NewInventory"

4 Add the following code to display a message box stating that the database
has been copied and the name has been changed:
'display new title
Messagebox "The new title is " & tdb.Title

5 Save the form and test the button.

U s i ng Lo tu s S c r ip t i n I B M L o tu s D o m in o A p pl i c a t i on s A „ 3
Preview
A pp en di x A „ E xerc is e S ol ut i on s

Lesson 3: Retrieving Your Access Level


Exercise

In this exercise, use LotusScript and the Domino objects to retrieve the access
level to a database on the instructor’s server and display it in a message box.

Display the access level for the Students group

Follow these steps to complete the exercise.

Step Action

1 Create a button on the ACL Entry Exercise form in the Demos and Activities
database. Name the button Get Access to DB on Server.

2 Add the following code to open the DEMACTLS-INST.NSF database on the


classroom server:
'get database object, using the database
' where the script lies, use notessession
Dim db As NotesDatabase
Set db=New NotesDatabase ("??","DemActLS-inst.nsf")

3 Add the following code to access the Students ACL entry:


'get acl from the database
Dim dbacl As NotesACL
Set dbacl = db.ACL
'get the Students entry
Dim dbaclentry As NotesACLEntry
Set dbaclentry = dbacl.GetEntry("Students")

(continued on next page…)

A „ 4 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Appendix A „ Exer cis e Solution s

Lesson 3: Retrieving Your Access Level Exercise...(continued)

Display the access level for the Students group...

Step Action

4 Add the following code to use a select case statement to set a display string
to a text value representing the ACL level:
'declare string
Dim dispstring As String
'get acl level
Select Case dbaclentry.level
Case ACLLEVEL_NOACCESS
Dispstring="No Access"
Case ACLLEVEL_DEPOSITOR
Dispstring="Depositor"
Case ACLLEVEL_READER
Dispstring="Reader"
Case ACLLEVEL_AUTHOR
Dispstring="Author"
Case ACLLEVEL_EDITOR
Dispstring="Editor"
Case ACLLEVEL_DESIGNER
Dispstring="Designer"
Case ACLLEVEL_MANAGER
Dispstring="Manager"
End Select

5 Add the following code to display the name of the ACL entry and the access
level with a message box:
Messagebox "The level of access for " & _
dbaclentry.name & " is " & dispstring

6 Test the code by previewing the form in Notes and clicking Get Access to
DB on Server. Open the ACL of the database and verify the access level
your script retrieved.

U s i ng Lo tu s S c r ip t i n I B M L o tu s D o m in o A p pl i c a t i on s A „ 5
Preview
A pp en di x A „ E xerc is e S ol ut i on s

Lesson 4: Asking for User Input


Exercise

In this exercise, add a button to prompt users for information using the Prompt
method of the NotesUIWorkspace class.

Create a button that prompts users for information

Follow these steps to complete the exercise.

Step Action

1 Create a new button on the Course form in the Inventory database. Name
the button Request Course Description.

2 Add the following code to the Request Course Description button on the
course form:
'This button allows users to request
' a course description
'get workspace object
Dim w As NotesUIWorkspace
Set w=New NotesUIWorkspace
'create a variable to store the prompt
Dim promptresults As Integer
'display initial prompt to user and capture result
promptresults = w.prompt (PROMPT_YESNOCANCEL ,"Mail", _
"Click Yes to send your request via mail, " & _
"No to send your request via email, " & _
"Cancel to cancel this request")

3 Add the following code to verify the initial decision:


'prompt user based on result of initial prompt
If promptresults=1 Then
Call w.prompt (PROMPT_OK,"Mail", _
"Your request will be sent by mail")
Elseif promptresults = 0 Then
Call w.prompt (PROMPT_OK,"EMail", _
"Your request will be sent by email")
Else
Call w.prompt(PROMPT_OK,"Cancel", _
"Your request has been cancelled")
End If

4 Save the form and test the Request Course Description button.

A „ 6 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Appendix A „ Exer cis e Solution s

Lesson 5: Interacting with Users


Programmatically Exercise

In this exercise, add code to the Inventory database that displays a message to
the users, thanking them for signing up for a particular course. The message
should use the current user’s name and the course name from the current
document.

Plan the code

To complete the exercise, use the following:


„ QueryClose event of the Student form in the Inventory database.
„ NotesUIWorkspace and the NotesUIDocument classes.
„ The following methods and properties:
„ New to create a NotesUIWorkpace object.
„ CurrentDocument property of NotesUIWorkspace to create a
NotesUIDocument object.
„ GetFieldText method of NotesUIDocument to access values on the current
document.

U s i ng Lo tu s S c r ip t i n I B M L o tu s D o m in o A p pl i c a t i on s A „ 7
Preview
A pp en di x A „ E xerc is e S ol ut i on s

Lesson 5: Interacting with Users Programmatically


Exercise...(continued)

Display a message when users save a document

Follow these steps to complete the exercise.

Step Action

1 In the Inventory database (not the copy you created in an earlier exercise),
open the Student form.

2 Add the following code to the QueryClose event of the form:


'instantiate workspace
Dim w As NotesUIWorkspace
Set w = New NotesUIWorkspace
'get currentdocument
Dim uidoc As NotesUIDocument
Set uidoc = w.CurrentDocument
'get variable to hold message
Dim msg As String
'assign value to message using fullname and course
msg = "Thank you " + uidoc.FieldGetText("FullName")+ _
" for signing up for " + _
uidoc.FieldGetText("Course") _
+ " course."
' display the message
Call w.prompt (PROMPT_OK,"Info",msg)

3 Save the form.

4 Open one of the course documents from the Course Summary view and
click Add a student. Enter values and save the document.

A „ 8 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Appendix A „ Exer cis e Solution s

Lesson 7: Creating a Report Document


Exercise

In this exercise, create an action for the Course Summary view in the Inventory
database that generates a report identifying the number of students currently
registered for a course.

Create a report for the Ceramics course

Follow these steps to complete this exercise.

Step Action

1 In the Course Summary view, each student is listed as a child to the course
name. To determine the number of students currently registered for a course,
use the ChildCount property of the NotesViewEntry class.

2 Create a new Count Students action in the Course Summary view.

3 Add the following code to the action to retrieve the number of children for the
Ceramics view entry:
'We are accessing a document in the same
' database the script lies.
' get the session, and current database.
Dim s As NotesSession
Set s = New NotesSession
Dim db As NotesDatabase
Set db = s.CurrentDatabase
'locate the view to get the document, CS
Dim v As NotesView
Set v = db.GetView("CS")
'get the viewentry representing a course
Dim ventry As notesviewentry
Set ventry=v.getentrybykey("Ceramics")
'get the number of children
Dim count As Integer
count=ventry.childcount

(continued on next page…)

U s i ng Lo tu s S c r ip t i n I B M L o tu s D o m in o A p pl i c a t i on s A „ 9
Preview
A pp en di x A „ E xerc is e S ol ut i on s

Lesson 7: Creating a Report Document Exercise...(continued)

Create a report for the Ceramics course…

Step Action

4 Add the following code to the action to create a new document that can be
displayed through the Report form:
'create document
Dim doc As notesdocument
Set doc=db.createdocument
'add form field
doc.form="R"

5 Add the following code to add the course name, number of students, and
user name to the document, and save it:
'add other fields
doc.ReportCourse = "Ceramics"
doc.ReportNumStudents = count
'save document
doc.save True,True

6 Add the following code to update the view to display the new report
document:
'refresh back-end view
v.Refresh
'update the front-end view
Dim w As NotesUIWorkspace
Set w = New NotesUIWorkspace
Call w.ViewRefresh

7 Save the view and preview it in the Notes client. Click the Count Students
action to test it.

A „ 10 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Appendix A „ Exer cis e Solution s

Lesson 7: Creating a Report Document Exercise...(continued)

Challenge

To build an action in the Course Summary view that creates a report for the
course representing the document that is currently selected in the view, use the
following code:
'We are accessing a document in the same database
' the script lies.
'Therefore, get the session and the current database.
Dim s As NotesSession
Set s = New NotesSession
Dim db As NotesDatabase
Set db = s.CurrentDatabase
' get the workspace and ui view
Dim w As NotesUIWorkspace
Set w = New NotesUIWorkspace
Dim uiv As NotesUIView
Set uiv = w.CurrentView

'get the category of the currently selected document


Dim currentCategory As String
currentCategory = uiv.CaretCategory
'locate the view to get the document, CS
Dim v As NotesView
Set v = uiv.View
'get the ViewEntry representing current category
Dim ventry As NotesViewEntry
Set ventry = v.GetEntryByKey(currentCategory)
'get the count
Dim count As Integer
count=ventry.ChildCount

'create document
Dim doc As NotesDocument
Set doc = db.CreateDocument
'add form field
doc.Form = "R"
'add other fields
doc.ReportCourse = currentCategory
doc.ReportNumStudents = count
'save document
call doc.save (True,True)

'refresh back-end view


Call v.refresh()
'update the front-end view
Call w.viewrefresh ()

U s i ng Lo tu s S c r ip t i n I B M L o tu s D o m in o A p pl i c a t i on s A „ 11
Preview
A pp en di x A „ E xerc is e S ol ut i on s

Lesson 9: Modify Code to Run More


Efficiently

This exercise modifies the code on the Course form in the Inventory database so
that the front-end document and back-end document are instantiated when the
form loads, and are available to all the buttons on the form.

Setting global variables

The Count Students and List Students buttons use the variable uidoc to
reference the current document displayed in Notes and the back-end document
related to the current document.
Follow these steps to declare the common object variables doc and uidoc so
that they are accessible to the entire form.

Step Action

1 Select the Count Students button on the Course form of the Inventory
database.

2 Select the following statement in the Click event:


Set uidoc = source

3 Choose EditÆCut.

4 In the Programmers pane, select the PostOpen event and choose


EditÆPaste.

5 Select the following statement in the Click event of the Count Students
button on the Course form:
Set doc=uidoc.document

6 Choose EditÆCut.

7 In the Programmers pane, select the PostOpen event and choose


EditÆPaste.

8 Select the List Students button and delete the following two statements from
the Click event:
Dim uidoc as NotesUIDocument
Dim doc As NotesDocument

A „ 12 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Appendix A „ Exer cis e Solution s

Lesson 9: Setting Global Variables...(continued)

Save and test the code

Follow these steps to save and test the code.

Step Action

1 Choose FileÆSave to compile the modified code on the Course form.

2 In the Notes client, open a course document from the Course Summary
view.

3 Select Pottery from the list of course names.

4 Click Count Students.


Result: The code runs as it did before, and adds the number of students to
the document.

5 Click List Students.


Result: The code runs as it did before, and adds the list of students to the
document.

U s i ng Lo tu s S c r ip t i n I B M L o tu s D o m in o A p pl i c a t i on s A „ 13
Preview
A pp en di x A „ E xerc is e S ol ut i on s

A „ 14 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Appendix B
Exam Competencies

© Cop yr ig ht IB M Co rpo ratio n 200 3. All rig hts re serv ed.


Preview
A pp en di x B „ E xam Co mpe t enc ie s

LotusScript in Notes for Advanced


Developers Exam Competencies

Exam Number/Type: 273 - Multiple Choice


Please visit the certification Web site at www.lotus.com/certification for the
most current information regarding certification exams
Description:
Covers LotusScript in Notes as it relates to these competency areas
Š Database Level Competencies
Š Document Level Competencies
Š Programming Concept Competencies
Š User Interface Competencies
Š Production/Architecture Issues
„ Database Level Competencies
; Establish connectivity within the databases
; Establish connectivity between Notes databases
; Establish connectivity among Notes/non-Notes databases
; Access session information
; Access DbDirectory information
; Create a database
; Delete a database
; Create a new replica database
; Access a database
; Set up ODBC connectivity
„ Document Level Competencies
; Establish relationships among documents
; Make response documents
; Create a document using methods and items
; Show a created view using the refresh method on NotesView
; Delete a document
; Create/delete items
; Create/delete rich text items
; Access documents through collections
; Search for all documents in a database
; Search for all documents in a view
; Process a collection
; Full Text Search a collection

B „ 2 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Ap pe nd ix B „ Exam Co mp eten cies

LotusScript in Notes for Advanced Developers Exam


Competencies ...(continued)
; Count a collection
; View documents through the User Interface
; Access all documents in a database
; Load the LSX module
; Create agents
; Create newsletters
„ Programming Concept Competencies
; Agent server document settings
; Control Field events
; Control Form events
; Control Button events
; Make use of scope
; Solve problems using the following data structures:
‚ Looping (Iterating)
‚ Logic (Program flow)
‚ Options (alternation/branching)
‚ Functions/subroutines (branching)
‚ Array processing
‚ Option base
‚ Declaration/initialization
; Build error checking routines
; Debug programming problemsSetting up View Logging
„ User Interface Competencies
; Access documents using UIWorkspace
; Access documents using UIDocument
; Log to a Log file
„ Production/Architecture Issues
; Plan and architect problem solutionsEnable server agents through script
; Solve security issues through script
; Decide script scope & source issues
; Mark documents processed through script

U s i ng Lo tu s S c r ip t i n I B M L o tu s D o m in o A p pl i c a t i on s B „ 3
Preview
A pp en di x B „ E xam Co mpe t enc ie s

LotusScript in Notes for Advanced Developers Exam


Competencies ...(continued)
; Decide script programming design and implementation issues such as:
‚ When to use/not use script
‚ When to use form events versus field actions
‚ When to use view columns versus fields
‚ When to use interactive versus batch
‚ When to use the front end/back end for. . .
ß getting data from databases
ß setting document contents
‚ When to use in memory versus on disk structures
‚ When to use gets versus loops

B „ 4 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Ap pe nd ix B „ Exam Co mp eten cies

LotusScript in Notes for Advanced


Developers Sample Questions

1. Competency Area:Database Level

Specific Objective:Delete a database


Question:Geraldine is creating a script which deletes a database. The script
prompts the user for the location of the database to be deleted, then deletes it.
What must she use in order to ensure the Notes Database object (db) is
representing a database?
A. The open property on the NotesDatabase object
B. The Isopen property on the NotesDatabase object
C. The createdate property on the NotesDatabase object
D. The constructor sub (New) on the NotesDatabase object to open the database
Correct answer: B

2. Competency Area:Document Level

Specific Objective:Access documents; count a collection


Question:Amelia wants to determine how many documents are in a database.
Which one of the following can she use to do this?

A. The All property on the NotesDatabase class


B. The Views property on the NotesDatabase class
C. The AllDocuments method on the NotesDatabase class
D. The AllDocuments property on the NotesDatabase class
Correct answer: D

U s i ng Lo tu s S c r ip t i n I B M L o tu s D o m in o A p pl i c a t i on s B „ 5
Preview
A pp en di x B „ E xam Co mpe t enc ie s

LotusScript in Notes for Advanced Developers Sample


Questions...(continued)

3. Competency Area:Programming Concepts

Specific Objective:Debug programming problems


Question: Consider the following:

dim s as new NotesSession


dim db as NotesDatabase
set db=s.CurrentDatabase Line 1
dim col as NotesDocumentCollection
dim fld as string
set col=db.AllDocuments Line 2
dim doc as NotesDocument
set doc=col.GetFirstDocument Line 3
fld=doc.form Line 4
messagebox fld
When this code is run, it returns the error message, type mismatch. Which line is
causing the error?
A. Line 1
B. Line 2
C. Line 3
D. Line 4
Correct answer: D

4. Competency Area:User Interface

Specific Objective:Access documents using UIDocument

B „ 6 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Ap pe nd ix B „ Exam Co mp eten cies

LotusScript in Notes for Advanced Developers Sample


Questions...(continued)
Question: Which UIDocument class property or method controls synchronizing
the UIDocument with its document?
A. AutoReload method
B. AutoReload property
C. AutoRefresh method
D. AutoRefresh property
Correct answer: B

5. Competency Area:Production/Architecture Issues

Specific Objective: Solve security issues through script


Question: Gretchen wants to create a script that changes the SystemAdmin
group's ACL access. If the SystemAdmin group's access is below Editor, it should
be changed to Manager. Which of the following properties and methods should
she investigate?
A. Grant on the NotesSession object
B. QueryAccess on the NotesDatabase Object
C. GrantAccess on the NotesDatabae Object
D. QueryAccess and GrantAccess on the NotesDatabase Object
Correct answer: D

U s i ng Lo tu s S c r ip t i n I B M L o tu s D o m in o A p pl i c a t i on s B „ 7
Preview
A pp en di x B „ E xam Co mpe t enc ie s

B „ 8 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Appendix C
Learning Processes and
Instructor Guide
Conventions

© Cop yr ig ht IB M Co rpo ratio n 200 3. All rig hts re serv ed.


Preview
A pp en di x C „ Le arn in g Pro cess es an d Instr ucto r Gu id e Co nve ntion s

Using the Learning


Processes

This section includes the relevant information about the standard curriculum
development learning processes and icons. Use this section as a tool to prepare
to deliver the course successfully.
Note: The terms instructional unit and unit are used to refer to general units of
instruction, including modules, lessons, topics, activities, and so on.

What are learning processes?

Learning processes are the basic instructional strategies that the instructor uses
to encourage students to achieve learning objectives. Presentation, Discussion,
Demonstration, Guided Practice, and other delivery strategies provide the means
for facilitating instruction and skills acquisition. A unique icon indicates the
recommended learning process and displays next to the learning process
instruction.
For the learning processes that follow, you will see:
„ A summary description
„ The appropriate icon
„ A table indicating what the instructor and students will see in their guides
„ Teaching tips
Note: Not all the learning processes are used in every course.

What is e-learning?

Some of the descriptions that follow include references to e-learning. E-learning


education offerings and seminars are delivered using online tools. E-learning
courseware can be self-paced or instructor-led. Instructor-led e-learning courses
use the tools of either the Lotus® Sametime® Meeting Center or the Lotus®
LearningSpace® Virtual Classroom.

C „ 2 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Appendix C „ Le arn in g Pro ces ses an d Ins tr ucto r Gu ide Co nve ntion s

Using the Learning Processes...(continued)

Assessment

An Assessment is an evaluation learning process used to gauge the student's


knowledge. Assessments provide feedback to both the student and instructor,
and can be formal or informal. Assessments can be collected and graded, or
assessment answers are provided.
Assessments are used to:
„ Assess prior knowledge (pre-test).
„ Provide self-assessment.
„ Calculate the course grade.
„ Verify attainment of course learning goals.
The following table lists the supporting materials that may be included in the
Instructor and Student Guides for this learning process.

Instructor Guide Contents Student Guide Contents

„ Assessment icon „ Assessment icon


„ Questions „ Answers
„ Answers
„ For Lotus LearningSpace materials,
reference to the Question Set or
assessment that was enabled for the
session.

Note: Answers to the assessments are included in the Assessment Answers


appendix of both the Student Guide and Instructor Guide.

Teaching tips

9 Clearly state the purpose of the assessment (for example, to provide self-assessment,
assess prior knowledge, or calculate course grade).
9 When applicable, provide information on the organization's policies regarding grading
and privacy of information.
9 When delivering an e-learning question, allow for transmission time before tallying
answers.

U s i ng Lo tu s S c r ip t i n I B M L o tu s D o m in o A p pl i c a t i on s C „ 3
Preview
A pp en di x C „ Le arn in g Pro cess es an d Instr ucto r Gu id e Co nve ntion s

Using the Learning Processes...(continued)

Case Study

A Case Study is an experience-based learning process used for discovery and


exploration, or as a culmination of learning objectives.
The Case Study presents a problem or scenario. Students work independently or
in groups to provide recommendations, problem resolutions, or solution
strategies. Although Case Study materials may not include a correct answer, they
may include recommended solutions, a list of considerations, or resolution
strategies.
The following table lists the supporting information that may be included in the
Instructor and Student Guides for this learning process.

Instructor Guide Contents Student Guide Contents

„ Case Study icon „ Case Study icon


„ Presentation strategy „ Facts and scenario of case
„ Workgroup recommendations „ Problem to be solved
„ Solution methodology „ Possible solutions, considerations, or
„ Estimated timing for student work strategies
„ Possible solutions, considerations, or
strategies
„ Estimated timing for discussion
„ Discussion tips

Teaching tips

9 Follow the recommended timing for the case study, but modify accordingly based on
the students’ expertise.
9 Lead a discussion on a recommended solution.
9 Discuss the solution(s) and, as a group, list the advantages and disadvantages of the
suggested alternatives.

C „ 4 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Appendix C „ Le arn in g Pro ces ses an d Ins tr ucto r Gu ide Co nve ntion s

Using the Learning Processes...(continued)

Demonstration

A Demonstration is a presentation of a procedure, user interface, solution, or


other course-related task or structure. In general, instructors use Demonstrations
to present content, procedures, and structure.
Students watch but do not participate in Demonstrations.
Demonstrations can be used to:
„ Present complex material.
„ Illustrate a new topic.
„ Present a topic quickly, without presenting it in detail.
„ Provide a change of pace within the course.
„ Implement specific parts of the classroom scenario.
The following table lists the supporting information that may be included in the
Instructor and Student Guides for this learning process.

Instructor Guide Contents Student Guide Contents

„ Demonstration icon „ Procedure icon


„ Instructions (and, if applicable, data) an „ When appropriate, the related generic
instructor uses to perform a particular Procedure or information related to the
Demonstration task being demonstrated.
„ Specific content information that should
be presented
„ For e-learning materials, instructions to
transition to the Screen Sharing mode

Demonstration database
For some offerings, a Demonstration database is included on the Classroom
Tools media. Sample Demonstrations are pre-built for the instructor to use.

U s i ng Lo tu s S c r ip t i n I B M L o tu s D o m in o A p pl i c a t i on s C „ 5
Preview
A pp en di x C „ Le arn in g Pro cess es an d Instr ucto r Gu id e Co nve ntion s

Using the Learning Processes...(continued)

Teaching tips

9 Relate the Demonstration to the information or Procedure in the Student Guide.


9 Ask questions during the Demonstration to ensure student comprehension of the task
or information referenced in the demonstration.
9 Consider directing the students to look at the Procedure after completing the
demonstration to help ensure that the students watch the instructor perform the steps.
9 For e-learning delivery, use Screen Sharing and enable participants to complete some
procedural tasks.

C „ 6 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Appendix C „ Le arn in g Pro ces ses an d Ins tr ucto r Gu ide Co nve ntion s

Using the Learning Processes...(continued)

Discussion

A Discussion is an interactive activity in which the instructor solicits opinions,


ideas, beliefs, and experience regarding course-related content or issues.
Discussions can be used to:
„ Solicit analogies from student experiences.
„ Introduce a new topic or sequence that builds on existing skills or knowledge.
„ Ascertain general understanding or assimilation of course content.
The following table lists the supporting information that may be included in the
Instructor and Student Guides for this learning process.

Instructor Guide Contents Student Guide Contents

„ Discussion icon „ Related procedure or information


„ Questions to ask students and ideal
answers to the questions
„ Important information or ideas that
could result from the Discussion
„ Transition statements to begin or
summarize discussion
„ For e-learning materials, tips or
alternatives for conducting the
Discussion with a large or distributed
student group

Teaching tips

9 Limit the Discussion to topics directly related to the lesson objective.


9 Ask questions to encourage participation.
9 Summarize the Discussion to help students relate the topics discussed with the
course content.
9 For e-learning delivery, use the hand raise tools, chat, and poll techniques to solicit
feedback.
9 For e-learning delivery, in sessions that do not use online audio, encourage students
to use the electronic hand raise feature to indicate that they would like to participate.
9 For e-learning delivery, remind students to state their name before speaking, to
identify themselves to classmates who might not recognize their voice.
9 For e-learning delivery to large groups, consider conducting the discussion using
other means, for example, Chat or Discussion Board.

U s i ng Lo tu s S c r ip t i n I B M L o tu s D o m in o A p pl i c a t i on s C „ 7
Preview
A pp en di x C „ Le arn in g Pro cess es an d Instr ucto r Gu id e Co nve ntion s

Using the Learning Processes...(continued)

Exercise

There are two types of exercises: online and paper-based.

Online Exercise icon


Students complete the exercise on the computer.

Paper-based Exercise icon


Students complete the exercise on paper.

An Exercise is a problem-solving learning process, which can provide immediate


positive feedback when successfully completed. Exercises challenge students to
use the skills they have learned in an instructional unit.
Exercises may occur in the middle or at the conclusion of a unit.
Exercises do not provide instructions for completion. Instead, they provide a set of
criteria, a problem statement, or general task that students use to develop a
working solution for a specific goal.
Note: Solutions to Exercises are included in Appendix A: Exercise Solutions of
both the Student Guide and Instructor Guide.
The following table lists the supporting information that may be included in the
Instructor and Student Guides for this learning process.

Instructor Guide Contents Student Guide Contents

„ Exercise icon „ Exercise icon


„ Estimated timing for the Exercise „ Facts or scenario
„ Recommendations on how students „ Problem to be solved
should perform the Exercise, such as „ Goal to be achieved
working in groups or individually „ Task to complete
„ Special preparation instructions „ Criteria for completion
„ Tips to help students resolve any
problems that they may encounter
„ For e-learning materials, instructions for
conducting a small group Exercise
using the Breakout Session tools or
other methods of collaboration.

C „ 8 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Appendix C „ Le arn in g Pro ces ses an d Ins tr ucto r Gu ide Co nve ntion s

Using the Learning Processes...(continued)

Teaching tips

9 Refer to any special preparation students must complete, or issues they may
encounter during the Exercise.
9 Remain available during the Exercise and be prepared to answer students' questions.
9 Review the Exercise solution in Appendix A: Exercise Solutions at the end of the
exercise.
9 Make group assignments clear and achievable.
9 For e-learning delivery that uses the Breakout Session tools, schedule the session as
a final class activity, one that does not require students to return to the main live
session. This simplifies the navigation that students need to complete.
9 For e-learning delivery where students have little or no experience with Breakout
Session tools, assign a teaching assistant to initiate the session and facilitate the
group’s work.

U s i ng Lo tu s S c r ip t i n I B M L o tu s D o m in o A p pl i c a t i on s C „ 9
Preview
A pp en di x C „ Le arn in g Pro cess es an d Instr ucto r Gu id e Co nve ntion s

Using the Learning Processes...(continued)

Guided Practice

A Guided Practice is a student-centered learning process that allows students to


learn by performing a task. Guided Practices can be instructor-led or self-paced.
„ Instructor-led practice is used to present a new procedure or a new user
interface.
„ The instructor and students perform the procedure at the same time.
„ The classroom projection system or monitor displays the instructor’s
actions.
„ The Student Guide includes detailed instructions for completing the task.

„ Self-paced practice allows students to apply a learned skill or knowledge.


Students perform a procedure independently, using instructions.
The following table lists the supporting information that may be included in the
Instructor and Student Guides for this learning process.

Instructor Guide Contents Student Guide Contents

„ Guided Practice icon „ Guided Practice icon


„ Indicates a recommendation as to „ Step/Action or Step/Action/Result table
whether the Guided Practice should be that contains specific information
instructor-led or self-paced „ Step/Action or Step/Action/Result table
„ Preparation directions that contains specific tasks to complete
„ Estimated timing for the self-paced
practice
„ Potential issues
„ Content details that should be
presented in the instance of an
instructor-led practice

Teaching tips

9 Briefly review the directions before starting the Guided Practice.


9 If the students perform the Guided Practice on their own, be available during the
guided practice so they can ask questions.
9 Review the Guided Practice results when completed to ensure that students have
successfully completed it or demonstrated comprehension of the skills.
9 Provide additional information as required.
9 Relate the Guided Practice information to the job task whenever possible.

C „ 10 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Appendix C „ Le arn in g Pro ces ses an d Ins tr ucto r Gu ide Co nve ntion s

Using the Learning Processes...(continued)

Presentation

A Presentation is an instructor-led learning process used to present content and


instruction using a variety of media.
Presentations include:
„ Freelance slides
„ Multimedia executables
„ Videos
„ Whiteboard slides for e-learning offerings
„ Follow Me pages for e-learning offerings
The following table lists the supporting information that may be included in the
Instructor and Student Guides for this learning process.

Instructor Guide Contents Student Guide Contents

„ Presentation icon „ Related Procedure or information


„ Slide title or content „ Slide content
„ Media for the Presentation
„ Location of Presentation materials in
the Classroom Tools database or
directory
„ Estimated timing for the Presentation
„ Special setup or delivery instructions
„ Content information to be presented
„ For e-learning materials, instructions to
share or use Whiteboard Tools
„ For e-learning materials, Follow Me
page name
„ For e-learning materials, instructions to
select and send the Follow Me page

U s i ng Lo tu s S c r ip t i n I B M L o tu s D o m in o A p pl i c a t i on s C „ 11
Preview
A pp en di x C „ Le arn in g Pro cess es an d Instr ucto r Gu id e Co nve ntion s

Using the Learning Processes...(continued)

Teaching tip

9 Keep the Presentation within the scope of the content.


9 Enhance the Presentation using your own words and relate the information to the
appropriate objective.
9 For e-learning delivery, use the Whiteboard Tools to annotate the slide and the
Whiteboard Pointer tool to focus attention.
9 For e-learning delivery, when displaying a new Whiteboard or Whiteboard slide, pause
to allow time for each student's display to refresh.
9 For e-learning delivery, when presenting a Web page, pause to allow the new browser
window to open and display the page on the student's machine. When finished
presenting the page, instruct students to close the window and display the live session
window.

C „ 12 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Appendix C „ Le arn in g Pro ces ses an d Ins tr ucto r Gu ide Co nve ntion s

Using the Learning Processes...(continued)

Procedure

A Procedure is a generic task that is documented using step-by-step instructions.


Procedures are always presented in a table format.
A Procedure can also be in the form of a checklist. Checklists can be used to list:
„ Tasks required to complete a specific objective.
„ Tasks that are part of a process.
„ Items, equipment, requirements, or other materials necessary to complete a
task.
The following table lists the supporting information that may be included in the
Instructor and Student Guides for this learning process.

Instructor Guide Contents Student Guide Contents

„ When accompanied by a „ Procedure icon


Demonstration, instructions, such as „ Step/Action or Step/Action/Result table
preparation and specific steps
„ The purpose of the procedure as it
relates to the subject matter

Teaching tips

9 If the Procedure is related to a Demonstration, direct the students to look at the


Procedure after completing the Demonstration. This helps ensure that the students
watch the instructor perform the task.
9 For a checklist, periodically review the checklist to show progress in completing a task
or process.
9 For a checklist, recommend to students that they use the checklist as a reference.
9 For a checklist, create and present a slide or flipchart containing the checklist. Track
the progress of the larger process on this flipchart or slide.

U s i ng Lo tu s S c r ip t i n I B M L o tu s D o m in o A p pl i c a t i on s C „ 13
Preview
A pp en di x C „ Le arn in g Pro cess es an d Instr ucto r Gu id e Co nve ntion s

Using the Learning Processes...(continued)

Review

A Review is used to reiterate main concepts and can be used to gain feedback,
assess learning, review critical material, or transition from one instructional unit to
another.
A Review may be used to:
„ Review the results of a Guided Practice, Case Study, or Exercise.
„ Seek feedback on the pace or level of instruction.
„ Provide self-assessment.
„ Present assessments that can be stored and graded in e-learning delivery.
„ Reinforce content.
The following table lists the supporting information that may be included in the
Instructor and Student Guides for this learning process.

Instructor Guide Contents Student Guide Contents

„ Review icon „ No Student Guide contents


„ Questions
„ Answers
„ Main concepts
„ For e-learning materials, reference to
the question or assessment that was
enabled for the session

Teaching tips

9 Use questions to review content and not restate objectives.


9 If students exceed the course prerequisites and/or demonstrate mastery of the key
concepts, consider excluding some questions.
9 For e-learning delivery, refer to the Course Setup Guide for instructions to create the
Question Set and add it to the live session materials.
9 When delivering an e-learning Question Set, allow for transmission time before
tallying the responses.

C „ 14 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


Preview
Appendix C „ Le arn in g Pro ces ses an d Ins tr ucto r Gu ide Co nve ntion s

Using the Learning Conventions

This section includes the relevant information about the standard curriculum
development conventions and icons. Use this section as a tool to prepare to
deliver the course successfully.

What are conventions?

Conventions are rules that govern how to display specific types of information.
The following are standard curriculum development conventions and icons that
may be used within this courseware.

Cautions are short, descriptive paragraphs meant to warn of potential


pitfalls or areas where students could experience problems during class
or back on the job.
Caution

Critical classroom setup procedures that the instructor must complete


before presenting subsequent content.
Instructor
Task

Note: Notes appear in the Instructor Guide and Student Guide and can be used to
note differences in content.

Notes for the Instructor: Special notes the course developer wants to
communicate to the instructor regarding delivery, classroom strategy, classroom
tools, exceptions, and other special considerations.

Tip: Tips provide additional guidance, or a hint, for students about a topic or task.

U s i ng Lo tu s S c r ip t i n I B M L o tu s D o m in o A p pl i c a t i on s C „ 15
Preview
A pp en di x C „ Le arn in g Pro cess es an d Instr ucto r Gu id e Co nve ntion s

C „ 16 Usin g L otu sScrip t in IBM Lo tus Domin o Ap plication s


© Copyright IBM Corporation 2003.
All rights reserved.

Lotus software
IBM Software Group
One Rogers Street
Cambridge, MA 02142

IBM Lotus Domino Designer


Release 6
Product Code ND540

Printed in the USA

You might also like