a guide to document locking in notes/domino 6

30
A Guide to Document Locking in Notes/Domino 6 No portion of this publication may be reproduced without written consent. 3 James Ray specializes in enterprise integration with Oracle and SAP, Web devel- opment, and Notes/Domino 6 migrations. He is a Principal Certified Lotus Professional (IBM Certified Advanced) System Administrator and Application Developer for Notes and Domino releases 4, 5, and 6, as well as a Microsoft Certified Systems Engineer. You can contact him at [email protected]. (complete bio appears on page 32) The new document locking functionality in Notes/Domino 6 has been long wished-for, sorely needed, and enthusiastically welcomed by administrators and developers alike. Most software users are familiar with the concept of document or record locks. In a relational database, records can be locked to prevent editing of records by multiple users at the same time. In word-processing software, document locking prevents users from editing documents that are being edited by other users. In collaborative applications, where many users have Editor access to the same documents, the ability to lock documents is especially desirable. Until Notes/Domino 6, however, native document locking was not available, and developers and administrators had to look to third-party add-on products or homegrown solutions for document locking functionality. Lotus Notes/Domino 6 document locking provides robust functions that can make applications more sturdy and user-friendly. It is not, however, the panacea for save and replication conflicts that many had hoped it would be. There are new issues and requirements relating to application implementation, architecture, and business practices, all of which need to be addressed before you can deploy document locking successfully. To help you get the most from this new feature and make informed decisions for successful implementation, I’ve written this article to serve as your essential guide to Notes/Domino document locking. It covers the out-of-the-box functionality, a look at what’s happening under the covers, things to watch out for, and how, when, and why to customize. A Guide to Document Locking in Notes/Domino 6 James Ray

Upload: johnsonaaa

Post on 22-Dec-2015

267 views

Category:

Documents


48 download

DESCRIPTION

A Guide to DocumentLocking in Notes/Domino 6The new document locking functionality in Notes/Domino 6 has beenlong wished-for, sorely needed, and enthusiastically welcomed byadministrators and developers alike.

TRANSCRIPT

Page 1: A Guide to Document Locking in Notes/Domino 6

A Guide to Document Locking in Notes/Domino 6

No portion of this publication may be reproduced without written consent. 3

James Ray specializes inenterprise integration withOracle and SAP, Web devel-opment, and Notes/Domino 6migrations. He is a PrincipalCertified Lotus Professional(IBM Certified Advanced)System Administrator andApplication Developer forNotes and Domino releases 4,5, and 6, as well as a MicrosoftCertified Systems Engineer.You can contact him at [email protected].

(complete bio appears on page 32)

The new document locking functionality in Notes/Domino 6 has beenlong wished-for, sorely needed, and enthusiastically welcomed byadministrators and developers alike.

Most software users are familiar with the concept of document orrecord locks. In a relational database, records can be locked to preventediting of records by multiple users at the same time. In word-processingsoftware, document locking prevents users from editing documentsthat are being edited by other users. In collaborative applications, wheremany users have Editor access to the same documents, the ability tolock documents is especially desirable. Until Notes/Domino 6, however,native document locking was not available, and developers andadministrators had to look to third-party add-on products or homegrownsolutions for document locking functionality.

Lotus Notes/Domino 6 document locking provides robust functionsthat can make applications more sturdy and user-friendly. It is not,however, the panacea for save and replication conflicts that many hadhoped it would be. There are new issues and requirements relating to application implementation, architecture, and business practices, all of which need to be addressed before you can deploy documentlocking successfully.

To help you get the most from this new feature and makeinformed decisions for successful implementation, I’ve written thisarticle to serve as your essential guide to Notes/Domino documentlocking. It covers the out-of-the-box functionality, a look at what’shappening under the covers, things to watch out for, and how, when,and why to customize.

A Guide to DocumentLocking in Notes/Domino 6

James Ray

Page 2: A Guide to Document Locking in Notes/Domino 6

THE VIEW September/October 2004

4 www.eVIEW.com ©2004 THE VIEW. All rights reserved.

I’ve created a demonstration Notes/Domino 6.5database (doclockd.nsf)1 that includes sample code forthe examples in this article, including:

LotusScript code to apply and remove locks usingdocument locking methods

Formula code to remove lock items from a document

A solution for locking and unlocking documentsvia in-view editing, including code to changeview column custom colors to indicate lock statusand the type of lock applied

A lock decay solution to avoid permanentlylocked documents that have been forgotten by the users who locked them

A check-in/checkout solution for effective document locking on the Web

We’ll start with a look at the native Domino functionality.

Native Notes/Domino Document LockingIn Notes/Domino 6, document locking is the processyou can employ to prevent users from editing certaindocuments when those documents are being edited byanother user. The “lock holder” of a document can bea single user or a group of users. When a Notes clientuser attempts to edit a document that is already lockedby another user, the user is notified immediately —via a modal, pop-up dialog box — that the documentis locked by another user and cannot be edited whileit is locked. (We’ll look at Web client operationlater.) By locking the document, Domino preventsthe “race condition”2 that occurs when different usersedit the same document almost simultaneously.Domino forces the editing process to be serial and notparallel, thereby reducing the chances of conflicts.(For a summary of what happens when multiple usersedit a document at the same time without documentlocking enabled, see the “Replication and SaveConflicts” sidebar.)

1 At www.eVIEW.com, click THE VIEW Journal > Download Files >September/October 2004 > the title of this article. Scroll to the bottomof the abstract page for the download link.

2 A race condition (or hazard) is deviant behavior that occurs in a processdue to a critical dependence on the sequence of events.

As a bonus, the Document Locking Demo database(doclockd.nsf at www.eVIEW.com) includes theseuseful libraries not mentioned in the article:

GetQueryStringArgument — Parses the query string argument from the query_stringCGI variable.

libAgentLoggingClassV2 — A LotusScriptlibrary that contains a user-defined class to per-form logging of agent execution. Used in theLockDecay agent.

libDocLocking — LotusScript library where thebulk of document locking code is kept.

libMisc — LotusScript library that houses miscellaneous functions such as getting key-words and database objects.

libReplaceSubstring — Has two versions of a LotusScript function to replace a substring— a plain one and a version that uses theEvaluate() function to execute formula languageinside the LotusScript code.

libSecurityClass — Used inlibAgentLoggingClassV2 and libDocLocking.

libStringFunctions — Miscellaneous stringfunctions.

Bonus Information

Page 3: A Guide to Document Locking in Notes/Domino 6

A Guide to Document Locking in Notes/Domino 6

No portion of this publication may be reproduced without written consent. 5

How Documents Are Locked

In order for a user or agent to lock or unlock a document,the user (or executor of an agent) must have at leastAuthor-level access to the database, and he or shemust also have Author access to the document. If thedocument is locked and the user is trying to unlock it,the user must also be the explicit lock holder for thatdocument or in the group that is listed as the lockholder. If these requirements are met, there are fivemain ways to lock/unlock a document:

• Select the document from a view or folder andchoose “Lock/Unlock Document” from theActions menu.

• Select the document from a view or folder and choose “Lock/Unlock Document” from a pop-up menu.

• Automatically lock and unlock the document byediting the document.

• Programmatically lock and unlock the documentthrough the use of Notes formula language orLotusScript code (in Notes/Domino 6.0) or Javacode (in Notes/Domino 6.5).

• Programmatically lock and unlock the documentthrough direct editing of items on the documentbackend.

Once a document is locked, it cannot be edited by anyone except the lock holder or holders. Even auser with Manager access to the database cannot editthe document if he or she is not a lock holder. Userswith Manager access can, however, unlock the documentand then edit it. In fact, the manager of a databasecan unlock any document, regardless of whether ornot he or she is the lock holder.

Note!

Users with Manager access must be careful whenexercising their authority to unlock a databasedocument. If they edit the document, they couldcause a conflict condition.

What’s Happening Behind the Scenes?

There are a whole host of clever activities takingplace behind the scenes when a document is beinglocked or unlocked. Before I show you what’s goingon, however, I’ll explain the types of locks that Dominoprovides and the system topology that supports documentlocking, so you can better understand how Dominosupports document locking.

