NotesReplicationEntry - Lotus Notes - 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

Related

OPC DA Client - Unable to assign item.Value to VBA variable

Below is an OPC Client written in VBA. It is using the OPC Foundation DA libraries. I am able to get the current value of the item (I can read it in locals window), but it is not assigning the value to myValue = theItem.Value Hovering over theItem.Value during a break shows the value as well.
Any thoughts?
Public Sub ReadValue()
Dim serverNames As Variant
Dim listServers As Variant
Dim i As Integer
Dim theStates As Variant
Set theServer = New OPCServer
serverNames = theServer.GetOPCServers
theStates = Array("Disconnected", "Running", "Failed", "No Configuration", "Suspended", "In Test")
For i = LBound(serverNames) To UBound(serverNames)
Debug.Print (serverNames(i))
Next i
theServer.Connect ("MyOPCServer")
Debug.Print theServer.VendorInfo
Debug.Print theServer.MajorVersion & "." & theServer.MinorVersion
Debug.Print theStates(theServer.ServerState)
Debug.Print theServer.StartTime
Debug.Print theServer.CurrentTime
Debug.Print theServer.LastUpdateTime
'Groups
Dim theGroup As OPCGroup
Dim theGroups As OPCGroups
If theGroups Is Nothing Then
Set theGroups = theServer.OPCGroups
End If
If theGroup Is Nothing Then
Set theGroup = theGroups.Add("testing")
txtName = theGroup.name
End If
theGroup.UpdateRate = CLng(1000)
theGroup.DeadBand = CLng(1)
theGroup.TimeBias = CLng(0)
theGroup.IsActive = CBool(1)
theGroup.IsSubscribed = CBool(1)
'
Dim theItem As OPCItem
Dim theItem1 As OPCItem
Dim myItems As Variant
Dim myValue As Variant
Dim myWriteValues As Variant
Dim handles(1) As Long
Dim Errors() As Long
Dim CancelID As Long
Dim TransID As Long
myItems = Array("MyPathBlahBlahBlah.CV")
myWriteValues = Array(8, 0, 1)
For i = LBound(myItems) To UBound(myItems)
Set theItem = theGroup.OPCItems.AddItem(myItems(i), currentHandle)
myValue = theItem.Value
handles(1) = theGroup.OPCItems.Item(1).ServerHandle
theGroup.OPCItems.Remove 1, handles, Errors
Next i
theServer.Disconnect
End Sub
After review/trouble shooting.
The OPCItem object provides methods to read the current value of the item in the server and write a new value to the item. I have included these facilities into this dialog. The read method provided on an OPCItem object performs a synchronous read from the server and can be configured to read either from cache or from the device. To read from cache both the group and item should be active, but synchronous read operations directly from the device do not depend on the active state of either the group or item.
Adding the following code allowed me to assign to variable.
Dim source As OPCDataSource
Dim myValue As Variant
source = OPCDevice
theItem.Read source, myValue

Error Sending automation mail after registration using lotus script

