IBM®
Skip to main content
    Country/region select      Terms of use
 
 
   
     Home      Products      Services & solutions      Support & downloads      My account     

developerWorks  >  Lotus  >  Forums & community  >  Best Practice Makes Perfect

Best Practice Makes Perfect

A collaboration with Domino developers about how to do it and how to get it right in Domino

I haven't been adding much technical content to this blog recently, because the little time I have available for that kind of thing has been going toward the Designer wiki.  My most recent article there is How to Write a Hide Formula (about which, as usual, I invite reader comments and corrections). This is fairly basic formula stuff, but it's the sort of thing that beginning developers often have a hard time with.

You folks who read this blog, probably have similar things that you could contribute.  I'd like to see the wiki become a resource for Notes developers of all levels to go when puzzled, or when they have spare time to read articles that might benefit them for later projects.  So we need a range of information from the basic to the high-end. What seems obvious to you might not be obvious to everyone.  Are there development techniques you use routinely that might be a pleasant surprise for someone new to Notes development?

Andre Guirard | 23 February 2009 10:55:05 AM ET | Home, Plymouth, MN, USA | Comments (9)


 Comments

1) simple OOP
Lars Berntrop-Bos | 2/23/2009 5:59:29 PM

A thing I use a lot is private or public classes. Especially to manage a list of something, (might be a list of objects)

Like:

Private Class cars_container

Public cars List as String

Public idx as Long

Public Sub Add(carName$)

idx = idx + 1

cars(idx) = carName

End Sub

End Class

Private Class boat_container

Public name as String

Public size as Double

Public Sub New(boatName$, boatSize#)

name = boatName

size = boatSize

End Sub

End Class

Private Class boats_container

Public boats List as boat_container

Public idx as Long

Public Sub Add(boatName$, size as Double)

idx = idx + 1

Set boats(idx) = New boat_container(boatName, Size)

End Sub

Public Sub sortBySize

' simple bubble sort to sort by size

End Sub

End Class

In other code:

' init hangar:

Dim shed as New boats_container

' load boats:

shed.add speeder, 10

shed.add dinghy, 5

etc, etc

2) yikes, the layout is awful
Lars Berntrop-Bos | 2/23/2009 6:02:20 PM

Hi Andre, I tried indenting with spaces, but those are all gone... can you fix the layout? Anyway you get the idea, rolling your own objects makes for compact code and is very useful!

3) My Frequent Use JS functions
rishi sahi | 2/23/2009 11:29:33 PM

//initialize dbUrl variable for every page on the web site

var dbUrl ;

if (location.href.indexOf(".NSF")>-1) dbUrl = location.href.split(".NSF")[0] + ".NSF";

if (location.href.indexOf(".nsf")>-1) dbUrl = location.href.split(".nsf")[0] + ".nsf";

// - - - - - - - dbUrl end - - - - - -

function addressBook(paramDivName, paramFormName, paramFieldName, Count, TextType, format, returnToFunction ){

dbURL = location.href.toLowerCase().split(".nsf")[0] + ".nsf" ;

texttype = TextType;

divname = paramDivName;

formname = paramFormName;

addressField = paramFieldName;

if ( returnToFunction ) addressFunction = returnToFunction; //if return value to function is required

statement = Count ;

var pathname= dbURL +"/";

if (format) {

nameformat = format;

}else{

nameformat = "CN";

}

strStatus = "status=no,menubar=no, scrollbars=no,top=120,left=100,width=550,height=500";

childwindow = window.open( dbURL+'/AddressBook?OpenForm&Login=1','Address',strStatus);

}

/* replaces the <arr> of texts with <replacement> text */

function replace( val, src, trg )

{

var regexp = new RegExp ( src , "gi" );

return val.replace( regexp, trg );

}

function trim ( paramString ) {

return paramString.replace(/^\s+/,'').replace(/\s+$/,'').replace(/\s{2,}/g,' ');

}

function isValidImageFile( filename ) {

var extn = (filename.indexOf(".")>-1)? filename.split(".")[1].toLowerCase() : "";

if (extn != "jpg" && extn != "gif" && extn != "png" )

{

alert( "Invalid image file.\nSupported file extensions are JPG, GIF and PNG only." );

return false;

}

return true;

}

//useful for retrieving FILE upload handle by passing "file" as parameter

function getElementByType( typename ){

var frm = document.forms[0];

var itms = frm.elements;

for(var i=0; i < itms.length ; i ++ )

{

if ( itms.type == typename ) return itms;

}

}

function getElementsByType( typename ){

var frm = document.forms[0];

var itms = frm.elements;

var arrO=new Array();

for(var i=0; i < itms.length ; i ++ )

{

if ( itms.type == typename ) arrO[arrO.length] = itms;

}

return arrO;

}

//to restrict keying only numbers within any input fields, Usage onkeypress=validNum(this);

function validNum(o)

{ if ( isNaN( o.value ) ) o.value = o.value.replace ( /[^0-9]/g, "" ); }

//restrict number of characters keyed in

function limitText( limitField, limitNum ) {

if (limitField.value.length > limitNum) {

limitField.value = limitField.value.substring(0, limitNum);

} else {

showLimit ( limitField, limitNum, limitNum - limitField.value.length );

}

}

