LotusScript getting data from a view - lotus-notes

I am new to lotus script, and I'm trying to get data from a view and save it into a string. But each time I do that I get the error that Initialize Object variable not set on line 36. In my domino designer Line 36 is right under ItemNames(6).
I tried to use the code from my friend and I get the same error, while his works without a problem.
Please help I'm desperate to make this work.
Sub Initialize
On Error GoTo ERRSUB
Dim nSession As New NotesSession
Dim nDb As NotesDatabase
Dim nDoc As NotesDocument
Dim view As NotesView
Dim nitem As NotesItem
Dim strRecord As String
Dim DataString As String
Dim nList List As String
Dim ListCount As Integer
Dim FirstLine As String
Dim counter As Integer
counter = 0
Dim ItemNames(6) As String
ItemNames(0) = "Date"
ItemNames(1) = "Name"
ItemNames(2) = "Name of buyer"
ItemNames(3) = "Naziv of project"
ItemNames(4) = "value"
ItemNames(5) = "source"
ItemNames(6) = "status"
Set nDb = nSession.Currentdatabase
Set view = nDb.Getview("X_view_1")
Set ndoc = view.Getfirstdocument()
Do Until (ndoc Is nothing)
ForAll item In ItemNames
Set nitem = ndoc.Getfirstitem(item)
DataString = nitem.Values & ";"
counter = counter + 1
End ForAll
DataString = DataString & Chr(13)
Set ndoc = view.Getnextdocument(ndoc)
Loop
GoTo DONE
DONE:
MessageBox counter
Exit Sub
ERRSUB:
Call logger("Error",nSession.currentagent.name,"Initialize","","")
GoTo done
End Sub

Line 36 is DataString = nitem.Values & ";". The error is that nitem is not set properly. Probably the item is not available in a certain document. Test for nitem isn't Nothing.
Change your ForAll loop to
ForAll item In ItemNames
Set nitem = ndoc.Getfirstitem(item)
If Not nitem Is Nothing then
DataString = DataString & nitem.Text
End If
DataString = DataString & ";"
counter = counter + 1
End ForAll

I would writ it something like this below.
Among the things I notice in your code:
* You use GoTo in your error handler, should be a Resume instead.
* You have "GoTo DONE" when the code would get there anyway, that is not needed.
* You have several variables declared that you don't use.
* You don't use much error checking, Knut's suggestion is a good one.
Here is my suggestion, this is how I would export a view:
Sub Initialize
Dim session As New NotesSession
Dim db As NotesDatabase
Dim view As NotesView
Dim col As NotesViewEntryCollection
Dim entry As NotesViewEntry
Dim DataString As String
Dim cnt List As Long
On Error GoTo errHandler
Set db = session.Currentdatabase
Set view = db.Getview("X_view_1")
Set col = view.AllEntries
'*** Set counters
cnt("total") = col.Count
cnt("processed") = 0
'*** Loop though all view entries, much faster that documents
Set entry = col.GetFirstEntry()
Do Until entry Is Nothing
'*** Update status bar every 100 documents
If cnt("processed") Mod 100 = 0 Then
Print "Processed " & cnt("processed") & " of " & cnt("total") & " documents."
End If
'*** Read view columns and add to string
ForAll cv In entry.ColumnValues
DataString = cv & ";"
End ForAll
'*** Add line break to string
DataString = DataString & Chr(13)
'*** Update counter and get next entry in view collection
cnt("processed") = cnt("processed") + 1
Set entry = col.GetNextEntry(entry)
Loop
exitSub:
MsgBox "Processed " & cnt("processed") & " of " & cnt("total") & " documents.",,"Finished"
Exit Sub
errHandler:
Call logger("Error",session.CurrentAgent.Name,"Initialize","","")
Resume exitSub
End Sub
Another way to do it would be to read the the value directly from the NotesDocument:
DataString = doc.GetItemValue(item)(0) & ";"
Of course, this will only read the first value of any multi-value fields, but you can fix that like this:
DataString = Join(doc.GetItemValue(item),"~") & ";"
This will put a ~ between each value if there are more than one, then you can process that the way you like.