Document Locking Topology and Lock TypesThe first requirement of document locking is that anydatabase that uses document locking must have a “masterlock server” defined in the database ACL, and thedatabase must be able to reach and communicate withthe master lock server. This requirement applies to data-bases on Domino servers as well as databases on localNotes clients. As you might expect, you will need to payattention to this requirement when setting up multiplereplicas of databases, especially replicas on remoteuser desktops or remote servers with limited replication.

The second requirement is that the master lockserver must contain a replica of the database that hasdocument locking enabled. Locks are applied andremoved in the replica on the master lock server, andlock statuses are propagated to replicas on othermachines. (We’ll go into how this is done later.)

When a user requests to lock or unlock a documentin a database in which document locking is enabled,Domino first determines whether or not the databasein which the request is being made is the same data-base that is on the master lock server:

• If the database in which the request is being madeis on the master lock server, then Domino nextdetermines whether the user is allowed to lock or unlock the target document, given the user’sdatabase ACL level and the lock holder status ofthe document.

• If the master lock server is remote to the databasein which the request is made, then Notes remoteprocedure calls (NRPCs) are made to the master

Page 4: A Guide to Document Locking in Notes/Domino 6

THE VIEW September/October 2004

6 www.eVIEW.com ©2004 THE VIEW. All rights reserved.

lock server to find out whether the document isavailable for locking/unlocking. These calls takeplace immediately if there is a current connectionto the master lock server; if there is no currentconnection, they take place at the next replicationor the next time a connection is made.

Depending on the topology of the database replicasand how a document is locked, a user can expect to

see one of four different types of locks applied to adocument: persistent, persistent-temporary, provisional,or provisional-temporary. To illustrate these locktypes, I’ll take you through some example scenarios.In each scenario, the target database is the one inwhich a user is attempting to edit a document.

• Scenario 1 (demonstrates persistent locks) —The target database is either on the master lock

In Lotus Notes, the Notes Object Service (NOS) keepstrack of when a document is edited and how manytimes the document has been edited. It does this bymonitoring and changing values in the document’s$Revisions item and originator ID (OID) whenever thedocument is edited and saved or revised. The OIDof a document contains the document’s universal ID(UNID), a sequence number, and a time stamp. TheUNID is a 32-digit, hexadecimal number that is uniqueto each document across all replicas of a database.In fact, according to the Inside Notes database onthe Lotus Domino Developer site, “Except for notesin replica copies of a database, no two notes in anydatabases anywhere in the world should ever havethe same UNID.” +

The OID sequence number indicates how many timesa document has been edited, and the time stampindicates when the document was last updated.The $Revisions item contains a list of time stamps forwhen the document was revised (the last entry in the $Revisions field is actually the OID time stamp).Together, $Revisions and the OID make up the refer-ence indicator to the “instance” of the Notes document.

Conflicts can occur when different users are editinga document at the same time. In this situation, thereis a race to determine which user will have his or herchanges saved in the document and which user willnot. There are two types of conflicts: save conflictsand replication conflicts.

A save conflict occurs when users are editing thesame document (or, more precisely, the sameinstance of a document in the same database replicaon the same server) at the same time. A save conflictresults in a Lotus Notes response document that islinked to its parent document. In this situation, theparent document contains the edited data from theconflict winner, and the response document containsthe edited data from the losing editor.

A replication conflict occurs when different users editdifferent instances of the same document in differentreplicas. Like save conflicts, replication conflicts produce a winner with changes saved in the maindocument and a loser with changes saved in aresponse document.

Notes determines the winner and losers of a conflictusing a document’s $Revisions and OID information.If a conflict is created (i.e., $Revisions has the samenumber of entries in each document instance, butthe last entries in the two documents do not match),the winner will be the document with the lowestsequence number in its OID. If the sequences arethe same in the OIDs, the winner will be the documentwith the most recent time stamp in its OID.

There are some replication and form design settingsthat have the potential to reduce the chances ofthese conflicts; however, Notes/Domino 6 documentlocking, if employed successfully, can prevent conflictsby stopping users from editing documents that arealready locked.

Replication and Save Conflicts

+ http://www-10.lotus.com/ldd/notesua.nsf/find/inside-notes

Page 5: A Guide to Document Locking in Notes/Domino 6

A Guide to Document Locking in Notes/Domino 6

No portion of this publication may be reproduced without written consent. 7

server or on a machine (server or client) that canreadily communicate with the master lock server.A user manually or programmatically requests tolock or unlock a document in the database.

• Scenario 2 (demonstrates persistent-temporarylocks) — This scenario uses the same databaseconfiguration as scenario 1; the difference is thatthe user is attempting to edit a document withoutmanually requesting that the document be lockedfirst (i.e., the user simply attempts to edit the document via the user interface).

• Scenario 3 (demonstrates provisional locks) —The target database is not on the master lock server, and the master lock server is unavailable.The user manually requests to lock or unlock adocument.

• Scenario 4 (demonstrates provisional-temporarylocks) — As in scenario 3, there is no communi-cation with the master lock server, except now theuser is locking the document as part of opening itin edit mode (without first manually locking thedocument).

• Scenario 5 (demonstrates the types of locks possible in situations where programmatic locking is attempted and the master lock server is unavailable) — The possible outcomes in thisscenario are the application of provisional locksor documents that cannot be locked at all.

As these scenarios will make clear, the persistentlock is the only type of lock that is safe — that is, apersistent lock ensures the prevention of data loss orconflicts, while a provisional lock does not.

Scenario 1 — Demonstrating Persistent Locks

In scenario 1, the target database is located on eitherthe master lock server or a machine (server or client)that can communicate with the master lock server viaa persistent network connection or dial-up.

When a user requests to lock or unlock a document in the target database, Domino checks the instance of this document in the replica on themaster lock server:

• If the document is already locked, the lock operation will not be permitted.

• If the lock operation is allowed and the user isallowed to lock/unlock the document, thenDomino applies a persistent lock to the documentinstance in the replica on the master lock server(and on the instance in the target database as well,if it is not on the master lock server). The usercan then choose to edit the document or not, asthe document is now locked from other users andwill remain so until another process unlocks thedocument (e.g., a manual unlock from the UI or aprogrammatic unlock).

• If the request is for an unlock operation and it isallowed by the master lock server based on theuser’s ACL level, then the target document isunlocked.

Persistent locks are safe in the sense that they canensure only one user can hold a lock on a documentat any given time. Thus, users can edit documentswithout fear that data will be lost. As you’ll see, persistent locks are the only safe locks to use.

Scenario 2 — Demonstrating Persistent-Temporary Locks

Scenario 2 is very similar to scenario 1 in that thetarget database is either on or can communicatereadily with the master lock server. In this case,the user is attempting to edit a document withoutmanually requesting to lock the document first.As soon as the user attempts to open the documentin edit mode through the UI, Domino communicateswith the master lock server and determineswhether the user is allowed to lock the document.If the user is allowed to lock the document and ifthe document is available for locking, the masterlock server places a persistent lock on the document.However, this persistent lock is only temporary; it will be removed after the user closes the document in the UI.

A persistent-temporary lock is considered safe, asit ensures no one else has the document locked while

Page 6: A Guide to Document Locking in Notes/Domino 6

THE VIEW September/October 2004

8 www.eVIEW.com ©2004 THE VIEW. All rights reserved.

Figure 1 Create a Provisional Lock?

The idea behind a provisional lock is that it canbe promoted to a persistent lock later, when the masterlock server becomes available. The catch is that thelock can only be promoted to a persistent lock if thedocument was not already locked through the masterlock server at the time that the persistent lock wasrequested and the provisional lock was applied. Later,we’ll look at what happens when there is an attempt topromote a provisional lock. For now, suffice it to saythat if the promotion fails, the user’s edits will be lost.

Clicking the Yes button in the dialog shown inFigure 1 causes a provisional lock to be placed on the document. If the user clicks No instead, then asecond dialog pops up (see Figure 2) to inform theuser that the master lock server was unavailable. Inthis case, no lock is applied to the document.

Best PracticesTeach your users to accept only persistent locks.Users should know that editing a document whileit is provisionally locked is risky — the only wayto ensure their edits will be preserved and not lostis to use a persistent lock.