function showLimit( limitField, limitNum, count ) {

var div = document.all.divLimitDisplay;

//creating for first time

if (! div ) {

var style = "background-color:lightyellow; position:absolute; left:0; top:0; width:100; height:30; font-size:7pt; color:black; padding:1; border:1 solid black;z-index:10; visibility:hidden;text-align:center;" ;

document.body.insertAdjacentHTML("beforeEnd","<div id='divLimitDisplay' style='"+style+"'></div>" );

div = document.all.divLimitDisplay;

}

//positioning and displaying

if ( div.style.visibility=="hidden" ) {

div.style.left = limitField.clientWidth + getRealLeft( limitField ) - div.clientWidth + 4 ;

div.style.top = getRealTop( limitField ) - div.clientHeight + 4;

div.style.visibility = "visible";

}

//updating msg

div.innerText = "Max chars: "+limitNum + "\nChars left: " + count ;

}

function hideLimit( ) {

var div = document.all.divLimitDisplay;

if (div) div.style.visibility = "hidden";

}

function getRealLeft(el) {

xPos = el.offsetLeft;

tempEl = el.offsetParent;

while (tempEl != null) {

xPos += tempEl.offsetLeft;

tempEl = tempEl.offsetParent;

}

return xPos;

}

function getRealTop(el) {

yPos = el.offsetTop;

tempEl = el.offsetParent;

while (tempEl != null) {

yPos += tempEl.offsetTop;

tempEl = tempEl.offsetParent;

}

return yPos;

}

function catchevent() {

var src = event.srcElement;

if ( ! src ) return;

if ( src.tagName != "TEXTAREA" ) return;

switch ( event.type ) {

case "focus":

limitText( src, 500 ); //limit characters to 500;

break;

case "keydown":

case "keyup":

limitText( src, 500 );

break;

case "blur":

hideLimit();

break;

}

}

function allTrim( mstr ) {

return mstr.split(/\s/g).join(" ");

}

function strToDate( mstr ) {

var arr = mstr.split("-");

//javascript supported date string is "MMM-DD, YYYY";

var jsDt = arr[1] + "-" + arr[0] + ", " + arr[2] ;

var dt = new Date( jsDt );

return dt;

}

4) Activity Class for log
rishi sahi | 2/23/2009 11:33:55 PM

Const acINFO = "Information"

Const acERR = "Error"

Const acMAIL = "Mail"

Class ActivityClass

Declare Public Function AddActivity(ActivityMsg As String)

Declare Public Function AddData(ActivityMsg As String)

Declare Public Function AttachLink(LinkDoc As NotesDocument)

Declare Public Function CloseActivity(StopTime As String, Status As Integer)

Declare Public Function GetStatistics()

Declare Public Function IsLogAvailable() As Integer

Declare Public Sub Save()

Public Status As Integer

Public AutoSave As Integer

'Private Variables

Private ActivityLog As NotesDocument

Private ItemActivityName As NotesItem

Private itemActivityStartTime As NotesItem

Private ItemActivityStopTime As NotesItem

Private ItemActivityStartedBy As NotesItem

Private ItemActivityFlag As NotesItem

Private ItemActivityStatus As NotesItem

Private ItemActivityLog As NotesRichTextItem

Private RtStyle1 As NotesRichTextStyle

Private RtStyle2 As NotesRichTextStyle

Private ItemActivityIsOnServer As NotesItem

Public MsgCount List As Long

Private TotalMsgCount As Long

'Constructor

Sub New(ActivityName As String ) ', StartDate As NotesDateTime , StartedBy As String)

Dim Ses As New NotesSession

Dim db As NotesDatabase

Dim ItemDate As NotesDateTime

Dim StartedBy As String

Dim StartDate As New NotesDateTime ( Now )

Call StartDate.SetNow

Set db = Ses.CurrentDatabase

StartedBy = Ses.CommonUserName

Set RtStyle1 = Ses.CreateRichTextStyle

RtStyle1.Bold = False

RtStyle1.Fontsize = 8

RtStyle1.NotesFont = FONT_COURIER

RtStyle1.NotesColor = COLOR_BLACK

Set RtStyle2 = Ses.CreateRichTextStyle

RtStyle2.Bold = False

RtStyle2.Fontsize = 8

RtStyle2.NotesFont = FONT_HELV

RtStyle2.NotesColor = COLOR_BLACK

If Not db Is Nothing Then

Set ActivityLog = db.CreateDocument

ActivityLog.Form = "ActivityLog"

Set ItemActivityName = ActivityLog.ReplaceItemValue( "Activity$AgentName", ActivityName)

Set ItemActivityStartTime = ActivityLog.ReplaceItemValue( "Activity$StartDtTime", StartDate)

Set ItemActivityStopTime = ActivityLog.ReplaceItemValue( "Activity$EndDtTime", "")

Set ItemActivityStartedBy = ActivityLog.ReplaceItemValue( "Activity$StartedBy", StartedBy)

Set ItemActivityStatus = ActivityLog.ReplaceItemValue( "Activity$Status", "")

Set ItemActivityFlag = ActivityLog.ReplaceItemValue("Activity$Flag", "")