Question:
1. My question why after registration of an user still not listed in domino directory?
Case:
I am using xPages form call lotus script agent.
All my script is using lotus script to register an user.
After Complete register an email, need to send automation notification mail to user as welcome mail.
when i complete registration, i want to send mail, it give me an error message:
1.unable to deliver message 'ChunWH#devsvr1.pcs.com.my'
2.User 'ChunWH#devsvr1.pcs.com.my' not listed in Domino Directory
Register user Agent
Option Public
Option Declare
Sub Initialize
On Error GoTo ErrorHandler
Dim s As New NotesSession, db As NotesDatabase, a As NotesAgent
Dim doc As NotesDocument
Set db = s.Currentdatabase
Set a = s.Currentagent
Set doc = s.Documentcontext ' uidoc
Dim maildoc As NotesDocument, body As NotesMIMEEntity
Dim stream As NotesStream
Dim groups
groups = Null
groups = group(groups,"Everyone")
Dim certid As String ' full path of cert id
Dim certpasswd As String
Dim OU As String
Dim lastname As String
Dim firstname As String
Dim middleinit As String
Dim usrIdpath As String
Dim mailsvr As String
Dim mailfile As String
Dim userpasswd As String
Dim internetpathLength As String
Dim internetpath As String
Dim remapuserID As String
Dim depvw As NotesView, depdoc As NotesDocument
Set depvw = db.Getview("Department sort by dept")
Set depdoc = depvw.Getdocumentbykey(doc.Dept(0), True)
If Not depdoc Is Nothing Then
certid = depdoc.IdPath(0)
certpasswd = depdoc.IdPassword(0)
OU = ""
lastname= doc.Name(0)
firstname = ""
middleinit = ""
usrIdpath = depdoc.DptIdStor(0) +doc.SelectMail(0)+ ".id"
' remove "." replace with empty and remove the empty space
remapuserID = remapChr(doc.SelectMail(0)) ' this is remapuserID
mailsvr = depdoc.MailSvr(0) ' mail svr
' Mail file name also cannot have . in between for example, mail/test1.apple, reason window not understand it
mailfile = depdoc.MailLocation(0)+ remapuserID ' Mail\Person
userpasswd= depdoc.UserPassword(0)
internetpath = doc.SelectMail(0)+depdoc.InternetPath(0) ' mail address
internetpathLength = Len(depdoc.InternetPath(0)) ' not used
End If
Dim reg As New NotesRegistration
Dim dt As Variant
dt = DateNumber(Year(Today)+1, Month(Today), Day(Today))
reg.RegistrationServer = mailsvr
reg.CreateMailDb = True '
reg.CertifierIDFile = certid
reg.Expiration = dt
reg.IDType = ID_HIERARCHICAL
reg.MinPasswordLength = 1
reg.IsNorthAmerican = True
reg.OrgUnit = OU
reg.RegistrationLog = "log.nsf"
reg.UpdateAddressBook = True
reg.Storeidinaddressbook = false
reg.MailInternetAddress = internetpath
reg.Shortname=doc.SelectMail(0)
reg.Mailowneraccess =2
reg.Mailcreateftindex=True
reg.Mailaclmanager ="LocalDomainAdmins"
reg.Grouplist=groups
Call reg.RegisterNewUser(lastname, _
usridpath, _
mailsvr, _
firstname, _
middleInit, _
certpasswd, _
"", _
"", _
mailfile, _
"", _
userpasswd, _
NOTES_DESKTOP_CLIENT)
Dim acl As NotesACL
Dim aclEntry As NotesACLEntry
Dim dbUser As NotesDatabase
Set dbUser = New NotesDatabase(mailsvr,mailfile) ' mail/person.nsf
Set acl = dbUser.aCL
Set aclEntry = acl.Getentry( "LocalDomainAdmins" )
If Not (aclEntry Is Nothing) Then
aclEntry.UserType = ACLTYPE_PERSON_GROUP
Call acl.Save()
End if
' call name nsf and open for edit for forcing user must change password first time
Dim ndb As NotesDatabase
Dim viwUser As NotesView
Dim docUser As NotesDocument
Set ndb = New NotesDatabase( mailsvr, "names.nsf" )
Set viwUser = ndb.GetView("People by Email")
Set docUser = viwUser.GetDocumentByKey(doc.SelectMail(0),True)
Call docUser.ReplaceItemValue( "HTTPPasswordForceChange" , "1" )
Print "Force user change password is updated"
Call docUser.Save( True, True, True )
Print "Please wait ...... Registration in progress"
Call doc.Replaceitemvalue("S_Process", "Pending")
Call doc.Save(True, False)
Dim agt As NotesAgent
Set agt=db.getagent("(Welcome Mail)")
Call agt.Runonserver()
EndOfRoutine:
Exit Sub 'or exit function
ErrorHandler:
Print Err & ", " & Error & " in line " & Erl
Resume EndOfRoutine
End Sub
Function remapChr (oldString)
' to replace all special character with a empty space after that trim to remove all special character in system
Dim oldChr, newChr, newString As String
oldChr = {! "" # $ % & ' ( ) * + , - . / : ; = > ? # [ \ ] ^ _}
newChr = " {"
oldChr = Split(oldChr, " ")
newChr = Split(newChr, " ")
newString = Trim(Replace(LCase(oldString), oldChr, newChr))
remapChr = newString
End Function
Function group(groupArr, newReason$)
If IsArray(groupArr) Then
If groupArr(0) = "" Then
groupArr(0) = newReason
Else
Dim counter%
counter = UBound(groupArr) + 1
ReDim Preserve groupArr(counter)
groupArr(counter) = newReason
End If
group = groupArr
Else
Dim tempgroupArr() As String
ReDim tempgroupArr(0)
tempgroupArr(0) = newReason
group = tempgroupArr
End If
End Function
Sending mail Agent
Sub Initialize
On Error GoTo ErrorHandler
Print "Welcome Mail Agent started..."
' This agent is a sub agent for register user, which let register agent call
Dim s As New NotesSession, db As NotesDatabase, a As NotesAgent
Dim doc As NotesDocument
Set db = s.Currentdatabase
Set a = s.Currentagent
Set doc = s.Documentcontext ' uidoc
Dim maildoc As NotesDocument, body As NotesMIMEEntity
Dim stream As NotesStream
Dim receiver$
Dim tmpallve As NotesViewEntry
Dim viwUser As NotesView
Dim viwVe As NotesViewEntry
Dim viwVc As NotesViewEntryCollection
Dim docUser As NotesDocument
Set viwUser = db.GetView("(Request sort by S_Process)")
'Set docUser = viwUser.GetDocumentByKey("Pending",True)
Set viwVc = viwUser.Allentries
If viwVc.Count = 0 Then
Print "No item found in this list"
Exit Sub
End If
Set viwVe = viwVc.Getfirstentry()
Do While Not viwVe Is Nothing ' loop to all entry
Set docUser = viwVe.Document
receiver$ = docUser.SelectMail(0) + "#devsvr1.pcs.com.my"
' send mail
Set maildoc = db.Createdocument()
Call maildoc.Replaceitemvalue("Form", "Memo")
Call maildoc.Replaceitemvalue("Subject", "Welcome")
Call maildoc.Replaceitemvalue("SendTo", receiver)
Set body = maildoc.Createmimeentity
s.Convertmime = False
Set stream = s.Createstream()
stream.Writetext(|<html><body>|)
stream.Writetext(|<p>Your application for registration ....</p>|)
stream.Writetext(|<p>Welcome. Pleaase....</p>|)
stream.Writetext(|<p><em>(No signature requried on this computer generated document)</em></p>|)
stream.Writetext(|<p>*** This is a system generated email. | + _
|Please do not reply to this email. ***</p>|)
Call stream.Writetext(|</body></html>|)
Call body.Setcontentfromtext(stream, "text/html;charset=UTF-8", 1725)
Call maildoc.Send(False)
s.Convertmime = True
Call docUser.Replaceitemvalue("S_Process", "Processed")
Call docUser.Save(True, False)
Set tmpallve = viwVc.Getnextentry(viwVe)
Set viwVe = tmpallve
Loop
Print "Welcome Mail Agent finished..."
EndOfRoutine:
Exit Sub 'or exit function
ErrorHandler:
Print Err & ", " & Error & " in line " & Erl
Resume EndOfRoutine
End Sub
new update of image on 25/09/2017
(after set config router_debug=3 set config DebugRouterLookup=3 )
i try send manually will be fine...but using code directly send after registration will be fail. Not only that, i also try on sleep(2) , wait 2 second just send mail..it seem like my thought of not directly create mail account mail also not valid..not sure which part is wrong?
I suspect that your issue is one of time and caching. The Domino server maintains a Name Lookup Cache that only gets refreshed, well, occasionally (I have never figured out how occasionally that is but 5-10 minutes generally does the trick). This affects both the email functions and the web login functions. What I have done with my registration systems is have the agent that does the ID creation leave a document in it database that is in the status "Pending welcome email". Then another agent finds those docs and if they are more then 15 minutes old it attempts the email. if the email goes through then the status is changed to "Complete".
Note, you can reset the cache with the console command show nlcache reset and that almost always results in the user being able to get mail and login from a browser. But I have not been able to get that to work from a scheduled agent run on the server or a web agent.
Can you take a look at the Person Document? See if that address is properly registered on the document.
You may also try to enable router_debug=3 and DebugRouterLookUp=3 and we may see where did it try to lookup the address.

Accessing Lotus Notes database from Excel VBA - how do I pick up COLUMNVALUES?

I am investigating pulling data from a Notes database directly into Excel as our Finance guy is manually re-typing figures a.t.m.
This is my code so far:
Sub notesBB()
Const DATABASE = 1247
Dim r As Integer
Dim i As Integer
Dim c As Integer
Dim db As Object
Dim view As Object
Dim Entry As Object
Dim nav As Object
Dim Session As Object 'The notes session
Dim nam As Object
Dim val As Variant
Dim v As Double
Dim items As Object
Set Session = CreateObject("Lotus.NotesSession")
Call Session.Initialize
Set nam = Session.CreateName(Session.UserName)
user = nam.Common
Set db = Session.getdatabase("MSPreston", "Billbook1415.nsf")
Set view = db.GetView("By Month\By Dept")
view.AutoUpdate = False
Set nav = view.CreateViewNav
Set Entry = nav.GetFirst
val = Entry.childcount
val = Entry.ColumnValues(6) ' this doesn't work
Set items = Entry.ColumnValues 'from a suggestion on the net
val = items(6) 'this doesn't work either
MsgBox (val)
End Sub
error is "object variable or With Block variable not set"
The annoying thing is that I can see the values I want in the ExcelVBA debug window... so I can't be far off. I guess its how to access an array of items properly
The answer is to declare a variant array and assign it directly...
Sub notesBB()
Const DATABASE = 1247
Dim r As Integer
Dim i As Integer
Dim db As Object
Dim view As Object
Dim Entry As Object
Dim nav As Object
Dim Session As Object 'The notes session
Dim nam As Object ' notes username
Dim v() As Variant ' to hold the subtotal values
Dim bills(12, 16) ' 12 months, 16 departments
r = 1
Worksheets(1).Range("A1:z99").Clear
Set Session = CreateObject("Lotus.NotesSession") 'Start a session to notes
Call Session.Initialize
Set nam = Session.CreateName(Session.UserName)
user = nam.Common
Set db = Session.getdatabase("MSPreston", "Billbook1415.nsf")
Set view = db.GetView("By Month\By Dept")
view.AutoUpdate = False
Set nav = view.CreateViewNav
Set Entry = nav.GetFirst
Do Until Entry Is Nothing
If Entry.isCategory Then
r = r + 1
v = Entry.ColumnValues
For i = 1 To 16
bills(v(0), i) = v(4 + i)
Cells(4 + r, 2 + i) = bills(v(0), i)
Next
End If
Set Entry = nav.getNextCategory(Entry)
DoEvents
Loop
End Sub
This code just extracts the 12 months (rows) by 16 departments (cols) bills values from the Notes view and populates an Excel range with them. Easy when you know (find out) how !

Remainder Mail agent

I have form with 3 fields adress,status,ReportingDate.
Adress field contains the ID where the mil has to be sent.
Now I have created an agent where it should mail to the data present in adress field when status is incomplete and reporting date is exactly 7 days before todays date.
My Code:
Option Public
Option Declare
Sub Initialize
Dim sess As New NotesSession
Dim db As NotesDatabase
Dim doc As NotesDocument
Dim timestamp As New NotesDateTime("Today")
Dim Noresponsedate As NotesDateTime
Dim vw As NotesView
Dim diff As Integer
Dim SendTo As Variant
Call timestamp.SetNow()
Set db = sess.CurrentDatabase
Set vw = db.GetView( "data" )
Set doc = vw.GetFirstDocument()
While Not doc Is Nothing
If doc.Status(0) = "Incomplete" Then
Call checktimedifference(doc)
End if
Set doc = vw.GetNextDocument(doc)
wend
End Sub
Sub checktimedifference(doc As NotesDocument)
Dim due As NotesDateTime
Dim present As NotesDateTime
Dim timecheck As variant
Set due = New NotesDateTime ( "" )
Set present = New NotesDateTime ( "Today" )
timecheck = doc.ReportingDate(0)
due.LSLocalTime = timecheck
If due.TimeDifference (present) = -604800 Then
Call sendmailtouser(doc)
End If
End Sub
Sub sendmailtouser(doc As NotesDocument)
Dim db As NotesDatabase
Dim rtiitem As NotesRichTextItem
Dim maildoc As NotesDocument
dim recepient As variant
Set maildoc = New NotesDocument( db )
Set rtiitem = New NotesRichTextItem( maildoc, "Body" )
recepient = doc.adress(0)
maildoc.from = db.Title
maildoc.form = "memo"
maildoc.subject = "A Minor Injury Report:" & doc.Seq_No(0) & " needs your response"
maildoc.SendTo = recepient
Call rtiitem.AppendText( "Please respond to this Minor Injury Report" )
Call rtiitem.AddNewline( 2 )
Call rtiitem.AppendText( "Your response for the Minor Injury Report: " & doc.Seq_No(0) & " is required" )
Call rtiitem.AddNewline( 2 )
Call rtiitem.AppendText( "Please click on the following link to access the document.")
Call rtiitem.AppendDocLink( doc, db.Title )
Call maildoc.Send(False)
End Sub
When I am running the agent on client I am getting the following error:
Please help me to solve the error and send mail to the recepients.
Not using any error handling is very bad practice. But your error will most probably happen in the sendmailtouser- sub, where you dim a local notesdatabase- object named db without actually initializing it.
The line
set maildoc = New NotesDocument( db )
will fail.
Either declare db globally and set it in your initialize or dim ses in that sub again and set db again (worst case as you have to do it for every document)

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.

Resources