You can optimize document locking in your envi-ronment by minimizing the situations that lead toprovisional locks — that is, by ensuring that thedatabases that have document locking enabled areon machines that can readily connect or have apersistent connection to the master lock server.

it is locked for this user. It differs from a persistentlock in that it is unlocked immediately upon endingthe editing session instead of persisting until anotherprocess unlocks the document.

Tip!

It is a good idea to design UIs (forms and views)so that end users know the status of a document.A simple computed text label on the form sufficesto indicate the current lock status of the docu-ment being edited.

Scenario 3 — Demonstrating Provisional Locks

In scenario 3, the user manually requests to lock orunlock a document in a database replica that is noton the master lock server, and the master lock serveris unavailable. This is similar to the situationencountered by users of local database replicas thatdo not have a current network connection to themaster lock server. In this case, the user is notifiedvia a modal dialog box that the master lock server is unavailable (see Figure 1; the truncation in the dialog’s text is reproduced as it naturally occurs).The user is asked if he or she would like to use aprovisional lock to lock the document.

Page 7: A Guide to Document Locking in Notes/Domino 6

A Guide to Document Locking in Notes/Domino 6

No portion of this publication may be reproduced without written consent. 9

Figure 2 The Message When the User Clicks “No” on the “Create a Provisional Lock?” Dialog

Figure 3 The Master Lock Server Is Unavailable (Cannot Unlock Document)

Figure 4 The Master Lock Server and Replica Are Not Available

If the user is attempting to unlock a document thatis already persistently locked in the target database,and the master server is unavailable, then the unlockoperation will fail, and the user will see a pop-up dialog indicating that the replica of this database onthe master server is unavailable (see Figure 3). Thesame error occurs when the master lock server isavailable but the replica of the database is not on themaster lock server. In any event, the user shouldunderstand that this message means that the documentis not safely locked — there’s no guarantee that his orher edits will be preserved.

If a user is attempting to unlock a provisionallock or a provisional-temporary lock (discussednext) and the master server is unavailable, theunlock operation will be allowed by the local replica of the database provided that the user is amember of the Lock Holders property of the lockeddocument, or the user has Manager access to thedatabase. However, the end user is performing thisoperation without a safety net, and the operation isnot entirely reliable.

Scenario 4 — Demonstrating Provisional-Temporary Locks

Scenario 4 is similar to scenario 3 in that there is nocommunication with the master lock server. However,now the user is requesting to lock the document aspart of opening it in edit mode. When the user triesto edit the document, the document-locking mechanismattempts to lock the document by communicatingwith the master lock server. Since the server isunreachable, the user is immediately prompted thatthe master lock server and master replica are notavailable, as shown in Figure 4.

Page 8: A Guide to Document Locking in Notes/Domino 6

THE VIEW September/October 2004

10 www.eVIEW.com ©2004 THE VIEW. All rights reserved.

At this point, the user can either cancel the editingattempt or click OK to continue and edit the document.If the user chooses to continue, a provisional-temporarylock is placed on the document. When this happens,the user may also see a warning from Lotus Notesthat the document has been modified since openingand it should be closed and reopened (see Figure 5).Apparently, a race condition occurs when a provisionallock is applied while a user has a document open andis editing it. As you’ll see, Domino modifies the document backend when a document is locked, whichmay be why this condition occurs. In other words,the process that modifies the backend of the documentto temporarily and provisionally lock the documentseems to conflict with the document being opened inthe UI.

The provisional-temporary lock is simply thetemporary version of the provisional lock and, assuch, it makes editing a risky proposition.

In addition, like its distant cousin the persistent-temporary lock, the provisional-temporary lock does notrequire the end user to overtly unlock the document.The provisional-temporary lock will disappear oncethe user closes the document in the user interface andthe master lock server is available to clear the lock.Therein lies the rub. The reason this lock was appliedwas because the master lock server was unavailable.This means that unlike the persistent-temporary lock,the provisional-temporary lock may not immediatelyclear when the locked document is closed in the UI.Until the master lock server is available, the provisional-temporary lock may linger. When the database replica

finally communicates with the master lock server, theprovisional-temporary lock will then disappear.

Scenario 5 — Attempting Locks with Programs

Scenario 5 is similar to scenarios 3 and 4 in that themaster lock server is unavailable, but scenario 5 alsocovers the situation where the user is executing code(either formula language, LotusScript, or Java) that isattempting to lock a document. When the user executescode in the Lotus Notes client to lock a document,one of two things can occur, depending on how thecode is written and what language is used:

• If the code is written in LotusScript or Java, the developer can allow or disallow provisionallocks when the user cannot persistently lock adocument. This is accomplished by simply passinga Boolean argument to the respective lock functionor method. If a true argument is passed, the provisional lock will automatically be applied if the persistent lock is not allowed; conversely, if a false argument is passed to the function ormethod, the lock will be denied and the user willbe prompted that the document cannot be lockedbecause the code cannot connect to the masterlock server (see Figure 6). To ensure that riskyprovisional locks are not used in your applications,I recommend that you pass a false argument here.

• If formula code is being executed, there are noarguments for allowing or disallowing provisionallocks when persistent locks are not possible. Infact, there is no indication to the user that thelocking operation or, for that matter, the unlocking

Figure 6 Cannot Connect to the Master Lock Server

Figure 5 UI Editing While Document Is Locked Causes a Race Condition

Page 9: A Guide to Document Locking in Notes/Domino 6

A Guide to Document Locking in Notes/Domino 6

No portion of this publication may be reproduced without written consent. 11

operation failed. There is simply no change tothe document.

Figure 7 summarizes the scenarios that we havejust discussed.

Lock PromotionAs you’ve seen, the persistent lock is the only type of lock that is safe for allowing users to begin editingdocuments. Provisional and provisional-temporarylocks are not intrinsically safe for allowing users tomake edits, because these lock types allow race conditions to occur and could result in data loss. The whole idea behind provisional and provisional-temporary locks is that, when the master lock serverbecomes available, they may or may not be promotedto persistent locks.

If a user creates a provisional or provisional-temporary lock on a document, the database replicamust communicate with the master lock server and

Scenario Lock Type Master Lock Server Method to Lock Document Safe for Editing

1 Persistent Available Manual/Menu Yes

2 Persistent-Temporary Available Automatic with document editing Yes

3 Provisional Unavailable Manual/Menu No

4 Provisional-Temporary Unavailable Automatic with document editing No

5a ProvisionalNote: An argument may be passed toallow/disallow locks

Unavailable Programmatic — LotusScript or Java code

No

5b None Unavailable Programmatic — formula code No

Figure 7 Lock Types

A provisional lock in database <YourDatabaseHere> has NOT been promoted to a hard lock. There was aconflict detected. Your changes may be found in the body of this message. A document link to the original document is attached to the end of the message.

Figure 8 Subject of E-mail Message Indicating the Unsuccessful Promotion of a Provisional Lock

its replica to trigger an attempted promotion for thelocks. The user triggers this communication in one of two ways — by manually initiating replicationwith the master lock server or by editing the documentwhile the master lock server is available. Both ofthese actions trigger document locking NRPCs to the master lock server, and the master lock serverattempts to promote any outstanding provisional orprovisional-temporary locks. (In the case of NRPCstriggered by editing the document in the UI, theattempt is to promote only the document being edited,not all documents in the database.)

If the promotion is successful and the persistentlock is applied, the user will receive a message in hisor her inbox that indicates a successful promotion andthat contains a doc link to the locked document. Ifthe lock promotion was unsuccessful, the user receivesa message that the lock was not promoted, and themessage will contain a doc link to the document thatis now locked by someone else. Figure 8 shows youDomino’s standard subject line for an e-mail messagethat tells the user about an unsuccessful promotion.

Page 10: A Guide to Document Locking in Notes/Domino 6

THE VIEW September/October 2004

12 www.eVIEW.com ©2004 THE VIEW. All rights reserved.

When a lock is placed on or removed from a document, Domino is actually modifying the backendof the document by adding or removing NotesItems.These items indicate the type of lock and the user underwhose authority the document is locked or unlocked.

