Saturday, November 1, 2003

A Fix for folders and documents

THIS WEEK'S POWERTIP

By Mick Moignard

Oh, the perils of putting code in DominoPower articles! People might just try to run the stuff, and then find that it doesn't work.

No sooner had my piece on Folders and Lost Documents appeared on DominoPower (at http://www.DominoPower.com/issues/issue200310/00001122001.html), than I had an email from Peter Reilly who said:

I've pasted the [agent code] into an Agent. The agent is set to run on selected documents. From the All Documents View, I select 6 documents, and then run the agent from the Actions menu. I get the following error: "Document was deleted from this collection". Could you point me to what I might be doing wrong?

The short answer to Peter was nothing. The problem was in my code, not in what he'd done. I'd written it some years back to solve a particular problem, and must never have run into the error. So when I dragged the code out for the article, I just assumed it would work. Dumb, huh?

Here's the fragment of the code that illustrates the problem:

While Not(doc Is Nothing)
        If doc.folderreferences(0) <> "" Then
                Call doccoll.deletedocument(doc)
        End If
        Set doc = doccoll.GetNextDocument(doc)
Wend

The 'Document was deleted' message is issued when the GetNextDocument call is made. The GetNextDocument all gets the next document using the argument NotesDocument as a placeholder. So when the code removes a document from the collection, the GetNextDocument fails because the document passed in the argument isn't in the collection, so GetNextDocument has no idea where it is.

There are two solutions to this problem. Here's the first one -- and yes, I have tested this one!

01 Sub Initialize
02      Dim sess As New notessession
03      Dim db As notesdatabase
04      Set db = sess.currentdatabase
05      db.FolderReferencesEnabled = True
06      Dim doccoll As NotesDocumentCollection
07      Dim tempdoc As notesdocument
08      Set doccoll = db.AllDocuments
09
10      Set doc = doccoll.GetFirstDocument
11
12      While Not(doc Is Nothing)
13              If doc.folderreferences(0) <> "" Then 'doc is in at least one folder...
14                      Set tempdoc = doc
15                      Set doc = doccoll.GetNextDocument(doc)
16                      Call doccoll.deletedocument(tempdoc) 'pull it from the collection
17              Else
18                      Set doc = doccoll.GetNextDocument(doc)
19              End If
20      Wend
21      Call doccoll.PutAllInFolder("(Inbox)") 'all those that remain in the collection
22 End Sub

You can see that in Line 8 I have Dim'd another NotesDocument object. When I need to remove a document from the collection, I first make a copy of the reference to it to my spare NotesDocument -- that happens in line 14. Then in line 15 I can get the next document, because the current 'doc' is still in the folder. Line 16, I remove the saved document from the folder.