Set ItemActivityLog = New NotesRichTextItem(ActivityLog, "Activity$Log")

Set ItemActivityIsOnServer = ActivityLog.ReplaceItemValue( "Activity$IsOnServer", Ses.IsOnServer )

End If

Me.Status = True

AutoSave = False 'Save only on termination by default

'Initialize default Msg Categories that are required

MsgCount( acINFO ) = 0

MsgCount( acERR ) = 0

MsgCount( acMAIL ) = 0

End Sub

Sub Delete()

If ActivityLog Is Nothing Then Exit Sub

'If AutoSave were enabled, nothing has to be saved

If Not AutoSave Then UpdateSummary

If Not AutoSave Then If MsgCount( acINFO ) > 0 Then Call ActivityLog.Save(True,True) 'save only if there are msgs

End Sub

Sub UpdateSummary()

'Do final updates when processing is completed

Call ActivityLog.ReplaceItemValue( "Activity$Summary", GetStatistics() )

Call ActivityLog.ReplaceItemValue( "Activity$CountINFO", MsgCount(acINFO) )

Call ActivityLog.ReplaceItemValue( "Activity$CountERROR", MsgCount(acERR) )

Call ActivityLog.ReplaceItemValue( "Activity$CountMAIL", MsgCount(acMAIL) )

End Sub

Function AddActivity( Ctg As String, ActivityMsg As String)

If ActivityLog Is Nothing Then Error 10001, "Cannot log events after the Quit method call"

Dim ActivityMessage As String

Dim dtTime As String

TotalMsgCount = TotalMsgCount + 1

If Ctg = "" Then Ctg = acINFO

'Increment count for this Ctg

MsgCount( Ctg ) = MsgCount( Ctg ) + 1

'For custom Ctg, increment acINFO count also treating them as normal info

If Ctg <>acINFO And Ctg <> acERR And Ctg <> acMAIL Then MsgCount( acINFO ) = MsgCount( acINFO ) + 1

dtTime = Format(Now(),"dd-mmm-yyyy hh:mm:ss AM/PM")

ActivityMessage = dtTime & ": " & Ctg & ": " & ActivityMsg

Call ItemActivityLog.AppendStyle(RtStyle2)

ItemActivityLog.AppendText(ActivityMessage)

Call ItemActivityLog.AppendStyle(RtStyle2)

Call ItemActivityLog.AddNewLine(1)

If Ctg = acERR Then

Me.Status = False

EndActivity

Else

EndActivity

End If

End Function

Function AddData(Activitys As String)

'Adding bulk data

Call ItemActivityLog.AppendStyle(RtStyle1)

ItemActivityLog.AppendText(Activitys )

Call ItemActivityLog.AppendStyle(RtStyle2)

Call ItemActivityLog.AppendStyle(RtStyle2)

Call ItemActivityLog.AddNewLine(1)

EndActivity

End Function

Function AttachLink(ActivityMsg As String, LinkDoc As NotesDocument )

'Append Document link

Dim ActivityMessage As String

ActivityMessage = ActivityMsg

Call ItemActivityLog.AppendStyle(RtStyle2)

ItemActivityLog.AppendText(ActivityMessage)

Call ItemActivityLog.AppendStyle(RtStyle2)

Call ItemActivityLog.AppendDocLink(LinkDoc, "DocLink")

Call ItemActivityLog.AddNewLine(1)

EndActivity

End Function

Function EndActivity ()

Dim endDateTime As NotesDateTime

'Close the Activity Log

Set endDateTime = New NotesDateTime ( "" )

Call endDateTime.SetNow

Call Me.CloseActivity( endDateTime, Me.Status )

End Function

Function CloseActivity(ItemDate As NotesDateTime, Status As Integer)

Set ItemActivityStopTime = ActivityLog.ReplaceItemValue("Activity$EndDtTime", ItemDate)

If Not Status Then Me.Status = False

If Me.Status Then

Set ItemActivityStatus = ActivityLog.ReplaceItemValue("Activity$Status", "Successful")

Else

Set ItemActivityStatus = ActivityLog.ReplaceItemValue("Activity$Status", "Failed")

End If

If AutoSave Then UpdateSummary

If AutoSave Then Call ActivityLog.Save(True,True)

End Function

Sub Save()

Call ActivityLog.Save(True,True)

End Sub

Sub Quit( flagSave As Integer )

'Force quitting the Log without saving by passing False argument

If flagSave Then Call ActivityLog.Save(True,True)

Set ActivityLog = Nothing

End Sub

Function IsLogAvailable() As Integer

'Return if any msgs were logged

If TotalMsgCount > 0 Then

IsLogAvailable = True

Else

IsLogAvailable = False

End If

End Function

Function GetStatistics() As Variant

'Returns an array of statistics messages

Dim retArr() As String

Dim count As Integer

Forall listEntry In MsgCount

Redim Preserve retArr( count )

retArr(count) = retArr(count) & Format( listEntry, "0" ) & " : " & Listtag( listEntry ) & " events logged"

count = count + 1

End Forall

GetStatistics = retArr

End Function

End Class

5) WinAPI - Part-1
rishi sahi | 2/23/2009 11:39:42 PM