When a persistent lock or persistent-temporarylock is applied to the document, two items are writtento the document, $Writers and $WritersDate. The$Writers item contains the user or group (lock holder)that has the document locked, and the $WritersDateitem contains the date that the document was persistentlylocked. When the document is unlocked using thedocument locking mechanisms, Domino removesthese two items from the document. In the case ofthe persistent-temporary lock, the removal of theitems takes place immediately when the document isclosed in the user interface.

When a provisional lock is applied to a document,a $PWriters item is added to the backend document,and it too contains the explicit lock holder or group oflock holders. Likewise, a $PTWriters item is addedfor a provisional-temporary lock type. (As a point ofreference, the $Writers, $PWriters, and $PTWritersitems are author access items, functioning similarly toAuthors fields.) However, there are no $PWritersDateor $PTWritersDate items added to the document, eventhough some Lotus Domino documentation seems tosuggest that there should be. In my testing withNotes/Domino 6.5, I never saw these items applied tolocked documents. Apparently, Lotus intended the$PWritersDate and the subsequent $PTWritersDateitems to be used for a lock decay feature that nevermade it into release 6. We will discuss lock decaylater in this article.

Adding items to a document’s backend withoutediting them through the UI is not such a novel idea,

Changes made to the database <YourDatabaseHere> have NOT been incorporated into the database. Therewas a conflict detected. Your changes may be found in body of this message. A document link to the originaldocument is attached to the end of the message.

Figure 9 Subject of E-mail Message Indicating a Failed Provisional-Temporary Lock

If the user creates a provisional-temporary lockby editing the document and saves the document underthat type of non-persistent lock, the user is now at themercy of the master lock server. If the document wasalready locked by another user prior to the second user’sedit/lock attempt, the provisional-temporary lock willnot be promoted. The unsuccessful user will receivea message similar to the one for the unsuccessful promotion of a provisional lock. Figure 9 shows youDomino’s standard subject for an e-mail message thattells the user about a provisional-temporary lock failure.

Both failure messages tell the user that their edits“may be found” at the bottom of the e-mail message.In reality, that is not the case — at least not in mytesting. Every time this situation occurs, the edits arelost with no means of retrieval by even the savviest ofadministrators. This shortcoming underlines the precarious nature of non-persistent lock types andstrengthens the case for persistent locks as being theonly safe locks to allow user editing. In fact, losingthe data in an unsuccessful lock promotion is worsethan dealing with replication or save conflicts. Atleast the data in a conflict document is retrievablethrough manual means. Later, see the section“Document Locking Setup and Administration” for adiscussion of how to prevent or minimize provisionallocks in your environment.

Behind the ScenesLet’s look now at what’s happening behind the sceneswhen a document is being locked or unlocked and themaster lock server is available for communication.Communication between the master lock server andthe Lotus Notes client is in the form of NRPCs. It takesapproximately 16 NRPCs to lock a single document.

Page 11: A Guide to Document Locking in Notes/Domino 6

A Guide to Document Locking in Notes/Domino 6

No portion of this publication may be reproduced without written consent. 13

as developers have been doing this for years. In fact,some of the core functionality of Lotus Notes involvesadding and removing backend note items. However,when a developer uses Notes formula language,LotusScript, or Java to modify the underlying data ofa note, the note’s OID is modified and replicationneeds to take place in order to synchronize documentinstances between database replicas. By contrast,when Notes/Domino 6 document locking adds orremoves items from the backend of a data note, thenote’s OID does not change and the changes to thedocument are not replicated. How, then, are documentlock statuses synchronized across multiple replicas?That’s what we’ll see next.

Propagating Lock Statuses to Other Replicas

When there is a current connection between therequesting client or server and the master server, theNRPCs that drive document locking move back andforth in real time, while the user is attempting to lockor unlock the document. If there is no connection tothe master lock server, this communication will nottake place until the next time the connection is madeand the master lock server and the remote server/clientreplicate. Replication triggers the document-lockingcalls between the master lock server and a remotereplica. Therefore, the NRPCs for document lockingare a by-product of the replication activity.

My testing bears this out. Locking/unlocking istriggered by replication, but locking/unlocking synchro-nization happens independently of the replication activity.

Note!

You can use replication to trigger and synchronizedocument locking, but you should not expect Notesreplication to always report that changes werereplicated.

Actually, I know two ways of triggering theNRPCs required to promote or synchronize document

locking with the master lock server: replication andopening a document on the remote client or server inthe UI in edit mode. The differences are these:

1. A replication-triggered NRPC will attempt to synchronize all the outstanding document locksbetween the two replicas.

2. Editing a document in the UI of the remote replicawill trigger the NRPC only for that document, noothers (as demonstrated in my testing).

Into Practice

Now that you’ve seen what the Notes/Domino document-locking implementation is all about, it’stime to get practical. Next, we turn to setup and admin-istration and then to programming document locking.

Document Locking Setup and AdministrationBefore document locking can be employed in a database, you must do two things:

• Configure the database for document locking, asdescribed below.

• Ensure that the database landscape and replicationtopology are set up properly to allow every replicaof the database (including remote replicas) tocommunicate with the master lock server.

As the document-locking scenarios we looked atearlier demonstrated, if any replica of a databasethat has document locking enabled cannot com-municate with the master lock server, documentlocking may be compromised and user data maybe lost.

Configuring a Database for Document Locking

Since document locking was first introduced in LotusNotes/Domino 6, the databases for which you want to enable document locking must have an on-diskstructure (ODS) of at least 43. I say at least because

Page 12: A Guide to Document Locking in Notes/Domino 6

THE VIEW September/October 2004

14 www.eVIEW.com ©2004 THE VIEW. All rights reserved.

at the time of this writing, Lotus Notes/Domino version7 beta 1 is available with the same ODS as Notes/Domino 6; however, this may change with the releaseof gold code.

Here are the steps to configure a database fordocument locking:

1. Go to the Basics tab of the database Propertieswindow and select the checkbox “Allow documentlocking” near the bottom of the window, asshown in Figure 10. This action requiresDesigner or higher-level access privileges in the database access control list (ACL).

2. Define a “Master Lock Server” in the databaseACL. (The master lock server is also known asthe administration server, which should alreadybe defined for most databases.) This setting isfound at the top of the Advanced tab on the data-base ACL window, as shown in Figure 11. Themaster lock server is a required setting, and it

Figure 10 The “Allow document locking” Database Property

Figure 11 The ACL “Master Lock Server” Setting

Page 13: A Guide to Document Locking in Notes/Domino 6

A Guide to Document Locking in Notes/Domino 6

No portion of this publication may be reproduced without written consent. 15

must be the same server for each replica of the database, regardless of how many replicasthe database has or on what other servers thereplicas are placed.

3. While you’re on the Advanced tab of the database ACL, I also recommend selecting“Enforce a consistent Access Control List across all replicas.” This setting can help prevent database replicas with incorrectlydefined master lock servers. Be aware, however,that administrators who have Manager rights tothe database can circumvent this setting.

4. Ensure that the defined master lock server actuallyhas a replica of the database for which documentlocking is being configured. The defined masterlock server must contain a replica of this data-base in order for document locking to work.

Once the database settings have been configured, document locking can and will attemptto operate without any additional programming orsetup needed. As mentioned above, you will stillneed to ensure that the database can communicatewith the master lock server.

Administering Document Locking

Since document locking relies on functionality thatis intrinsic to Lotus Notes and Domino (replication,Notes Object Service, Notes remote procedurecalls), it requires little additional maintenance.Administrators simply need to monitor replicationand client communication, and document lockingwill take care of itself.

Troubleshooting document-locking issues is similar to troubleshooting replication or mail routingissues. Document-locking issues are usually theresult of communication problems between a clientand server or between two servers.

Document Locking Strategy 101

In my experience, avoiding provisional locks is thename of the game when it comes to optimizingDomino’s native document-locking functionality.

Application developers can try to “code around” provisional locks to ensure that they are not used,but since the Notes client UI menu contains lock andunlock actions, there is no way to guarantee that arogue user will not defy the odds and provisionallylock a document. Here are some strategies that canhelp keep non-persistent locks to a minimum:

Educate your end users and management aboutprovisional locks, explaining their behavior andthe risks that they entail. If you can convinceyour application stakeholders that a policy isneeded to avoid provisional locks, even better.

Avoid having an abundance of remote databasereplicas. If you have remote replicas that do notcommunicate regularly to the master lock server,document locking in those remote replicas maynot function reliably.

Unless your Notes clients can reliably connectto the master lock server and your users under-stand that a document might not be locked untilmultiple replications have occurred (i.e., untilthe master lock server has replicated with allclients and servers that have replicas of thedatabase), avoid having local (Notes client)replicas of a database with document lockingenabled in your environment. Allowing suchreplicas is a recipe for help calls.

Tightening database ACL security can help prevent provisional locks. By keeping userswith Editor access and above to a minimum,you can reduce the chances of multiple userssimultaneously attempting to edit documents.

Important!

Make sure that the defined master lock serverhas a replica of the database. As you saw, ifthere is no replica on the master lock server,only provisional locks will be created and userswill never be able to unlock documents regard-less of whether the master lock server is avail-able to the client.

Page 14: A Guide to Document Locking in Notes/Domino 6

THE VIEW September/October 2004

16 www.eVIEW.com ©2004 THE VIEW. All rights reserved.

Programming Notes/Domino 6Document Locking in the Notes ClientSince Lotus Notes/Domino version 6.0, programmershave been able to use the Notes formula andLotusScript languages to code solutions with documentlocking. Java coding for document locking came withthe release of Notes/Domino 6.5. In the demonstrationdatabase that accompanies this article, I provideexamples written in all three languages.

One of the most important aspects of programmingdocument locking is to provide an interface to allowusers to know the status of locked and unlocked documents. Figure 12 shows you the view called “1. Main” , which is one of the views in the demon-stration database. This view displays the lock statusof documents. The first column of the view containsa red or green icon to indicate document lock statuses(red for locked, green for unlocked). In fact, userscan click on this status icon to trigger the document toattempt document locking or unlocking. Documentshighlighted in red (dark gray) are persistently locked; documents highlighted in yellow (light gray) are provisionally locked.

To create this view, I used two view features that are new in Notes/Domino 6: row custom color

formulas and the InViewEdit event of the LotusScriptNotesUIView class.

Row custom colors are an easy way to provideprogrammatic row highlighting in Notes client viewsbased on document data. To change the row colorswhen a document lock status changes, use row customcolor formulas, which are defined in view customcolor columns. Custom color columns are added toviews but hidden from users. When defined properly,these formulas adjust the color of all columns to theright of the defined color column in the view. Colorformulas, like other view column formulas, can bebased on document data.

I used the formula shown in Figure 13 in the 1. Main view to highlight the rows based on documentlock status. If a document is persistently locked, thenthe row is highlighted with a red background and haswhite text. If the document is provisionally locked,the row is highlighted with a yellow background andhas black text. If the document is not locked at all,then a white background with plain text, in this caseblack, is used.

The InViewEdit event of the NotesUIView classallows the documents in a view to be directly editedfrom within the confines of the view, without openingthe document in the UI. In fact, the InViewEdit eventcan actually expose editable fields resembling HTML

Figure 12 The “1. Main” View Displays Document Lock Status

Page 15: A Guide to Document Locking in Notes/Domino 6

Sub Inviewedit(Source As Notesuiview, Requesttype As Integer, Colprogname As Variant, Columnvalue AsVariant, Continue As Variant)

'This view has one editable column

REM Define constants for request typesConst QUERY_REQUEST = 1Const VALIDATE_REQUEST = 2Const SAVE_REQUEST = 3Const NEWENTRY_REQUEST = 4

REM Define variablesDim db As NotesDatabaseDim doc As NotesDocumentDim ws As New NotesUIWorkspaceDim caret As String

REM Get the CaretNoteID - exit if it does not point at a document

Figure 14 The “InViewEdit” Event Code

A Guide to Document Locking in Notes/Domino 6

No portion of this publication may be reproduced without written consent. 17

text inputs in the view columns. Then users can edit documents in much the same way spreadsheets are edited. Note: The InViewEdit feature is not supported on the Web.

Coding the InViewEdit event is not trivial, asthere can be only one InViewEdit event for the entireview. Columns that allow in-view editing must bedefined at design time. The InViewEdit event must bewritten so that every editable column can be triggeredby the click of the mouse.

(continues on next page)

For the icons in the first column of the 1.Mainview, I used the InViewEdit event to run code thattoggles the document locks of selected documents.When a user clicks on the red or green sphere icons,the InViewEdit event fires and calls the toggle lockcode in a LotusScript library. Figure 14 displays thecode in the InViewEdit event of the 1. Main view.This code uses the CaretNoteID property, which isnew in release 6, to get the note ID of the currentlyhighlighted document (the one at the caret location,which is changed by the user clicking the mouse or

red := 255:0:0;white := 255:255:255;yellow := 255:255:0;black := 1:1:1;plain:= 0:0:0;@If(@IsAvailable($Writers); red:white;@IsAvailable($PWriters) | @IsAvailable($PTWriters); yellow:black;white:plain)

Figure 13 The View Column Formula for Custom Row Colors

Page 16: A Guide to Document Locking in Notes/Domino 6

THE VIEW September/October 2004

18 www.eVIEW.com ©2004 THE VIEW. All rights reserved.

using the up and down arrow keys). With this note ID, we can retrieve a document using theNotesDatabase.GetDocumentByID method. Theretrieved document is then passed to the toggleLock()sub, which will attempt to lock or unlock the document.

The code that toggles the locks is in thelibDocumentLocking library of the demonstrationdatabase. You can see this code listed in Figure 15.The code uses the NotesDocument Lock() andUnLock() methods to toggle the document locks ofselected document objects, first checking to see if adocument is locked by looking at the NotesDocumentproperty, LockHolders. This property is an array ofall the users/groups that have the document locked.

If the LockHolders property is not empty, then the code assumes that the document is locked andcalls the Unlock method, which takes no arguments.

If the LockHolders property is empty, then thecode assumes that the document is unlocked andattempts to lock it by calling the Lock method.

This method offers programmers the option ofpassing a string array argument that could be used topopulate the LockHolders property and the $Writersor $PWriters items. Populating these items may beuseful to lock documents with multiple persons listedas lock holders. This means that anyone listed in thearray would be able to unlock or edit the document if

caret = Source.CaretNoteIDIf caret = "0" Then Exit Sub

REM Get the current database and documentSet db = Source.View.ParentSet doc = db.GetDocumentByID(caret)

REM Select the request typeSelect Case Requesttype

Case QUERY_REQUESTREM Reserved - do not use for release 6.0

Case VALIDATE_REQUESTREM Not used for icon columns

Case SAVE_REQUESTREM Toggle document locks

Call toggleLock(doc)

Case NEWENTRY_REQUEST

End SelectEnd Sub

Figure 14 (continued)

Page 17: A Guide to Document Locking in Notes/Domino 6

A Guide to Document Locking in Notes/Domino 6

No portion of this publication may be reproduced without written consent. 19

needed. I chose not to pass in the array since lockingthe document with a single lock holder is the mostreliable solution. The Lock() method simply defaultsto the current user executing the code.

The Boolean argument is also optional anddefaults to false. This argument controls whether ornot the Lock() method tries to apply a provisional lockshould the persistent lock operation fail to succeed. Iuse the false argument here, because I feel there is noneed to use a provisional lock since the persistentlock is the only safe lock to guard against data loss.

Document Locking Loophole

As you’ve seen, Domino locks documents by placingitems on the backend of the document note, whichmeans, of course, that there’s a way to edit the itemsdirectly without using the native methods providedwith the document locking API. A database user withManager or Author access and who is also a lock holdercan execute code to modify (or even remove or add)the $Writers and $WritersDate items of a document,thus effectively circumventing the entire document-locking process. In the (RemoveLockItems) agent ofthe demo database, I have provided a simple formulato remove document-locking items. Of course, performing such an operation results in the documentOID being changed and therefore requires a replicationto synchronize document instances between replicas.This procedure could ultimately result in replication/save conflicts and even lost data. It should be reserved