Related

NotesReplicationEntry - Lotus Notes

I am trying to set Selective Replication using LotusScript but I cannot get it to save. The log shows no errors and the script completes without error. The replica gets created but not with my Selective Replication set.
%REM
Agent createRenewalDB
Created Dec 14, 2016 by
Description: Comments for Agent
%END REM
Option Public
Use "xxx Routines"
Sub Initialize
Dim db As NotesDatabase
Dim doc As NotesDocument
Dim s As New NotesSession
Dim flag As Boolean
Dim renDb As NotesDatabase
Dim renFP As String
Dim renHubDb As NotesDatabase
Dim sQuote As String
Dim nowt As String
Dim pos As Long
Dim client As String
Dim frm As String
Dim L As Long
Dim P1 As String
Dim P2 As String
Dim item As NotesItem
Dim renYN As String
Dim agent As NotesAgent
Set agent = s.CurrentAgent
Print("createRenewalDB starting")
Set db = s.Currentdatabase
Set doc = db.GetDocumentByID(agent.ParameterDocID)
'Print("got doc")
client = doc.getItemValue("Client")(0)
nowt = ""
sQuote = """"
pos = 1
Dim tmp1 As String
'Print("set vars")
tmp1 = doc.getItemValue("SearchFormula")(0)
'Print("got search formula")
frm = StrLeft(StrRight(tmp1,"ix_client;"),")")
'### strip out quotation marks
Do Until pos = 0
L = Len(frm)
pos& = InStr(1,frm,sQuote)
If pos <> 0 Then
P1 = Left(frm,pos - 1) ' Part 1 of the text string
P2 = Right(frm,L- pos )
frm = P1 & nowt & P2
End If
Loop
'Print("stripped out the rubbish")
'#### Setup a new Renewals document if none exixts and Renewals has been selected
Set item = doc.getfirstitem("EnabledApps")
renYN = item.text
If InStr(renYN, "32") > 0 Then
'##### Get the Renewals Quotes Db
Set renHubDb = Get_Specific_Db_Object("Renewal Quotes", "xxx-01")
If renHubDb Is Nothing Then
MsgBox("Fail: Could not get the Renewals Quotes database on Hub, exiting renewals created.")
Exit Sub
End If
renFP = doc.getItemvalue("Renewals")(0)
'Msgbox("Renewals to be set up " + renFP)
Set renDb = s.GetDatabase("",renFP,False)
If renDb Is Nothing Then '#### No replica, so create one
Print("Creating a replica for " + client)
Set renDb = renHubDb.CreateReplica("xxx-01",renFP)
renDb.Title = client
Dim rep As NotesReplication
Dim re As NotesReplicationEntry
Dim server As String
server = "xxx-xxx-01"
Set rep = renDb.ReplicationInfo '## Get the replication info
Set re = rep.GetEntry("-",server,True) '## get the replication entry - true creates it
re.Formula = "SELECT #Contains(client;" &"""" & frm & """" & ")" '## add the selective replication
Print("selective replication formula " + re.Formula)
'## save both
Call re.Save
Call rep.Save()
Print(re.Formula) '## formula is still set correctly at this point
End If
If renDb Is Nothing Then
MsgBox("Could not create a replicate for " + client)
Exit Sub
End If
Else
MsgBox("No Renewals " + renYN)
End If
Print("###########################################Finished creating the replica - agent")
End Sub
Any thoughts?
Lotus Notes 9.0.1
Lotus Domino 9.0.1
Code is in an agent that has Full Admin Access Set on the Security Tab.
Thanks
Graeme

Not able to get out of the loop after getfirstitem in lotus script

Sub Initialize
On Error GoTo ErrorOut
Dim sess As NotesSession
Dim db As NotesDatabase
Dim doc, searchDoc, reqNumDoc As NotesDocument
Dim body As NotesMIMEEntity
Dim header As NotesMIMEHeader
Dim stream As NotesStream
Dim vwSearchRequests As NotesView
Dim reqNum, totalNotify, totalAccepted, totalRejected, totalOOO, totalNoRes As Integer
Dim reqSer, reqJRSS, reqSPOC, reqNumStr As String
Dim reqDate As String
Dim reqNumColl As NotesDocumentCollection
Dim reqPanelRes As NotesItem
Dim reqPanelResValue As Variant
Set sess = New NotesSession
Set db = sess.CurrentDatabase
Set vwSearchRequests = db.GetView("RequestDocReport")
vwSearchRequests.Autoupdate = False
Set searchDoc = vwSearchRequests.GetFirstDocument
While Not searchDoc Is Nothing
reqSer = "Service"
reqJRSS = searchDoc.PS_JRSS(0)
reqSPOC = "Hiring SPOC"
totalAccepted = 0
totalRejected = 0
totalOOO = 0
totalNoRes = 0
totalNotify = 0
reqNum = searchDoc.PS_RequestNo(0)
reqNumStr = {PS_RequestNo = "} & reqNum & {"}
Set reqNumColl = vwSearchRequests.GetAllDocumentsByKey(reqNumStr)
Set reqNumDoc = reqNumColl.GetFirstDocument
While Not reqNumColl Is Nothing
If Not reqNumDoc.GetFirstItem("PanelResponse") Is Nothing Then
reqPanelResValue = reqNumDoc.GetItemValue("PanelResponse")
MsgBox CStr(reqPanelResValue(0))
'Exit Sub
If CStr(reqPanelResValue(0)) = "Accepted" Then
totalAccepted = totalAccepted + 1
End If
If CStr(reqPanelResValue(0)) = "Rejected" Then
totalRejected = totalRejected + 1
End If
If CStr(reqPanelResValue(0)) = "OOO" Then
totalOOO = totalOOO + 1
End If
Else
If CStr(reqPanelResValue(0)) = "" Then
totalNoRes = totalNoRes + 1
End If
End If
totalNotify = totalNotify + 1
Set reqNumDoc = reqNumColl.GetNextDocument(reqNumDoc)
Wend
what is the error in code? The code is getting stuck after
If Not reqNumDoc.GetFirstItem("PanelResponse") Is Nothing Then
reqPanelResValue = reqNumDoc.GetItemValue("PanelResponse")
Instead of line
While Not reqNumColl Is Nothing
write
While Not reqNumDoc Is Nothing
You got an infinitive loop because the collection reqNumColl is not nothing all the time even when you reached the last document in collection. Instead you have to test the document reqNumDoc.
Another issue might be your code for collection calculation:
reqNumStr = {PS_RequestNo = "} & reqNum & {"}
Set reqNumColl = vwSearchRequests.GetAllDocumentsByKey(reqNumStr)
The way you coded it the first sorted column in view should contain
PS_RequestNo = "12345"
Probably, your view contains in first sorted column just the request number. If so, your code would be just:
Set reqNumColl = vwSearchRequests.GetAllDocumentsByKey(reqNum)
if column contains a numeric value or
Set reqNumColl = vwSearchRequests.GetAllDocumentsByKey(cStr(reqNum))
if it contains a string.
Apart from any other problems you might have in your code (and #Knut is correct about the cause of your infinite loop), this is not a good pattern:
If Not reqNumDoc.GetFirstItem("PanelResponse") Is Nothing Then
reqPanelResValue = reqNumDoc.GetItemValue("PanelResponse")
You're retrieving the item twice when you don't actually have to.
This woould be much better:
If reqNumDoc.HasItem"PanelResponse") Then
reqPanelResValue = reqNumDoc.GetItemValue("PanelResponse")

LotusScript cannot get file attachment from email

I had never run into this problem, but I cannot get a handle on a file attachment on an email. I have code that can either search the document for Embedded Objects or search a field for Embedded Objects -- neither of them are returning the file. I can see the file on the email and I can see the $FILE field which contains the file attachment.
Here is the code:
Function FileDetachFiles(doc As NotesDocument, fieldName As String, getFromField As Integer) As Variant
On Error Goto ProcessError
Dim s As NotesSession
Dim db As NotesDatabase
Dim rtItem As NotesRichTextItem
Dim fileToExtract As String
Dim fileName As String
Dim fileArray() As String
Dim message As String
Dim embedObjects As Variant
Dim attachFile As Integer
Dim x As Integer
Set s = New NotesSession
Set db = s.CurrentDatabase
Const fileImport = "C:\"
attachFile = False
'Let's see if there are attached files...
If getFromField = True Then
'Locate field and get files...
If doc.HasEmbedded Then
If doc.HasItem(fieldName) Then
'Set the first field...
Set rtItem = doc.GetFirstItem(fieldName)
embedObjects = rtItem.EmbeddedObjects
If Isarray(embedObjects) Then
Forall Files In rtItem.EmbeddedObjects
If Files.Type = EMBED_ATTACHMENT Then
fileName = Files.Source
fileToExtract = fileImport & fileName
Redim Preserve fileArray(x)
fileArray(x) = fileToExtract
x = x + 1
Call Files.ExtractFile(fileToExtract)
attachFile = True
End If
End Forall
End If
End If
End If
Else
x = 0
'Go through doc looking for all embedded objects...
If doc.HasEmbedded Then
Forall o In doc.EmbeddedObjects
If o.Type = EMBED_ATTACHMENT Then
fileName = o.Name
fileToExtract = fileImport & fileName
Call o.ExtractFile(fileToExtract)
Redim Preserve fileArray(x)
fileArray(x) = fileToExtract
x = x + 1
attachFile = True
End If
End Forall
End If
End If
If attachFile = True Then
FileDetachFiles = fileArray
End If
Exit Function
ProcessError:
message = "Error (" & Cstr(Err) & "): " & Error$ & " on line " & Cstr(Erl) & " in GlobalUtilities: " & Lsi_info(2) & "."
Messagebox message, 16, "Error In Processing..."
Exit Function
End Function
I tried both routines above -- passing the $FILE and Body field names, as well as searching the document. It does not find any file attachments.
I even tried this:
Extracting attachments as MIME using LotusScript
Which did not find any MIME on the document.
I have never run into this problems -- any ideas would be great.
Thanks!
I had that before, but unfortunately do not remember, where it comes from, it might have to do something with V2- Style Attachments coming from Domino Websites...
Try Evaluate( #AttachmentNames ) to get a Variant containing the names of all attachments. Then loop through this with a Forall- loop and try the NotesDocument.getAttachment( strLoopValue ) - Function to get a handle to the attachment.
For further info read here and follow the links on that page, especially this one
Code would be something like this:
Dim doc as NotesDocument
Dim varAttachmentNamens as Variant
Dim object as NotesEmbeddedObject
REM "Get the document here"
varAttachmentNames = Evaluate( "#AttachmentNames" , doc )
Forall strAttachmentName in varAttachmentNames
Set object = doc.GetAttachment( strAttachmentName )
REM "Do whatever you want..."
End Forall

Sequence number of documents saved

I use the below script in querysave event of a form. The logic is when I save the form the sequence should get displayed in the view in two columns. like "115-" in one column and the sequence "00001", "00002", ... in the second column. The first two documents gets saved without any issue. When I save try to save 3rd and more documents, its displaying "00002" only every time after that. I am not able to identify what is the mistake. Can somebody help please.
Sub Querysave(Source As Notesuidocument, Continue As Variant)
Dim SESS As New NotesSession
Dim w As New NotesUIWorkspace
Dim uidoc As NotesUIdocument
Dim Doc As NotesDocument
Dim RefView As NotesView
Dim DB As NotesDatabase
Dim RefDoc As NotesDocument
Set DB = SESS.CurrentDatabase
Set uidoc = w.CurrentDocument
Set Doc = uidoc.Document
Set RefView = DB.GetView("System\AutoNo")
Dim approvedcnt As Integer
approvedcnt = Cint(source.fieldgettext("appcnt"))
If uidoc.EditMode = True Then
Financial_Year = Clng(Right$(Cstr(Year(Now)),3)) + 104
If Month(Now) >= 4 Then Financial_Year = Financial_Year + 1
DocKey = Cstr(Financial_Year)& "-"
New_No = 0
Set RefDoc = RefView.GetDocumentByKey(DocKey , True)
If Not(RefDoc Is Nothing) Then New_No = Clng(Right$(RefDoc.SETTLEMENT_NO(0),5))
New_No = New_No + 1
autono = DocKey & "-" & Right$("00000" & Cstr(New_No) ,5)
Application ="ST"
Latest_No = Application + autono
Doc.SETTLEMENT_NO = Latest_No
Doc.FinFlag="Finish"
Call SESS.SetEnvironmentVar("ENV_ST_NO",Right$("00000" & Cstr(DefNo&) ,5))
'Call uidoc.FieldSetText("SETTLEMENT_NO",Latest_No)
Call uidoc.Refresh
Else
Exit Sub
End If
get_ex_rate
get_cv_local
Call uidoc.FieldSetText("Flag1", "A")
If approvedcnt = 12 And uidoc.FieldGetText("STATUS") = "APPROVE" Then
Call uidoc.fieldsettext("Flag2", "B")
End If
Dim answer2 As Integer
answer2% = Msgbox("Do you want to save this document?", 1, "Save")
If answer2 = 1 Then
Print "Saving"
End If
If answer2 = 2 Then
continue=False
Exit Sub
End If
uidoc.Refresh
uidoc.close
End Sub
I imagine your call to GetDocumentByKey is getting the wrong document or not the next one in sequence. Make sure the view is sorted properly and perhaps call the refresh method on the view before calling GetDocumentByKey.

Lotus Notes Agent - Remove Embedded Images?

I have an agent someone shared years ago which takes attached files, saves them to my hard drive, and removes them from the email. I use it to keep my emails for a while but stay under my corporate mailbox quota. I get a LOT of attachments.
I'm now finding that a lot of the remaining large emails have embedded images rather than "attached files". Can anyone share a script that would actually be able to do the same (save to hard drive, remove from email) with an embedded image?
FWIW, here is the agent I use for detaching attachments. Props to original author, don't know who that was.
Dim sDir As String
Dim s As NotesSession
Dim w As NotesUIWorkspace
Dim db As NotesDatabase
Dim dc As NotesDocumentCollection
Dim doc As NotesDocument
Sub Initialize
Set s = New NotesSession
Set w = New NotesUIWorkspace
Set db = s.CurrentDatabase
Set dc = db.UnprocessedDocuments
Set doc = dc.GetFirstDocument
Dim rtItem As NotesRichTextItem
Dim RTNames List As String
Dim DOCNames List As String
Dim itemCount As Integer
Dim sDefaultFolder As String
Dim vtDir As Variant
Dim iCount As Integer
Dim j As Integer
Dim lngExportedCount As Long
Dim attachmentObject As Variant
Dim text As String
Dim subjectLine As String
Dim attachmentMoved As Boolean
' Prompt the user to ensure they wish to continue extracting the attachments
Dim x As Integer
x = Msgbox("V4 This action will extract all attachments from the " & Cstr (dc.Count) & " document(s) you have selected, and place them into the folder of your choice." & _
Chr(10) & Chr(10) & "Would you like to continue?", 32 + 4, "Export Attachments")
If x <> 6 Then Exit Sub
' Set the folder where the attachments will be exported
sDefaultFolder = s.GetEnvironmentString("LPP_ExportAttachments_DefaultFolder")
If sDefaultFolder = "" Then sDefaultFolder = "F:"
vtDir = w.SaveFileDialog( False, "Export attachments to which folder?", "All files|*.*", sDefaultFolder, "Choose Folder and Click Save")
If Isempty(vtDir) Then Exit Sub
sDir = Strleftback(vtDir(0), "\")
Call s.SetEnvironmentVar("LPP_ExportAttachments_DefaultFolder", sDir)
' Loop through all the selected documents
While Not (doc Is Nothing)
iCount = 0
itemCount = 0
lngExportedCount = 0
Erase RTNames
Erase DocNames
' Find all of the RichText fields in the current document. If any have an embedded object, add the item to the RTNames array.
Forall i In doc.Items
If i.Type = RICHTEXT Then
If Not Isempty(i.EmbeddedObjects) Then
'Msgbox i.Name,64,"Has embedded objects"
End If
Set rtItem = doc.GetfirstItem(i.Name)
'Set rtItem = i
If Not Isempty(rtItem.EmbeddedObjects) Then
RTNames(itemCount) = Cstr(i.Name)
itemCount = itemCount +1
End If
End If
End Forall
' Loop through the RTNames array and see if any of the embedded objects are attachments
attachmentMoved = False
For j = 0 To itemCount-1
Set rtItem = Nothing
Set rtItem = doc.GetfirstItem(RTNames(j))
Forall Obj In rtItem.EmbeddedObjects
If ( Obj.Type = EMBED_ATTACHMENT ) Then
' The embedded object is an attachment. Export it to the chosen directory
Call ExportAttachment(Obj)
' Append to the bottom of the file details on the extracted file and its new location.
Call rtItem.AddNewline(1)
Call rtitem.AppendText("---------------------------------------" + Chr(13) + Chr(10))
text = """" + sDir + "\"+ Obj.Name + """" + Chr(13) + Chr(10) + Chr(9) + "Extracted by: " + s.UserName + " on " + Str$(Today()) + ". "
Call rtitem.AppendText(text )
Call rtItem.AddNewline(1)
' Remove the object from the file and save the document.
Call Obj.Remove
Call doc.Save( False, True ) 'creates conflict doc if conflict exists
attachmentMoved = True
Else
Forall verb In Obj.Verbs
'Msgbox verb, 64, "VERB"
End Forall
End If
End Forall
' If the document had an attachment moved, update the subject line
If attachmentMoved = True Then
Dim item As Notesitem
Set item = doc.GetFirstItem("Subject")
subjectLine = item.Text + "- ATTACHMENT MOVED"
Set item = doc.ReplaceItemValue("Subject", subjectLine)
Call doc.Save( False, True ) 'creates conflict doc if conflict exists
End If
Next
Set doc = dc.GetNextDocument(doc)
Wend
Msgbox "Export Complete.", 64, "Finished"
End Sub
Sub ExportAttachment(o As Variant)
Dim sAttachmentName As String
Dim sNum As String
Dim sTemp As String
' Create the destination filename
sAttachmentName = sDir & "\" & o.Source
' Loop through until the filename is unique
While Not (Dir$(sAttachmentName, 0) = "")
' Get the last three characters of the filename - "_XX"
sNum = Right(Strleftback(sAttachmentName, "."), 3)
' Ensure the first of the three characters is an underscore and the next two are numeric. If they are, add one to the existing number and insert it back in.
If Left(sNum,1) = "_" And Isnumeric(Right(sNum, 2)) Then
sTemp = Strleftback(sAttachmentName, ".")
sTemp = Left(sTemp, Len(sTemp) - 2)
sAttachmentName = sTemp & Format$(Cint(Right(sNum,2)) + 1, "##00") & "." & Strrightback(sAttachmentName, ".")
Else
sAttachmentName = Strleftback(sAttachmentName, ".") & "_01." & Strrightback(sAttachmentName, ".")
End If
Wend
' Save the file
Call o.ExtractFile( sAttachmentName )
End Sub
This is very problematic to do with the script as it currently stands as MIME encoded images won't show up as any type of attachment using the EmbeddedObjects Property.
If the images are stored inline as part of a MIME message, the Notes client will turn them into an attachment for viewing, but programmatically the can only be accessed as parts of the MIME message. It should be achievable to grab the correct part of a multi-part MIME message with the image encoded (using the MIMEEntity classes), stream this out to disc and reconstitute the original file(s) then remove the MIMEEntity that represented it (and took up the space).
More info on the
IBM Support Site
NotesMIMEEntity Class Documentation

Resources