Declarations

--------------------------------------------------------------

Declare Function GetLocaleInfo Lib "kernel32" Alias "GetLocaleInfoA" (Byval Locale As Long, Byval LCType As Long, Byval lpLCData As String, Byval cchData As Long) As Long

Declare Function SetLocaleInfo Lib "kernel32" Alias "SetLocaleInfoA" (Byval Locale As Long, Byval LCType As Long, Byval lpLCData As String) As Integer

Declare Function GetUserDefaultLCID% Lib "kernel32" ()

Private Const LOCALE_ICENTURY = &H24

Private Const LOCALE_ICOUNTRY = &H5

Private Const LOCALE_ICURRDIGITS = &H19

Private Const LOCALE_ICURRENCY = &H1B

Private Const LOCALE_IDATE = &H21

Private Const LOCALE_IDAYLZERO = &H26

Private Const LOCALE_IDEFAULTCODEPAGE = &HB

Private Const LOCALE_IDEFAULTCOUNTRY = &HA

Private Const LOCALE_IDEFAULTLANGUAGE = &H9

Private Const LOCALE_IDIGITS = &H11

Private Const LOCALE_IINTLCURRDIGITS = &H1A

Private Const LOCALE_ILANGUAGE = &H1

Private Const LOCALE_ILDATE = &H22

Private Const LOCALE_ILZERO = &H12

Private Const LOCALE_IMEASURE = &HD

Private Const LOCALE_IMONLZERO = &H27

Private Const LOCALE_INEGCURR = &H1C

Private Const LOCALE_INEGSEPBYSPACE = &H57

Private Const LOCALE_INEGSIGNPOSN = &H53

Private Const LOCALE_INEGSYMPRECEDES = &H56

Private Const LOCALE_IPOSSEPBYSPACE = &H55

Private Const LOCALE_IPOSSIGNPOSN = &H52

Private Const LOCALE_IPOSSYMPRECEDES = &H54

Private Const LOCALE_ITIME = &H23

Private Const LOCALE_ITLZERO = &H25

Private Const LOCALE_NOUSEROVERRIDE = &H80000000

Private Const LOCALE_S1159 = &H28

Private Const LOCALE_S2359 = &H29

Private Const LOCALE_SABBREVCTRYNAME = &H7

Private Const LOCALE_SABBREVDAYNAME1 = &H31

Private Const LOCALE_SABBREVDAYNAME2 = &H32

Private Const LOCALE_SABBREVDAYNAME3 = &H33

Private Const LOCALE_SABBREVDAYNAME4 = &H34

Private Const LOCALE_SABBREVDAYNAME5 = &H35

Private Const LOCALE_SABBREVDAYNAME6 = &H36

Private Const LOCALE_SABBREVDAYNAME7 = &H37

Private Const LOCALE_SABBREVLANGNAME = &H3

Private Const LOCALE_SABBREVMONTHNAME1 = &H44

Private Const LOCALE_SCOUNTRY = &H6

Private Const LOCALE_SCURRENCY = &H14

Private Const LOCALE_SDATE = &H1D

Private Const LOCALE_SDAYNAME1 = &H2A

Private Const LOCALE_SDAYNAME2 = &H2B

Private Const LOCALE_SDAYNAME3 = &H2C

Private Const LOCALE_SDAYNAME4 = &H2D

Private Const LOCALE_SDAYNAME5 = &H2E

Private Const LOCALE_SDAYNAME6 = &H2F

Private Const LOCALE_SDAYNAME7 = &H30

Private Const LOCALE_SDECIMAL = &HE

Private Const LOCALE_SENGCOUNTRY = &H1002

Private Const LOCALE_SENGLANGUAGE = &H1001

Private Const LOCALE_SGROUPING = &H10

Private Const LOCALE_SINTLSYMBOL = &H15

Private Const LOCALE_SLANGUAGE = &H2

Private Const LOCALE_SLIST = &HC

Private Const LOCALE_SLONGDATE = &H20

Private Const LOCALE_SMONDECIMALSEP = &H16

Private Const LOCALE_SMONGROUPING = &H18

Private Const LOCALE_SMONTHNAME1 = &H38

Private Const LOCALE_SMONTHNAME10 = &H41

Private Const LOCALE_SMONTHNAME11 = &H42

Private Const LOCALE_SMONTHNAME12 = &H43

Private Const LOCALE_SMONTHNAME2 = &H39

Private Const LOCALE_SMONTHNAME3 = &H3A

Private Const LOCALE_SMONTHNAME4 = &H3B

Private Const LOCALE_SMONTHNAME5 = &H3C

Private Const LOCALE_SMONTHNAME6 = &H3D

Private Const LOCALE_SMONTHNAME7 = &H3E

Private Const LOCALE_SMONTHNAME8 = &H3F

Private Const LOCALE_SMONTHNAME9 = &H40

Private Const LOCALE_SMONTHOUSANDSEP = &H17

Private Const LOCALE_SNATIVECTRYNAME = &H8

Private Const LOCALE_SNATIVEDIGITS = &H13

Private Const LOCALE_SNATIVELANGNAME = &H4

Private Const LOCALE_SNEGATIVESIGN = &H51