for instances when a document holder is not availableand there is an urgent need to unlock the document.

Document Locking on the WebUntil now, we have focused on document locking asit works in the Notes client environment. I have chosen to discuss how it works in Web environmentsseparately because while document locking workswell out-of-the-box in the Notes client, it does notwork as well for Web users.

In the Notes client, when a user tries to edit a lockeddocument that he or she has not locked, the Notesclient complains (i.e., sends an NRPC to the masterlock server saying that the document is locked andrequesting it to be unlocked). The stateless environmentof the Web does not provide NRPCs to the masterlock server when a user requests to edit a document.Moreover, the Web client does not have the function-ality needed to stop users from editing locked documentswithout added custom programming. If a Web user isunaware that a document is locked and he or she editsthat document, the edits are lost and the Web servercould throw an ambiguous HTTP 500 error.

Lotus is aware of this shortcoming and recommendsthat developers employ WebQueryOpen code to alertthe user that a document is locked before the usertries to edit it. For instance, you could create aWebQueryOpen LotusScript agent that checks for

Sub toggleLock(doc As NotesDocument)

If doc.LockHolders(0) = "" Then

Call doc.Lock(, False)

Else

Call doc.UnLock

End If

End Sub

Figure 15 The “toggleLock” Subroutine

Page 18: A Guide to Document Locking in Notes/Domino 6

Figure 16 illustrates a simple Web interface with check-in/checkout links to allow users to claimdocuments before they can edit them. This view listsdocuments, provides the links to check in or checkout documents, and by displaying lock holder infor-mation, indicates which documents are locked. Thelinks are created by adding formula language to computethe values for the columns in the “1. Main Web”view and passthru HTML that is calculated to provideeither a check-in or checkout link. The code for creatingthe links is listed in Figure 17.

The checkout link calls a LotusScript agent thatlocks documents, and the check-in link calls an agentthat unlocks document. Figure 18 shows the code for

THE VIEW September/October 2004

20 www.eVIEW.com ©2004 THE VIEW. All rights reserved.

Figure 16 A Web Check-In/Checkout Interface

locked status before the document is edited on theWeb. The agent could then set values on the HTMLform that indicate the document’s lock status. Youcould use JavaScript or VBScript to check these valuesand alert the Web user if the document is already locked.

Best Practice — A Check-In/Checkout Process

A best practice for Web document locking is toemploy a check-in/checkout process. By forcing Webusers to check out a document before they edit it, youcan keep users from editing documents that they havenot yet checked out or locked. This practice is goodfor the Notes client environment as well, as it avoidsthe risks associated with provisional locks.

Page 19: A Guide to Document Locking in Notes/Domino 6

A Guide to Document Locking in Notes/Domino 6

No portion of this publication may be reproduced without written consent. 21

Sub InitializeOn Error Goto ErrorHandler

Dim s As New NotesSessionDim db As NotesDatabaseDim view As NotesViewDim doc As NotesDocumentDim strUNID As String, strWebDbName As StringDim varRet As VariantDim nnn As NotesName

varRet = Evaluate("@WebDBName")strWebDbName = Cstr(varRet(0))

Set db = s.CurrentDatabaseSet doc = s.DocumentContextstrUNID = Left(GetQueryStringArgument(doc),32)

Set view = db.GetView("allbyunid")Set doc = view.GetDocumentByKey(strUNID,True)

Call doc.unlock

If doc.LockHolders(0) = "" ThenPrint |

<script>//alert("Check-in failed, you do not have permission to unlock the document.");

top.location = "/| & strWebDbName & |";

</script>

Figure 18 The “(WebCheckIn)” Agent

check_out_link := "[<a href=\"/" + @WebDbName + "/(WebCheckOut)?openagent&" +@Text(@DocumentUniqueID) + "&Login\">Check Out</a>]";

check_in_link := "[<a href=\"/" + @WebDbName + "/(WebCheckIn)?openagent&" +@Text(@DocumentUniqueID) + "&Login\">Check In</a>]";@If($Writers = ""; check_out_link; check_in_link)

Figure 17 Column Formulas for Creating Web Links

(continues on next page)

Page 20: A Guide to Document Locking in Notes/Domino 6

THE VIEW September/October 2004

22 www.eVIEW.com ©2004 THE VIEW. All rights reserved.

the (WebCheckIn) agent. The link for this agent forcesthe Web user to log in before the agent is executed,and the agent is set up to run as the Web user. Thisagent first tries to unlock the document. If this attemptfails, either because the user is not the explicit lockholder or because the user is not in a group that islisted as the lock holder, a JavaScript alert box notifiesthe user that he or she doesn’t have permission tounlock the document and presents the user with theidentity of the lock holder.

Lock DecayDocument locking raises the possibility of forgottenlocked documents. If a document is locked by an enduser and he or she neglects to act on it or unlock it ina timely manner, then other users continue to berestricted from editing the locked document and thedocument is considered to be stagnant. This situationcan lead to database managers receiving late-nightrequests to manually unlock stranded locked documents.

|

Else

End If

ExitGracefully:

Exit Sub

ErrorHandler:

If Error$ = "Notes error: The document is not locked by you" Then

Set nnn = New NotesName(doc.LockHolders(0))

Print |

<script>

alert("Check-in failed, The document is currently locked by | & nnn.Abbreviated & |. You do not have permis-sion to unlock the document.");

top.location = "/| & strWebDbName & |";

</script>

|

Else

Print "***Error: " & Str(Err) & " : " & Error$

End If

Resume ExitGracefully

End Sub

Figure 18 (continued)

Page 21: A Guide to Document Locking in Notes/Domino 6

A Guide to Document Locking in Notes/Domino 6

No portion of this publication may be reproduced without written consent. 23

Lock decay is the solution that can prevent thisscenario. Simply put, lock decay is the process thatunlocks documents after a certain amount of time has passed, when we can assume that they no longerneed to be locked or that they have been forgotten orabandoned by the original lock holder(s).

With the appropriate lock decay policy and implementation, you can avoid stalled documentworkflows in your business applications. Unfortunately,lock decay is not currently implemented in Notes/Domino 6. Once a document is manually or program-matically locked with a persistent lock, the documentcould remain locked indefinitely.

Since this much-needed functionality never madeit into the final product, developers and administratorsmust provide their own lock decay solution. I recom-mend incorporating the following principles into yoursolution:

• To avoid stagnant locks on documents, definebusiness practices for informing all users howlong a document can remain locked and not

actively edited before the lock on the document is decayed.

• Any lock decay functionality should be underpinnedby the $Writers and the $WritersDate items thatare used by the built-in Notes/Domino 6 documentlocking mechanism.

• It may also be worthwhile to monitor the last-modified property of the document to help determinewhen a document entered a stagnant state.

• The lock decay solution should notify the lockholder(s) of a document whose lock has decayed.

In the demonstration database that accompaniesthis article, I provide a lock decay solution thatdecays locked documents based on the $WritersDateitem and Last Modified property of the locked document.Use the Lock Decay Config form to create a lockdecay profile that can be used for all users or for certain roles listed in the ACL.

Figure 19 shows a Lock Decay Config document that pertains to the [Test] role of the

Figure 19 A “Lock Decay Config” Document

Page 22: A Guide to Document Locking in Notes/Domino 6

Then the LotusScript Lock Decay agent iteratesthrough all the locked documents in the vwUserLocksview and compares the value of the LockHoldersproperty to the ACL entries. If a lock holder is listedin the ACL explicitly, then the user’s roles are checkedagainst those roles listed in the Lock Decay Configdocuments (Figure 21 shows the code). This part ofthe agent processing also checks for the [NoDecay]role for the lock holder; if the lock holder has thisrole applied in the database ACL, then the processskips this locked document.

When the agent finds multiple Lock Decay Configdocuments that can be applied to a lock holder, thedocument with the highest weighted value takesprecedence over all others. If the lock holder does notbelong to roles that have associated Lock Decay Configdocuments, then the Lock Decay Config documentfor ALL users is applied (see Figure 22).

When a lock holder is not explicitly listed in thedatabase ACL, then the agent must determine how theACL is applied to the lock holder. To accomplishthis, the agent must search through groups in theDomino Directory (or NAB, for you old-timers) todetermine not only which group the lock holderresides in, but also how that group is entered in the

THE VIEW September/October 2004

24 www.eVIEW.com ©2004 THE VIEW. All rights reserved.

Setting Definition

$WritersDate Decay (#, Unit) Indicates the time that must pass after a document is locked before it can be decayed

Last Modified Decay (#, Unit) Indicates the time that must pass after a document is modified before the lockcan be decayed

Send Message Indicates (Yes or No) whether a message is to be sent to the lock holder(s)when the document lock is decayed

Message Text Contains the message that will be sent to the lock holder(s)

Include DocLink Includes a link to the decayed document in the e-mail message

Decay Users Indicates the users that this profile applies to

Roles Indicates what roles this profile should apply to (if roles have been selected)

Weight Indicates the weighted value for this document (used to determine the configurationdocument whose settings should be used when there are multiple Lock DecayConfig documents)

Figure 20 Settings in the “Lock Decay Config” Document

sample database. Figure 20 defines the settings inthis document.

Create a Lock Decay Config document for eachrole in the database ACL, being sure to assign aWeight value for each role. The Weight value will beused to determine the configuration document whosesettings should be used when there are multiple LockDecay Config documents that might apply to the user.Also create a document called “ALL” that has a verylow Weight value. The settings in the ALL documentwill apply when another, higher-weighted documentdoes not match a role that the user has.

The core of this lock decay solution is theLotusScript Lock Decay agent, which is set in thedownload database to be called manually from theActions menu, but which you will probably want toset up as a scheduled agent. This agent begins by initializing a custom logging routine to create an audittrail of when and why document locks were decayed.Next, the agent calls the processLocks subroutine,which generates a list of all of the Lock Decay Configdocuments and their weighted values, organized intoLotusScript lists. A list of NotesACLEntry elementsis also created by the processLocks subroutine to beused in later processing.

Page 23: A Guide to Document Locking in Notes/Domino 6

A Guide to Document Locking in Notes/Domino 6

No portion of this publication may be reproduced without written consent. 25

Do While Not (doc Is Nothing)strUser = doc.LockHolders(0)boolFlag = FalseForall entries In aclList

If Listtag(entries) = strUser ThenForall r In entries.Roles

If r = NO_DECAY ThenCall logger.logactivity("[NODECAY] document (" & doc.UniversalID & ") for " & strUser)Goto SkipDocument

End If

If Iselement(roleWeight(r)) ThenIf strRole = "" Then

strRole = rElse

If roleWeight(strRole) < roleWeight(r) ThenstrRole = r

End IfEnd IfboolFlag = True

End IfEnd Forall

End IfIf boolFlag Then

If checkDecay(docList(strRole), doc) ThendecayList(doc.UniversalID) = docList(strRole).universalidCall logger.logactivity("[DECAY] decaying document (" & doc.UniversalID & ") for " & strUser &

" using role " & strRole)End IfExit Forall

ElseIf checkDecay(docList("ALL"), doc) Then

decayList(doc.UniversalID) = docList("ALL").universalidCall logger.logactivity("[DECAY] decaying document (" & doc.UniversalID & ") for " & strUser &

". Using ""ALL"" settings for -Default- user")End If

End IfEnd Forall

Figure 21 Code to Check User Roles Against “Lock Decay Config” Documents

If checkDecay(docList("ALL"), doc) ThendecayList(doc.UniversalID) = docList("ALL").universalidCall logger.logactivity("[DECAY] decaying document (" & doc.UniversalID & ") for " & strUser &

". Using ""ALL"" settings for -Default- user")End If

Figure 22 Applying Lock Decay Settings for “ALL” Users

Page 24: A Guide to Document Locking in Notes/Domino 6

THE VIEW September/October 2004

26 www.eVIEW.com ©2004 THE VIEW. All rights reserved.

ACL. This could mean processing multiple nestedgroups, so I use the recursive function shown inFigure 23, which gets group membership informationfrom the ($ServerAccess) view in the DominoDirectory.

The getGroups() function processes all of thegroups that a lock holder belongs to and all of thegroups that those groups may be nested in, whiledrilling down through several layers of the nestedgroup hierarchy. It creates a list of all the associated/nested groups and returns that list to the calling function,which then compares each group to the ACL entriesand checks the group’s roles against the settings in theLock Decay Config documents.

The Lock Decay agent applies a Lock DecayConfig document to a lock holder by executing thecheckDecay() function, which simply adds a list element to the decayList, where the element is theUNID of the Lock Decay Config document and thelist tag is the UNID of the actual locked document.At this time, the agent also adds a log entry that

Function getGroups(strName As String) As BooleangetGroups = False

Dim groupdoc As NotesDocumentDim dc As NotesDocumentCollection

Set dc = vwAccess.GetAllDocumentsByKey(strName, True)If dc.Count > 0 Then

getGroups = TrueSet groupdoc = dc.GetFirstDocumentDo While Not (groupdoc Is Nothing)

strGroups(groupdoc.ListName(0)) = groupdoc.ListName(0)Call getGroups(groupdoc.ListName(0))Set groupdoc = dc.GetNextDocument(groupdoc)

LoopEnd If

End Function

Figure 23 The Recursive Function “getGroups( )”

indicates why the document lock is being decayedand what user, group, and lock decay settings havebeen used. Figure 24 shows a typical log document.

Later, the agent uses the decayList and calls thedocDecay() function for each locked document thatneeds to be decayed (see Figure 25).

Design Element LockingWith the ever-increasing likelihood that teams ofapplication developers may be working on the sameapplications across long distances and multipleservers, there is a need to manage conflicts amongdevelopers working on the same design elements.Design elements are simply Notes documents (notes)that represent database design components. Unlikedata notes, however, design notes do not create conflictdocuments. If a save or replication conflict occurswith a design note, the loser of the conflict loses his or her changes.

Page 25: A Guide to Document Locking in Notes/Domino 6

A Guide to Document Locking in Notes/Domino 6

No portion of this publication may be reproduced without written consent. 27

Figure 24 A Typical Log Document of Lock Decay Execution

…Forall unids In decayList

Call docDecay(unids, Listtag(unids))End Forall…Function docDecay(cfgUNID As String, lockUNID As String) As Boolean

docDecay = False

Dim strWho As StringDim cfgdoc As NotesDocument, lockdoc As NotesDocument

Set cfgdoc = vwUNID.GetDocumentByKey(cfgUNID,True)Set lockdoc = vwUNID.GetDocumentByKey(lockUNID,True)

strWho = lockdoc.LockHolders(0)

Call lockdoc.UnLock

docDecay = True

If cfgdoc.radMsg(0) = "1" ThenDim strMsg As StringDim memo As NotesDocumentDim rti As NotesRichTextItem

Figure 25 The “docDecay( )” Function

(continues on next page)

Page 26: A Guide to Document Locking in Notes/Domino 6

THE VIEW September/October 2004

28 www.eVIEW.com ©2004 THE VIEW. All rights reserved.

Notes/Domino 6 design element locking is abuilt-in tool that you can use on any database that will be developed by multiple developers. With someexceptions, the same back-end items are used to lockdesign elements that are used to lock Notes documents.Like document locking, design element locking requiresthat a master lock server be set in the database ACL.The second database-level requirement is that the“Allow design locking” property must be checked on the Design tab of the database properties.

Notes/Domino design locking has the same topology requirements and characteristics as document locking:

The defined master lock server must have a replica of the database.

The master lock server must be available forcommunication with any server or client that isattempting to use persistent locking.

Design locking also has the same characteristicsas document locking:

Persistent locks are the only safe locks.

Provisional locks can be promoted to persistentlocks.

NRPCs are used to communicate with the masterlock server to lock design notes.

Replication can be used to trigger lock promotionand synchronization.

Developers can lock or unlock design elementsmanually while the master server is available.

Despite the similarities between document lockingand design element locking, there are notable differences.If a persistent lock is applied to a design element, thenthe $Writers and the $WritersDate items are added tothe design note and a padlock icon is displayed in theleft margin of the design element list as an indicator(see Figure 26). Padlock icons are characteristicsonly seen with design element locking.

If the design element has a provisional lock applied,then the $PWriters item is added to the design note

strMsg = cfgdoc.txtMsg(0)Set memo = db.CreateDocumentmemo.SendTo = strWhomemo.Subject = "Your document has been decayed."Set rti = New NotesRichTextItem(memo, "Body" )

Call rti.AppendText(strMsg)Call rti.AddNewline(1, True)

If cfgdoc.radLink(0) = "1" ThenCall rti.AppendDocLink(lockdoc, "Previous Locked Document")

End If

Call memo.send (False)End If

End Function

Figure 25 (continued)

Page 27: A Guide to Document Locking in Notes/Domino 6

and a padlock with an arrow is used as the indicator icon.

I noticed another difference in how automaticdesign element locking works while testing this functionality in the Notes/Domino 6.5 client with a6.5 server. When a design note is opened in theDomino Designer client and the master lock server isavailable, the design element is automatically lockedand the correct items are written to the backend of thedesign note. When the design note is closed in theUI, the items disappear from the design note.However, when the master lock server is unavailableand a design element is opened in Domino Designer,the behavior is not congruent with the document lock-ing conventions we saw earlier.

First, you are presented with the modal dialogshown in Figure 27. Note that this dialog does not

A Guide to Document Locking in Notes/Domino 6

No portion of this publication may be reproduced without written consent. 29

Figure 26 Persistent and Provisional Locks on Design Elements

Figure 27 Dialog for Editing a Design Note When the Master Lock Server Is Unavailable

mention the use of provisional locks, but it doesmention that the master lock server is not available.

In this situation, I observed no back-end itemswritten to the design note, which means that a provisional lock is the only type available. I would not consider this option for editing designelements.

Another unique behavior of design locking is theone I observed when I tried to edit the Help Aboutand Help Using this Database documents found inthe Database resources. It appears that these designelements do not automatically lock when they areedited. They cannot be edited and saved, however,without first locking them manually. If I tried toedit the documents without first locking them, Icould not save my edits and I would be notified by a Notes pop-up that I had to first lock the document.

Page 28: A Guide to Document Locking in Notes/Domino 6

THE VIEW September/October 2004

30 www.eVIEW.com ©2004 THE VIEW. All rights reserved.

Figure 28 shows the message I received when Itried to save the document. Figure 29 shows themessage I received when I tried to save the documentin response to the prompt during the QueryCloseevent of the document.

Design Locking and WebDAV

One of the key uses for design locking is apparentwhen we consider WebDAV, Web-based DistributedAuthoring and Versioning. WebDAV is an IETF(Internet Engineering Task Force) standard, “a set ofextensions to the HTTP protocol, which allows usersto collaboratively edit and manage files on remoteWeb servers” (www.webdav.org).

With WebDAV, non-Domino developers can editDomino design elements (File, CSS, and Imageresources) from outside the Domino database andserver, without the Domino Designer client.

In fact, using mainstream Web tools such asMacromedia’s Dreamweaver MX, Web developerscan actually check out design elements and lock themin the Domino database while they edit them. Design locking is a requirement for WebDAV operations.

Mixed R5 and Notes/Domino 6EnvironmentsAccording to Lotus, there are several things to beaware of if your environment includes older versionsof Notes/Domino and you are using Notes/Domino 6document locking. Figure 30 lists these concerns, asoutlined in Notes documentation.3

Best Practices In this section, I gather up the recommendations andbest practices for document locking that were provided

3 See http://www-1.ibm.com/support/docview.wss?rs=0&q=7003259&uid=swg27003259

Figure 28 The Developer Must Lock Help Documents Before Editing and Saving Them

Figure 29 The Developer Cannot Save This Help Document Without First Locking It

Scenario Outcome

R5 client trying to edit a lockeddocument

Client generates an error message on save: Cannot save edits.

Notes/Domino 6client trying to edit a documenton an R5 server

The following error messagedisplays: Server does not support this version of the network protocol.

Note: Your Notes/Domino 6client will have the menu optionto Lock/Unlock, but the serveris not able to support that call.

Figure 30 Document Locking Concerns in a Mixed Environment

Page 29: A Guide to Document Locking in Notes/Domino 6

A Guide to Document Locking in Notes/Domino 6

No portion of this publication may be reproduced without written consent. 31

throughout the article, together with a few new ones,and present them in one easy-to-reference list.

Avoid provisional or provisional-temporarylocking.

- Where possible, employ application designtechniques to help provide check-in/checkoutfunctionality as an alternative to provisionaldocument locks.

- Educate users about the dangers of provisionallocks.

- For users with a remote replica and dial-up orVPN connection that is not always connectedto the master lock server, suggest that they tryto connect to the Domino server and initiatean NRPC (through replication or some othermeans) to try to lock a document before theymake edits to it.

Grant Editor access and above to as few usersas possible, restricting general users of thedatabase to Author. This practice is almostalways a good idea, regardless of whether or notdocument locking is enabled. By keeping thenumber of potential editors to a minimum, youreduce the chances of multiple editors attemptingto edit a document simultaneously.

Design views and forms that make the useraware of document-locking status.

Consider using custom lock decay functionality.Even though it’s not intrinsically part of documentlocking, lock decay should be considered a necessityfor any application manager or administrator whodoes not want to have stagnant locked documentsand calls from frustrated users in the small hoursof the morning.

Plan your database locking strategy aroundsound server availability and replication setup.If the master lock server cannot be reached, per-sistent locks cannot be created and editing will beunreliable.

Make sure that the defined master lock serverhas a replica of the database. If there is noreplica on the master lock server, only provisional

locks will be created and users will never be ableto unlock documents regardless of whether themaster lock server is available to the client.

Provide check-in and checkout for Web users.In certain circumstances (e.g., remote users), provide this functionality for Notes client users as well.

Keep users informed.

- Let users know the status of documentsthrough UI components such as views andcomputed text.

- Users should understand that if they edit documents under a provisional or provisional-temporary lock, their changes will not be preserved if someone else has the documentpersistently locked.

- Users should also should know that the e-mail message they receive from Notes when provisional locks are not promoted issomewhat unreliable and could cause them to lose their edits.

Inform users with Manager access to exercisecaution. If they use their authority to unlock adatabase document and edit it, they could cause aconflict condition.

Notes/Domino 6 DocumentLocking and Design Locking in a NutshellDocument locking comes built-in with LotusNotes/Domino version 6.0 and above. Out-of-the-boxfunctionality requires no additional development andprovides a clean solution for record locking in a LotusNotes client environment — provided that the masterlock server is readily available for replication andNRPC communication with clients and other servers.To use document or design locking, the master lockserver must have a replica of the database.

Lotus provides programmability of documentlocking using the Notes formula and LotusScript

Page 30: A Guide to Document Locking in Notes/Domino 6

THE VIEW September/October 2004

32 www.eVIEW.com ©2004 THE VIEW. All rights reserved.

languages in release 6.0 and, as of Notes/Domino 6.5,the Java API, which is great because effective documentlocking for Web users requires custom solutions.

Design locking is document locking for designnotes and works much the same way as documentlocking with a few minor exceptions. Design lockingis a requirement if applications will be accessed viaWebDAV clients.

To implement many of the best practices and recommendations made in this article, I invite you to use the solutions provided in the database atwww.eVIEW.com.

James Ray has been working with Notes sincerelease 3.3. He specializes in enterprise integrationwith Oracle and SAP, Web development, andNotes/Domino 6 migrations. He is a PrincipalCertified Lotus Professional (IBM CertifiedAdvanced) System Administrator and ApplicationDeveloper for Notes and Domino releases 4, 5,and 6. James is also an IBM Certified AssociateSystem Administrator for Lotus QuickPlace 3, aswell as a Microsoft Certified Systems Engineer(MCSE). In addition, he has worked with Lotuseducation in developing exam content, includingthe Notes and Domino 6 update exams foradministration and application development, aswell as the administration exam for the Domino 6server. James has written for several professionalpublications and has been a speaker at multipleconferences for THE VIEW. You can contact himat [email protected].