Private Const LOCALE_SPOSITIVESIGN = &H50

Private Const LOCALE_SSHORTDATE = &H1F

Private Const LOCALE_STHOUSAND = &HF

Private Const LOCALE_STIME = &H1E

Private Const LOCALE_STIMEFORMAT = &H1003

'

' Locale Constants

'

Const LOCALE_USER_DEFAULT = &H400

Declare Function GetSystemDefaultLangID Lib _

"KERNEL32" () As Integer

Declare Function VerLanguageName Lib "KERNEL32" _

Alias "VerLanguageNameA" (Byval wLang As Long, _

Byval szLang As String, Byval nSize As Long) As Long

--------------------------------------------------------------

Function GetRegionalSettings() ' Retrieve the regional setting

GetRegionalSettings = "/"

Dim Symbol As String

Dim iRet1 As Long

Dim iRet2 As Long

Dim lpLCDataVar As String

Dim Pos As Integer

Dim Locale As Long

Locale = GetUserDefaultLCID()

'LOCALE_SDATE is the constant for the date separator

'as stated in declarations

'for any other locale setting just change the constant

'Function can also be re-written to take the

'locale symbol being requested as a parameter

iRet1 = GetLocaleInfo(Locale, LOCALE_SDATE, _

lpLCDataVar, 0)

Symbol = String$(iRet1, 0)

iRet2 = GetLocaleInfo(Locale, LOCALE_SDATE, Symbol, iRet1)

Pos = Instr(Symbol, Chr$(0))

If Pos > 0 Then

Symbol = Left$(Symbol, Pos - 1)

GetRegionalSettings = Symbol

End If

End Function

-----------------------------------------------------------

Sub SetRegionalSettings() 'Change the regional setting

Dim Symbol As String

Dim iRet As Long

Dim Locale As Long

'LOCALE_SDATE is the constant for the date separator

'as stated in declarations

'for any other locale setting just change the constant

'Function can also be re-written to take the

'locale information being set as a parameter

Locale = GetUserDefaultLCID() 'Get user Locale ID

Symbol = "-" 'New character for the locale

iRet = SetLocaleInfo(Locale, LOCALE_SDATE, Symbol)

End Sub

----------------------------------------------------------

Function GetRegionalSettingDateFormat() As String

Dim lBuffLen As Long

Dim sBuffer As String

Dim lResult As Long

Dim sDateFormat As String

On Error Goto ErrHand

lBuffLen = 128

sBuffer = String$(lBuffLen, vbNullChar)

lResult = GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_SSHORTDATE, sBuffer, lBuffLen)

If lResult > 0 Then

sDateFormat = Left$(sBuffer, lResult - 1)

If Instr(1, sDateFormat, "YYYY" ) = 0 Then

End If

GetRegionalSettingDateFormat = sDateFormat

Else

GetRegionalSettingDateFormat = "DD/MM/YYYY"

End If

Exit Function

ErrHand:

Msgbox Error$

End Function

-----------------------------------------------------------

6) Notes Client generic validation class
rishi sahi | 2/23/2009 11:42:10 PM

Class Validations

'includes common validations

Function CheckBlank(itemname As String , value)

Dim Msg As String, Title As String

If Trim(Cstr(value))="" Then

Msg="Please enter a valid value for field : '" + itemname + "'"

Title = "Field Validation "

Call ShowMsg(Msg ,Title)

CheckBlank=False

Else

CheckBlank=True

End If

End Function

Function CheckBlankItems(itemname() As String , value() ) 'to check many items together

Dim Msg As String, Title As String

Dim count As Integer, i As Integer

count=Ubound(itemname)

For i=0 To count

If Trim(Cstr(value(i)))="" Then

Msg="Please enter/select a valid value for field : '" + itemname(i) + "'"

Title = "Field Validation "

Call ShowMsg(Msg ,Title)

CheckBlankItems=False

Exit Function

Else

CheckBlankItems=True

End If

Next

End Function

Function CheckRelativeBlank(itemname As String , value , FilledItems() As String, FilledItemValues() )

Dim Msg As String, Title As String

Dim i As Integer

For i=0 To Ubound(FilledItems)

If FilledItemValues(i)<>"" Then

If Trim(Cstr(value))="" Then

Msg = "Field '" + itemname + "' cannot be blank when a value for field '"+ FilledItems(i) + "' has been entered/selected."

Title = "Field Validation"

Call ShowMsg(Msg ,Title)

CheckRelativeBlank=False

Exit Function

End If

Else

End If

Next

CheckRelativeBlank=True

End Function

Function CheckFieldValidity(label As String, fieldValue , fieldType As String)

Dim Msg As String, Title As String

Title = "Field Validation"

Select Case fieldType

Case "DATE"

If Trim(Cstr(FieldValue)) <> "" Then

If Not Isdate(fieldvalue) Then

Msg="Please enter a valid date value for the field : '" + label + "'"

Call ShowMsg(Msg, Title)

CheckFieldValidity=False

Exit Function

End If

End If

Case "NUMBER"

If Trim(Cstr(fieldvalue))<>"" Then

If Not Isnumeric(fieldvalue) Then

Msg="Please enter a valid number value for the field : '" + label + "'"

Call ShowMsg(Msg, Title)

CheckFieldValidity=False

Exit Function

End If

End If

End Select

CheckFieldValidity=True

End Function

Function CheckNumberType(label As String, fieldValue , checkType As String)

'assumption that this is called after validity check

Dim Msg As String, Title As String

Title = "Field Validation"

Msg="Field '"+ label + "' should be numeric and of type " + checkType +"."

Select Case checkType

Case "INTEGER"

If Int(fieldValue) <> fieldValue Then

' If Datatype(fieldValue) = V_INTEGER Then

Call ShowMsg(Msg,Title)

CheckNumberType=False

Exit Function

End If

End Select

CheckNumberType=True

End Function

Function DateComparisonCheck(fieldlabel As String, fieldvalue , otherfieldlabel As String, otherfieldvalue)

Dim Msg As String, Title As String

Title = "Date Validation"

Msg="Field : '"+fieldlabel +"' cannot be a date earlier than the date entered for field : '"+ otherfieldlabel +"'"

If Trim(Cstr(fieldvalue))="" Or Trim(Cstr(otherfieldvalue))=""Then

DateComparisonCheck=True

Exit Function

End If

If Cdat(fieldvalue)< Cdat(otherfieldvalue) Then

Call ShowMsg(Msg, Title)

DateComparisonCheck=False

Exit Function

End If

DateComparisonCheck=True

End Function

Function NumberSignCheck(Label As String, FieldValue,ValidSign As String)

'assumption that this is called after validity check

Dim Msg As String, Title As String

Title="Field Validation"

Select Case ValidSign

Case "POSITIVE"

If Sgn(FieldValue) <> 1 Then

Msg="Value entered for Field : '"+ Label + "' should be a Positive number"

Call ShowMsg(Msg, Title)

NumberSignCheck=False

Exit Function

End If

Case "NEGATIVE"

If Sgn(FieldValue) <> -1 Then

Msg="Value entered for Field : '"+ Label + "' should be a Negative number"

Call ShowMsg(Msg, Title)

NumberSignCheck=False

Exit Function

End If

Case "NONZERO"

If Sgn(FieldValue) = 0 Then

Msg="Value entered for Field : '"+ Label + "' cannot be Zero"

Call ShowMsg(Msg, Title)

NumberSignCheck=False

Exit Function

End If

End Select

NumberSignCheck=True

End Function

Function ValueLengthCheck(Label As String, Fieldvalue, ValidLength As Integer, Check As String)

'assumption that this is called after validity check

Dim Msg As String, Title As String

Title="Field Validation"

Select Case Check

Case "MAXLENGTH" ' value length can be max specified value

If Len(Cstr(FieldValue))>ValidLength Then

Msg="Length of value entered for Field : '"+ Label + "' cannot exceed " + Cstr(ValidLength) + " characters"

Call ShowMsg(Msg, Title)

ValueLengthCheck=False

Exit Function

End If

Case "VALIDLENGTH" ' value length has to be specified value

If Len(Cstr(FieldValue))<>ValidLength Then

Msg="Length of value entered for Field : '"+ Label + "' has to be equal to " + Cstr(ValidLength) + " characters"

Call ShowMsg(Msg, Title)

ValueLengthCheck=False

Exit Function

End If

End Select

ValueLengthCheck=True

End Function

Function CheckNotDupInOtherDoc(Label As String, FieldValue() As String, View As String, docID As String, ErrMsg As String)

Dim Msg As String, Title As String

Dim s As New Notessession

Dim db As Notesdatabase

Dim v As Notesview

Dim dc As Notesdocumentcollection

Dim doc As Notesdocument

Set db=s.currentdatabase

Set v=db.getview(View)

If Not v Is Nothing Then

Set dc = v.getalldocumentsbykey(FieldValue,True)

If dc.count >1 Then

Title="Duplicate document Check"

Msg="'"+ label + "'" + ErrMsg + " Please enter unique value."

Call ShowMsg(Msg, Title)

CheckNotDupInOtherDoc=False

Exit Function

Elseif dc.count=1 Then

Set doc=dc.getnthdocument(1)

If doc.UniversalID<> docID Then

Title="Duplicate document Check"

Msg="'"+ label + "'" + ErrMsg + " Please enter unique value."

Call ShowMsg(Msg, Title)

CheckNotDupInOtherDoc=False

Exit Function

Else

CheckNotDupInOtherDoc=True

Exit Function

End If

Else

CheckNotDupInOtherDoc=True

Exit Function

End If

Else

Msg="An error occured during '"+ Label + "' field duplicate check. View Object could not be set. Please contact Administrator."

Title="Error during validation"

Call ShowMsg(Msg, Title)

CheckNotDupInOtherDoc=False

Exit Function

End If

End Function

Function CheckNoInvalidChars(Label As String , Fieldvalue As String, Chars As String,specialchars() As String)

Dim Msg As String, Title As String

Dim i As Integer

Title="Invalid Character Check"

Msg="Field '"+ label + "' has one of the following invalid characters : " + chars

If specialchars(0)<>"" Then

For i=0 To Ubound(specialchars)

If Fieldvalue Like "*"+specialchars(i) +"*" Then

Msg="Field '"+ label + "' has the following invalid character/ pattern : " + specialchars(i)

Call showmsg(Msg, title)

CheckNoInvalidChars = False

Exit Function

End If

Next

End If

If Chars <>"" Then

If Fieldvalue Like "*["+Chars+"]*" Then

Call showmsg(Msg, title)

CheckNoInvalidChars = False

Exit Function

End If

End If

CheckNoInvalidChars=True

End Function

Function CheckNoInvalidCharsAtEnds(Label As String , Fieldvalue As String, Chars As String,specialchars() As String,WhichEnd As String)

Dim Msg As String, Title As String

Dim i As Integer

Title="Invalid Character Check"

Select Case WhichEnd

Case "START"

If specialchars(0)<>"" Then

For i=0 To Ubound(specialchars)

If Fieldvalue Like specialchars(i) +"*" Then

Msg="Field '"+ label + "' starts with the following invalid character/ pattern : " + specialchars(i)

Call ShowMsg(Msg, title)

CheckNoInvalidCharsAtEnds = False

Exit Function

End If

Next

End If

If Chars <>"" Then

If Fieldvalue Like "["+Chars+"]*" Then

Msg="Field '"+ label + "' starts with one of the following invalid characters : " + chars

Call ShowMsg(Msg, title)

CheckNoInvalidCharsAtEnds = False

Exit Function

End If

End If

Case "END"

If specialchars(0)<>"" Then

For i=0 To Ubound(specialchars)

If Fieldvalue Like "*"+specialchars(i) Then

Msg="Field '"+ label + "' ends with the following invalid character/ pattern : " + specialchars(i)

Call ShowMsg(Msg, title)

CheckNoInvalidCharsAtEnds = False

Exit Function

End If

Next

End If

If Chars <>"" Then

If Fieldvalue Like "*["+Chars+"]" Then

Msg="Field '"+ label + "' ends with one of the following invalid characters : " + chars

Call ShowMsg(Msg, title)

CheckNoInvalidCharsAtEnds = False

Exit Function

End If

End If

Case "BOTH"

If specialchars(0)<>"" Then

For i=0 To Ubound(specialchars)

If Fieldvalue Like specialchars(i) +"*" Then

Msg="Field '"+ label + "' starts with the following invalid character/ pattern : " + specialchars(i)

Call ShowMsg(Msg, title)

CheckNoInvalidCharsAtEnds = False

Exit Function

End If

Next

End If

If Chars <>"" Then

If Fieldvalue Like "["+Chars+"]*" Then

Msg="Field '"+ label + "' starts with one of the following invalid characters : " + chars

Call ShowMsg(Msg, title)

CheckNoInvalidCharsAtEnds = False

Exit Function

End If

End If

If specialchars(0)<>"" Then

For i=0 To Ubound(specialchars)

If Fieldvalue Like "*"+specialchars(i) Then

Msg="Field '"+ label + "' ends with the following invalid character/ pattern : " + specialchars(i)

Call ShowMsg(Msg, title)

CheckNoInvalidCharsAtEnds = False

Exit Function

End If

Next

End If

If Chars <>"" Then

If Fieldvalue Like "*["+Chars+"]" Then

Msg="Field '"+ label + "' ends with one of the following invalid characters : " + chars

Call ShowMsg(Msg, title)

CheckNoInvalidCharsAtEnds = False

Exit Function

End If

End If

End Select

CheckNoInvalidCharsAtEnds=True

End Function

Function CheckAddressBookforPersonsGroups(ServerPath As String, AddressBookPath As String,Label As String , Field As Notesitem, CheckType As String)

'checks whether field values are present in the groups or people list in the specified addressbook

'3 options to check in 'CheckPersons', 'CheckGroups',CheckPersonsGroups' so will throw error if not in

' persons, groups, persons or groups respectively

Dim add_db As Notesdatabase

Dim Msg As String, Title As String

Set add_db = New NotesDatabase(ServerPath, AddressBookPath)

If Not add_db.isopen Then

Call add_db.open(ServerPath,AddressBookPath)

End If

If Not add_db.isopen Then

Title="Program Error"

Msg="Address Book database is not open - this error encountered while validating field : '"+ Label+"'. Cannot Proceed. "

Call ShowMsg(Msg, Title)

CheckAddressBookforPersonsGroups=False

Exit Function

End If

Dim v As NotesView

Dim v2 As Notesview

Dim vdoc As Notesdocument

Dim n As Notesname ' to convert name to abbreviated format for names fields

Select Case CheckType

Case "CheckPersons"

Set v=add_db.getview("($VIMPeople)")

Forall value In Field.Values

Set n=New Notesname(value)

Set vdoc = v.GetDocumentByKey(n.Abbreviated,True)

If vdoc Is Nothing Then

Msg="The value: '"+ n.Abbreviated + "' in the field '" + Label + "' does not represent a valid User ID."+Chr(13)+"Please use selection button to select the user ID from the Address Book."

Title = "User Entry Check"

Call ShowMsg(Msg, Title)

CheckAddressBookforPersonsGroups = False

Exit Function

End If

End Forall

'CheckAddressBookforPersonsGroups = True

Case "CheckGroups"

Set v=add_db.getview("($VIMGroups)")

Forall value In Field.Values

Set n=New Notesname(value)

Set vdoc = v.GetDocumentByKey(n.Abbreviated,True)

If vdoc Is Nothing Then

Msg="The value: '"+ n.Abbreviated + "' in the field '" + Label + "' does not represent a valid group. "+Chr(13)+"Please use selection button to select the group from the Address Book."

Title = "User Entry Check"

Call ShowMsg(Msg, Title)

CheckAddressBookforPersonsGroups = False

Exit Function

End If

End Forall

'CheckAddressBookforPersonsGroups = True

Case "CheckPersonsGroups"

Set v=add_db.getview("($VIMPeople)")

Set v2=add_db.getview("($VIMGroups)")

Forall value In Field.Values

Set n=New Notesname(value)

Set vdoc = v.GetDocumentByKey(n.Abbreviated,True)

If vdoc Is Nothing Then

Set vdoc = v2.GetDocumentByKey(n.Abbreviated,True)

If vdoc Is Nothing Then

Msg="The value: '"+ n.Abbreviated + "' in the field '" + Label + "' does not represent a valid Group or User. "+Chr(13)+"Please use selection button to select the Group/User from the Address Book."

Title = "User Entry Check"

Call ShowMsg(Msg, Title)

CheckAddressBookforPersonsGroups = False

Exit Function

End If

End If

End Forall

'CheckAddressBookforPersonsGroups = True

End Select

CheckAddressBookforPersonsGroups = True

End Function

Sub ShowMsg(Msg As String, Title As String)

Dim BoxType As Long

BoxType=MB_OK + MB_ICONSTOP

Messagebox Msg , BoxType, Title

End Sub

End Class

7) Some more generic JS functions
rishi sahi | 2/23/2009 11:42:55 PM

------------------------------------------------------------

function windowOpener(url, name, args)

{

args.match(/height=(.*?)(\,)/i);

height = RegExp.$1;

args.match(/width=(.*?)(\,)/i);

width = RegExp.$1;

var left = Math.floor( (screen.width - width) / 2);

var top = Math.floor( (screen.height - height) / 2);

args = args+",left="+left+",top="+top;

if (typeof(popupWin) != "object")

{

popupWin = window.open(url,"name",args);

}

else

{

if (!popupWin.closed)

{

popupWin.location.href = url;

}

else

{

popupWin = window.open(url,"name",args);

}

}

popupWin.focus();

//self.close();

}

---------------------------------------------------------

// Used to Add value in a List Box

function addToList(value,fldList)

{

if(value == "") return false

if(fldList.length ==0) fldList.length +=1

if(fldList[0].text=="") fldList[0].text = value

else

{

fldList.length +=1

fldList[fldList.length-1].text = value

}

}

// Used to select all the values in a List Box before saving

function selectAllListValues(objListFld,objListFldLabelName)

{

if(objListFld.length==0)

{

alert("Please enter atleast one " + objListFldLabelName)

return false;

}

else

{

for (iCount=0;iCount<objListFld.length;iCount++)

{

objListFld.options[iCount].selected=true

}

return true

}

}

----------------------------------------------------------

// Used to check for any duplicate values in the List box

function IsAnyDuplicate(objListFld1,objListFld2,objInputFld1,objInputFld2,skipElementNo)

{

for (iCount=0;iCount<objListFld1.length;iCount++)

{

if (iCount != skipElementNo)

{

if(objListFld1[iCount].text.toLowerCase()==objInputFld1.value.toLowerCase())

{

if(objListFld2[iCount].text.toLowerCase()==objInputFld2.value.toLowerCase())

{

alert("Combination already exists");

return false;

}

}

}

}

return true;

}

-------------------------------------------------------

// used to select all or deselect all the check boxes

// Action is to be false if u want to deselect all the check boxes

function performAction(Action,objCheckBox)

{

// var checkbox = document.forms[0].Check;

var pos=0;

var selectcount = 0;

var selectValue="";

for(i = 0; i < objCheckBox.length; i ++){

objCheckBox.checked = Action

}

}

--------------------------------------------------------

function get_radio_value(objRadio)

{

for (var i=0; i < objRadio.length; i++)

{

if (objRadio.checked)

{

return objRadio.value;

}

}

}

--------------------------------------------------------

//function to check if the currently logged in user is an admin ?

function IsAdmin(objUserRoles)

{

for(var i=0;i<objUserRoles.length;i++){

if(objUserRoles.value == "[Admin]" ) {

var isAdmin = 1

}

}

if(isAdmin == 1){

return true

}

else return false;

}

------------------------------------------------------------

8) I didn’t mean for this thread to become a tip repository...
Andre Guirard | 2/24/2009 9:05:47 AM

Rather, I hoped to encourage people to post to the Designer wiki directly.

9) Doh!
Lars Berntrop-Bos | 2/25/2009 5:40:10 AM

Doh!

 Add a Comment
Subject:
   
Name:
Comment:  (No HTML - Links will be converted if prefixed http://)
 
Remember Me?     Cancel

Search this blog 

Disclaimer 

    About IBM Privacy Contact