Pages

Wednesday, March 31, 2010

Native Javascript String Class Enhancements

This post consist of a cluster of functions that are used to extend the usage of Javascript String Object with custom functions which are added to the native String object's prototype

The native Javascript String Object will be enhanced with the following properties if the scripts in this post are included into your application.

  • strLeft 
  • strLeftBack
  • strRight
  • strRightBack
  • replaceAll
  • toProperCase

/*
 *   @Created :  31st Mar 2010
 *   @Author  :  Karthikeyan A
 *   @Purpose : To mimic the functions @left and StrLeft in formula
 *                    and Lotusscript respectively
 */


String.prototype.strLeft=function(seperator)    {
    var pos=this.indexOf(seperator);
    var result=this.substring(0,pos)
    return result;
}


/*
 *   @Created :  31st Mar 2010
 *   @Author  :  Karthikeyan A
 *   @Purpose : To mimic the functions @leftBack and StrLeftBack in
 *                    formula and Lotusscript respectively
 */


String.prototype.strLeftBack=function(seperator)    {
    var pos=this.lastIndexOf(seperator);
    var result=this.substring(0,pos)
    return result;
}


/*
 *   @Created :  31st Mar 2010
 *   @Author  :  Karthikeyan A
 *   @Purpose : To mimic the functions @right and StrRight in formula
 *                    and Lotusscript respectively
 */


String.prototype.strRight=function(seperator)    {
    var pos=this.indexOf(seperator);
    var result=this.substring(pos+1,this.length)
    return result;
}


/*
 *   @Created :  31st Mar 2010
 *   @Author  :  Karthikeyan A
 *   @Purpose : To mimic the functions @RightBack and StrRightBack in  
 *                      formula and Lotusscript respectively
 */


String.prototype.strRightBack=function(seperator)    {
    var pos=this.lastIndexOf(seperator);
    var result=this.substring(pos+1,this.length)
    return result;
}

/*
 *   @Created :  1st Apr 2010
 *   @Author  :  Karthikeyan A
 *   @Purpose :  To replace all occurences of a substring in a string  
 *                    with an other string
 */

String.prototype.replaceAll = function(stringToFind,stringToReplace){
    var temp = this;
    var index = temp.indexOf(stringToFind);
        while(index != -1){
            temp = temp.replace(stringToFind,stringToReplace);
            index = temp.indexOf(stringToFind);
        }
    return temp;
 }

/*
 *    @Source: http://www.codeproject.com/KB/scripting/propercase.aspx
 */
String.prototype.toProperCase = function()    {
  return this.toLowerCase().replace(/^(.)|\s(.)/g,
      function($1) { return $1.toUpperCase(); });
}

strLeftBack in javascript

String.prototype.strLeftBack=function(seperator)    {
    var pos=this.lastIndexOf(seperator);
    var result=this.substring(0,pos)
    return result;
}

alert("xkrky".strLeftBack('k')); //will alert 'xkr'

function strLeftBack(stringValue,seperator)    {
    var pos=stringValue.lastIndexOf(seperator);
    var result=stringValue.substring(0,pos)
    return result;
}

alert(strLeftBack("xkrky",'k')); //will alert 'xkr'

strLeft in javascript

String.prototype.strLeft=function(seperator)    {
    //stringValue
    var pos=this.indexOf(seperator);
    var result=this.substring(0,pos)
    return result;
}

alert("xkrky".strLeft('k')); // will alert 'x'


function strLeft(stringValue,seperator)    {
    var pos=stringValue.indexOf(seperator);
    var result=stringValue.substring(0,pos)
    return result;
}

alert(strLeft("xkrky",'k')); // will alert 'x'

strRight in javascript

String.prototype.strRight=function(seperator)    {
    //stringValue
    var pos=this.(seperator);
    var result=this.substring(pos+1,this.length)
    return result;
}

alert("xkr".strRight('k'));  // will alert 'r'

function strRightBack(stringValue,seperator)    {
    var pos=stringValue.indexOflastIndexOf(seperator);
    var result=stringValue.substring(pos+1,stringValue.length)
    return result;
}

alert(strRightBack("xkr",'k')); // will alert 'r'

My Ideas to work upon

The following is a list of ideas that I might possibly work on in the near future.

1. Creating a javascript library that would hold most of the String Manipulation commands in the Lotusscript.

2. To Ensure all scripts developed for #1 can be used to extend the native Javascript String class

3. To create a custom javascript class that can be used to parse XMLs in a simpler way

4. To summarize ways that I can use to crash lotus notes

5. To learn more about Javascript blink statement and create a useful tool implementing the same

6. To learn more about z-index and create a useful tool implementing the same

7. A LEI starters guide

8. SQL and Lotus Notes Integration

9. To create a Javascript  logger plugin for Lotus Notes

10. To create XPage logger custom control - i think it is already available in OpenNtf

11. To create a simple API that shall help to work on the new HTML Canvas nodes

12. To create a progress bar that with a nice look and feel as in Windows Vista which would keep track of the Synchronous XMLHTTP Requests 

13. To prepare a documents that will help begineers in lotus notes to quickly understand the concepts

Sizing Backgroung Image Of a Button According To The Size Of The Button

The following is a fragment of html code that will help you to create button like features whose background images will automatically adjust according to the text length.

I honestly believe that u can use it as such, in most of the scenarios. However you may have to tweak the code if your expectation differs

<div style="position:relative; float: left;">
    <div style="z-index: -1">
        <img src="redButton.jpg" width="70px" height="30px">
    </div>

    <div style="position: absolute; top: 5px; left: 15px;">
        <a href="#" target="frTarget" width="10%" style="color:white;font-family:Verdana,Geneva,Arial,Helvetica,sans-serif;font-size:11px;font-weight:bold;text-decoration:none;">Search</a>
    </div>

</div> 

The background image that I have used here is as follows,
The Button that I have got using this code is as follows,

As you can see, the original size of the image has adjusted to the text size...

Hope this helps :)

Tuesday, March 30, 2010

strRightBack in javascript

The following is a function equivalent to lotus script's strRightBack function.

Code
 function strRightBack(stringValue,seperator)    {
    var pos=stringValue.lastIndexOf(seperator);
    var result=stringValue.substring(pos+1,stringValue.length)
    return result;
}

Illustriation
var x="My Name~ My Friend Name";
alert(strRightBack(x,"~"));    // this will alert " My Friend Name"

Following is a code that will help you extend native javascript's String class with this function

Code
String.prototype.strRightBack=function(seperator)    {
    //stringValue
    var pos=this.lastIndexOf(seperator);
    var result=this.substring(pos+1,this.length)
    return result;
}

Illustriation
var x="My Name~ My Friend Name";
alert(x.strRightBack("~"));    // this will alert " My Friend Name"

Wednesday, March 24, 2010

Creating links on XPage which executes server side scripts

Honestly, I dont know if links on XPages created using anchor tags be coded to execute server side scripts. I have tried it but I get exceptions when I attempt to preview my XPage on client or browser.

So here is a work around to do the same.

1.Assume that you want to create a link by the name "My XPage Link"

2. Create a label on the XPage with the label mentioned in #1. Now move to the source code panel in the XPage.

3.Let me assume that the xsp code created for the label that you have just dopped in is <xp:label blah blah blah></xp:label>

4.  Code the label with the server side script on its on click event. and ensure where it works fine.

5. Now locate the label in the source code panel and modify the label's code to suit the following,
<a href='#" class="your style class if any>
  
<xp:label blah blah blah></xp:label>
</a>


6. Now you got the link on the xpage that will execute the server side script.

Use case: It feels a little wearied to convert a label code on its onclick event, and then convert it into a link etc... You may ask y can't we use it as such and apply styles for the label directly.

Remember with links, you can write code that will support- hover, active and visited properties. Especially when u use links with in list then they can help you create beautiful menus etc....

And in these cases direct labels would not be of much use

Hope it makes sense to you :)

Friday, March 19, 2010

Style Overflow for div

If you like to see scrolls inside a div tag when the contents of the same exceed ,
you can mention the following style for that specific div tag,

overflow: auto;
overflow-x:  auto;<- for horizontal scrolling
overflow-y:  auto;<- for vertical scrolling

If you always want to see a scroll then,

overflow: scroll;

overflow-x:  scroll;<- for horizontal scrolling
overflow-y:  scroll;<- for vertical scrolling

If you never like a scroll in your div tag no matter what then,

overflow: hidden;

overflow-x:  hidden;<- for horizontal scrolling
overflow-y:  hidden;<- for vertical scrolling

Hope this helps ;-)

Wednesday, March 17, 2010

History.go(-1) -> redirect to home page if no history found

//This code will work fine in IE and firefox. Have not tested with others

//create a refernce variable which gets the value 0 if the the browser is ie and 1 if its not

var ref=document.all?0:1;

 //if the page has been initiated from an other page then get back to the previous page or if its fresh
//then redirect to home page

if (window.history.length==ref) {    
   location.href="home page url";
} else    {    
   history.go(-1);
}

Tuesday, March 16, 2010

getDesignElementNames (in Java)

/**
     * Method to return the names of a particular set or all design elements from a database
     * depending upon the user's input
     * @param    targetDB-    The database from which the design elements needs to be obtained
     * @param    DESIGN_ELEMENT_TYPE - An integer representation of the design element type
     * @return    String[]
     * @author    karthikeyan_a
     * @since    29-April-2009
     * @see        NotesCollection selectDesigns(Database targetDB,int DESIGN_ELEMENT_TYPE)
     * @see        ArrayList filterHiddenElements(ArrayList designElementNames)
     * @see        ArrayList removeAlias(ArrayList designElementNames)
     * @see        String[] CreateStringArrayFromVector(ArrayList stringVector)
     */   
    public String[] getDesignElementNames(Database targetDB,int DESIGN_ELEMENT_TYPE)    {
       
        if (targetDB==null) return null;

        String noteID=null;
        String noteIDTemp=null;
        Document dsgnDoc=null;
        NoteCollection nc=null;
        ArrayList designElementNames=null;
        //initialize the return value
        String[] designElementNamesString=null;

        try {
            //create an empty note collection
            nc =selectDesigns(targetDB,DESIGN_ELEMENT_TYPE);
            //initiate return value
            designElementNames=new ArrayList();
           
            if (nc.getCount()>0){
                noteID=nc.getFirstNoteID();
                //check if the noteID is neither empty nor null and get the design doc's name associated with the id
                while (noteID!=null && !noteID.equals(""))    {     //start of noteID while       
                    try {       
                        noteIDTemp = noteID;
                        dsgnDoc=targetDB.getDocumentByID(noteIDTemp);
                        //add the names of the design elements into the vector
                        designElementNames.add(dsgnDoc.getItemValueString("$TITLE"));
                        noteID=nc.getNextNoteID(noteID);
                    } catch (NotesException ne)    {
                        ne.printStackTrace();
                    }   
                }    //end of noteID while
            }
        } catch (NotesException e) {
            e.printStackTrace();
        }       
       
        // remove alias names of design elements
        designElementNames=removeAlias(designElementNames);
        //filter hidden design elements
        designElementNames=filterHiddenElements(designElementNames);
        //create a string array of the resultant design elements name
        designElementNamesString=arrayListToStringArray(designElementNames);
       
        //recycle objects
        noteID=null;
        nc=null;
        noteIDTemp=null;
        dsgnDoc=null;
        targetDB=null;
        designElementNames=null;
       
        //return the array of names
        return designElementNamesString;
    }    //end of function::getDesignElementNames

    /**
     * Method to return a particular set or all design elements from a database
     * depending upon the user's input
     * @param    targetDB-    The database from which the design elements needs to be obtained
     * @param    DESIGN_ELEMENT_TYPE - An integer representation of the design element type
     * @return    NoteCollection
     * @author    karthikeyan_a
     * @since    29-April-2009
     */   
    public NoteCollection selectDesigns(Database targetDB,int DESIGN_ELEMENT_TYPE) throws NotesException    {
        NoteCollection nc=null;
        nc = targetDB.createNoteCollection(false);
        if (DESIGN_ELEMENT_TYPE==1)    {
            nc.setSelectForms(true);
        } else if(DESIGN_ELEMENT_TYPE==2)    {
            nc.setSelectViews(true);
            nc.setSelectFolders(true);
        } else    {
            nc=null;
            return nc;
        }
        //build the design document collection of the resultant collection
        nc.buildCollection();
        //return the design collection
        return nc;
    }    //end of function::selectDesigns

    /**
     * Method to remove the strings from a string vector (Vector) which corresponds
     * to the name of an hidden element
     * @param    designElementNames  - an ArrayList with String Objects
     * @return    ArrayList
     * @author    karthikeyan_a
     * @since    29-April-2009
     */
    public ArrayList filterHiddenElements(ArrayList designElementNames)    {
        //if the input param in null then return null
        if (designElementNames==null)return null;
        //initialize the return value
        ArrayList filteredDsgnElements=new ArrayList();
        String dsgnName=null;   
        Object[] buffer=designElementNames.toArray();
        int countItr=0;
        /**
         *    loop through all the string objects in the input vector and remove the string objects
         *    that correspond to the name of an hidden design element
         */
        for(countItr=0;countItr
            dsgnName=buffer[countItr].toString().trim();
            if ( !( (dsgnName.indexOf("(")==0) && (dsgnName.indexOf(")")==(dsgnName.length()-1)) ) )    {
                 filteredDsgnElements.add(dsgnName);
            }   
        }
        //recycle objects
        dsgnName=null;
        designElementNames=null;
       
        return filteredDsgnElements;
    }    //end of function::filterHiddenElements

    /**
     * Method to remove the part of strings from string objects in a string vector (Vector)
     * which correspond to the alias names of the design elements
     * @param    designElementNames  - an ArrayList with String Objects
     * @return    ArrayList
     * @author    Karthikeyan_a
     * @since    29-April-2009
     */   
    public ArrayList removeAlias(ArrayList designElementNames)    {
        //if the input parameter in null then return null
        if (designElementNames==null)return null;
        //initialize the return value
        ArrayList filteredDsgnElements=new ArrayList();       
        String dsgnName=null;       
        Object[] buffer=designElementNames.toArray();
        int countItr=0;
        /**
         *    loop through all the string objects in the input vector and remove the part of stirngs in
         *    string objects that correspond to the alias names of the design elements
         */
        for(countItr=0;countItr
            dsgnName=buffer[countItr].toString().trim();
            if(dsgnName.indexOf("|")==-1)    {
                filteredDsgnElements.add(dsgnName);
            }    else    {
                filteredDsgnElements.add(dsgnName.substring(0, dsgnName.indexOf("|")).trim());
            }   
        }   
        //recycle objects
        dsgnName=null;   
        designElementNames=null;
       
        return filteredDsgnElements;
    }    //end of function::removeAlias

    /**
     * Method to assimilate the contents of a string Array List into a string array
     * @param    arrList  - an array list with string objects
     * @return    String[]
     * @author    karthikeyan_a
     * @since    30-April-2009  
     */
    public String[] arrayListToStringArray(ArrayList arrList){
        String[] strArray=null;
        Object[] elements=arrList.toArray();
        strArray=new String[elements.length];
        int countItr=0;
        for (countItr=0;countItr
            strArray[countItr]=elements[countItr].toString();
        }
        //recycle objects       
        elements=null;
        arrList=null;
       
        return strArray;
    }

    /**
     * Method to obtain a collection of all documents from a specified view in a specified database
     * @param    targetDB  - the database from which the document collection is to be obtained
     * @param    viewName  - the name of the view from which the document collection is to be obtained
     * @return    DocumentCollection
     * @author    karthikeyan_a
     * @since    30-April-2009       
     */
    public DocumentCollection getViewDocuments(Database targetDB, String viewName)    {
        //if any of the input parameters in undefined then return null
        if ((targetDB==null)|| (viewName==null) || (viewName.trim().equals("")))    {
            return null;
        }
        //mark the return value and initialize other variables
        DocumentCollection viewDocs=null;
        Document viewDoc=null;
        ViewEntryCollection viewEntries=null;
        ViewEntry viewEntry=null;
        View chosenView=null;
        try {
            //set the handle for the view mentioned by the view name
            chosenView=targetDB.getView(viewName);
            //if the view handle is not set then return null
            if (chosenView==null)    {
                return null;
            }
           
            //ensure that an empty document collection is created
            Random generator = new Random();
            viewDocs=chosenView.getAllDocumentsByKey(".~^$#$^&~."+generator.toString());
           
            /**
             * loop through all the entries in the view and push their associated
             * documents into the document collection
             */
            viewEntries= chosenView.getAllEntries();
            //get the handle for the first entry in the collection
            viewEntry=viewEntries.getFirstEntry();
            while(viewEntry!=null)    {
                if (viewEntry.isDocument())    {
                    viewDoc=viewEntry.getDocument();
                    /*
                     * If the document concerned with the entry is already present in the
                     * collection then a duplicate exception is thrown. So catch the same and
                     * dont allow that to hurt the process
                     */
                    try {
                        viewDocs.addDocument(viewDoc);
                    }
                    catch (NotesException duplicateException) {
                        //by pass exception
                        duplicateException=null;
                    }
                }
                //push the handle to the next entry in the collection
                viewEntry=viewEntries.getNextEntry(viewEntry);
            }
           
        } catch (NotesException e) {
            e.printStackTrace();
        }
        //return the collection of documents thus obtained
        return viewDocs;
    }

Function to open a CSV file in Java

    public void openCSV(String csvFileName){
        try    {
            String[] commands = {"cmd", "/c", "start", "\"DummyTitle\"",csvFileName};
            Runtime.getRuntime().exec(commands);
        }    catch(Exception e)    {
            e.printStackTrace();
        }
    } //END OF openCSV

Check whether a windows file exists or not (in Java)

    public boolean fileExists(String filePath)    {    //Start of fileExists function
        boolean flagExists=false;
        java.io.File file=new java.io.File(filePath);
        flagExists=file.exists();
        return flagExists;
    }//END of fileExists function

Create a windows folder (in Java)

public void createFolder(String FolderPath)
    { 
        try{
            /* By default the folders will be created in your workspace directory
             * Hence it is advisable to provide a proper path where you can find these directories easily
             */
            (new java.io.File(FolderPath)).mkdirs();
               
        }catch (Exception e){//Catch exception if any
            e.printStackTrace();
        }
    }//END OF createFolder

Check whether a directory exists or not (in java)

public boolean isDirectory(String folder)
    {
        java.io.File directoryName = new java.io.File(folder);
        return directoryName.isDirectory();
    }  //END OF isDirectory

Convert image file Attachment into a image resource

The following functions will help you convert image files attached in documents into image resources in the same database. Probable you may have to remove fragments that you dont want to use.

'**************************************************************
'@Purpose     :      To process file attachments and
'                        convert the same into image resources in the current database
'**************************************************************
Private Function ProcessAttachments(imageName As String,flag As String,imagePath As String) As Boolean
   
    'mark the flow of control getting inside the current function
    ProcessAttachments=False
   
    'declare variables and objects necessary for further manipulations
    Dim session As New notessession
    Dim tempFolderPath As String
    Dim directory As String
    Dim db As NotesDatabase
    Dim tempDoc As NotesDocument
    Dim entity As NotesMimeEntity
    Dim imageSize As Long
   
    'handle errors in case of abrupt termination
    On Error Goto processAttErrHandler
   
   
    'set the handle of the current database
    Set db = session.CurrentDatabase
    directory = tempFolderPath
   
    'create a temporary document to contain the mime entity of the images
    Set tempDoc = db.CreateDocument
    If Not( CreateMIMEEntity(imagePath, tempDoc, entity, imageSize)) Then
        Exit Function
    End If
   
    'create a dxl file of the created mime type
    If Not  CreateDXLFile( imagePath, entity, imageSize) Then
        Exit Function
    End If
   
    'import the created dxl file as image resource
    If Not  ImportDXLFile( imagePath, db) Then
        Exit Function
    End If
    'destroy the file created in the temporary folder
    Kill imagePath

    'mark the flow of control getting out of the current function
    ProcessAttachments=True
    Exit Function
    'log the errors that resulted in abrupt termination
processAttErrHandler:
    Print "Error ***" & Error & "*** occured on line ***" & Cstr(Erl) & "*** with error number ***"   _
    & Cstr(Err) & "*** in Method ""ProcessAttachments"" in script Library ""lsLookAndFeel"""
  
    Exit Function
End Function   

'****************************************************************
'@Created      :      2008/09/12
'@Purpose     :      To create a dxl file that resembles the dxl of design elements in Image resources
'                        provided the mime type of an image file   
'****************************************************************
Private Function CreateDXLFile( imagePath As String, entity As NotesMimeEntity, imageSize As Long)
   
    'mark the flow of control getting inside the current function
    CreateDXLFile=False
   
    'declare all variables and objects necessary for furhter manipulation
    Dim session As New notessession
    Dim stream As NotesStream
    Dim directory As String
    Dim imageName As String
   
    'initiation
    'handle errors in case of abrupt termination
    On Error Goto errHandler
   
    If Instr(imagePath, "\") <> 0 Then
        directory = Strleftback(imagePath, "\") & "\"
        imageName = Strrightback(imagePath, "\")
    Else
        directory = Strleftback(imagePath, "/") & "/"
        imageName = Strrightback(imagePath, "/")
    End If
   
    'create a stream
    Set stream = session.CreateStream
    If Not stream.Open(directory & Strleftback(imageName, ".") & ".dxl", "ISO-8859-1") Then
        Error 1405, "Cannot create file " & directory & Strleftback(imageName, ".") & ".dxl on the server."
    End If
    Call stream.WriteText({})
   
    Call stream.WriteText({
    Call stream.WriteText({ noreplace='true' publicaccess='false' designerversion='7'>})
    If Right(Lcase(imageName), 4) = ".gif" Then
        Call stream.WriteText({})
        Call stream.WriteText(entity.ContentAsText)
        Call stream.WriteText({
})
    Else
        Call stream.WriteText({})
        Call stream.WriteText(entity.ContentAsText)
        Call stream.WriteText({
})
    End If
    Call stream.WriteText({})
    Call stream.WriteText(Cstr(imageSize) & {
})
    Call stream.WriteText({})
    If Right(Lcase(imageName), 4) = ".gif" Then
        Call stream.WriteText({image/gif})
    Else
        Call stream.WriteText({image/jpeg})
    End If
    Call stream.WriteText({
})
    Call stream.WriteText({})
    Call stream.WriteText(Format$(Now, "YYYYMMDD") & "T" & Format$(Now, "HHMMSS") & ",00-00")
    Call stream.WriteText({
})
    Call stream.WriteText({
})
    Call stream.Close

    'mark the flow of control movingout of the current function
    CreateDXLFile=True
   
    Exit Function
    'log the error that resulted in abrupt termination
errHandler:
    Print "Error ***" & Error & "*** occured on line ***" & Cstr(Erl) & "*** with error number ***"   _
    & Cstr(Err) & "*** in Method ""CreateDXLFile"" in script Library ""lsLookAndFeel"""

    Exit Function
End Function

'****************************************************************
'@Created      :      2008/09/12
'@Purpose     :      To create mime content of an image file
'****************************************************************
Function  CreateMIMEEntity( imagePath As String, tempDoc As  NotesDocument, entity As  NotesMimeEntity, imageSize As Long)As Boolean
   
    'mark the flow of control getting inside the current function
    CreateMIMEEntity=False
   
    'declare variables and objects necessary for further manipulation
    Dim session As New notessession
    Dim stream As NotesStream
   
    'initiation
    'handler errors in case of abrupt termination
    On Error Goto mimeErrHandler
   
    'create a stream object
    Set stream = session.CreateStream
    If Not stream.Open(imagePath) Then
        Error 1404, "Cannot open file " & imagePath & " for processing."
        Exit Function
    End If
   
    imageSize = stream.Bytes
   
    Call tempDoc.ReplaceItemValue("Form", "Temporary Document")
    Set entity = tempDoc.CreateMIMEEntity
    If Right(Lcase(imagePath), 4) = ".gif" Then
        Call entity.SetContentFromBytes(stream, "image/gif", ENC_NONE)
    Else
        Call entity.SetContentFromBytes(stream, "image/jpeg", ENC_NONE)
    End If
    Call entity.EncodeContent(ENC_BASE64)
    Call stream.Close
    'mark the flow of control moving out of the current function
    CreateMIMEEntity=True
    Exit Function
mimeErrHandler:
    Print "Error ***" & Error & "*** occured on line ***" & Cstr(Erl) & "*** with error number ***"   _
    & Cstr(Err) & "*** in Method ""CreateMIMEEntity"" in script Library ""lsLookAndFeel"""   
    Exit Function
End Function

'****************************************************************
'@Created      :      2008/09/12
'@Purpose     :      To import a dxl file in to the current database
'****************************************************************
Private Function ImportDXLFile( imagePath As String, db As NotesDatabase) As Boolean
   
    'mark the flow of control getting inside the current function
    ImportDXLFile=False
   
    'declaring variables and objects necessary for further manipulation
    Dim session As New notessession
    Dim stream As NotesStream
    Dim importer As NotesDXLImporter
    Dim dxlPath As String
   
    'initiation
    'handle errors in case of abrupt termination
    On Error Goto errHandler
   
    dxlPath = Strleftback(imagePath, ".") & ".dxl"
   
    Set stream = session.CreateStream
    If Not stream.Open(dxlPath, "ISO-8859-1") Then
        Error 1406, "Cannot open file " & dxlPath & " after it was created."
    End If
   
    Set importer = session.CreateDXLImporter(stream, db)
    importer.ReplaceDBProperties = False
    importer.ReplicaRequiredForReplaceOrUpdate = False
    importer.DesignImportOption = DXLIMPORTOPTION_REPLACE_ELSE_CREATE
    Call importer.Process
    Call stream.Close

    'mark the flow of control movingout of the current function
    ImportDXLFile=True
   
    Exit Function
    'log the errors that resulted in abrupt termination
errHandler:
    Print "Error ***" & Error & "*** occured on line ***" & Cstr(Erl) & "*** with error number ***"   _
    & Cstr(Err) & "*** in Method ""ImportDXLFile"" in script Library ""lsLookAndFeel"""


    Exit Function
End Function

Tuesday, March 9, 2010

Function to Enable or Disable a scheduled agent (#2) - Added param

Function scheduledAgentSetEnabled(enable As Boolean, targetDB As NotesDatabase,scheduledAgentName As String) As Boolean
'***************************************************************
'@Purpose    :    To enable or disable a scheduled agent in target database
'@Param       :     enable - boolean, true if agent is to be enabled and false otherwise
'@Param       :     targetDB - NotesDatabase, database in which the agents have to be processed
'@Param       :     scheduledAgentName - String, name of the agent on which the operation has to made
'@Name        :    scheduledAgentSetEnabled
'@Author        :    Karthikeyan A
'@Return        :    Boolean. True if the operation completes successfully and false other wise
'***************************************************************
   
    'mark the flow of control getting inside the current function
    scheduledAgentSetEnabled=False
   
    'constants used in this function
    Const TITLE_ITEM="$Title"
    Const ASSIST_FLAG_ITEM="$AssistFlags"
   
    'declare variables and objects necessary for further manipulation
    Dim nc As notesnotecollection
    Dim desDoc As NotesDocument
    Dim noteID As String
    Dim assistFlags As String
   
    'handle errors in case of abrupt termination
    On Error Goto errHandler
    If Not targetDB.IsOpen Then
        Exit Function
    End If
   
    'get the notes collection of all the agents in the current database
    Set nc=targetDB.CreateNoteCollection(False)
    nc.SelectAgents=True
    Call nc.BuildCollection()
    'get the first noteid from the notes design document collection
    noteID=nc.GetFirstNoteId
    'loop through the design document collection using the noteIDs and enable or diable the agent whose title matches
    'input parameter- agent name
    Set desDoc=targetDB.GetDocumentByID(noteID)
    While Not desDoc Is Nothing       
        If Ucase(desDoc.GetItemValue(TITLE_ITEM)(0))=Ucase(scheduledAgentName) Then
            assistFlags=desDoc.GetItemValue(ASSIST_FLAG_ITEM)(0)
           
            If enable Then
                If Not Instr(Ucase(assistFlags),"E") Then
                    assistFlags=assistFlags & "E"
                End If
            Else
                While Instr(Ucase(assistFlags),"E")
                    assistFlags=Replace(Ucase(assistFlags),"E","")               
                Wend
            End If   
            Call desDoc.ReplaceItemValue(ASSIST_FLAG_ITEM,assistFlags)       
            Call desDoc.Save(True,False)
           
        End If
        noteID=nc.GetNextNoteId(noteID)
        Set desDoc=targetDB.GetDocumentByID(noteID)
    Wend
   
        'mark the flow of control moving out of the current function
    scheduledAgentSetEnabled=True
   
    Exit Function
    'inform the user regarding the errors that resulted in abrupt termination
errHandler:
    If Err=4270 Then Exit Function   
    Msgbox "Error ***" & Error & "*** occured in line ***" & Cstr(Erl) & "*** with error number ***" & Cstr(Err) & "*** in agent scheduledAgentSetEnabled(enable As Boolean, agentName As String)"
    Print "Error ***" & Error & "*** occured in line ***" & Cstr(Erl) & "*** with error number ***" & Cstr(Err) & "*** in agent scheduledAgentSetEnabled(enable As Boolean, agentName As String)"
    Exit Function
End Function

Query String in XPages

Assuming that you pass parameters to xpages as indicated in the following link....

http://xyz.com/abc.xsp?solo="polo"

To retrieve or extract parameters.

var externalContext=facesContext.getExternalContext();
var servletRequest=externalContext.getRequest();
var queryString=servletRequest.getQueryString();
return queryString

it will return solo=polo.

You can also perform the following operation
.

var exCon = facesContext.getExternalContext();
var request = exCon.getRequest(); // This is the actual HTTP servlet request...
var paramValue = request.getParameter("paramName");
return paramValue;

it will return polo.

Function to Enable or Disable a scheduled agent

Function scheduledAgentSetEnabled(enable As Boolean, scheduledAgentName As String) As Boolean
'***************************************************************

'@Purpose    :    To enable or disable a scheduled agent
'@Name        :    scheduledAgentSetEnabled
'@Author        :    Karthikeyan A
'@Return        :    Boolean. True if the operation completes successfully and false other wise
'***************************************************************
   
    'mark the flow of control getting inside the current function
    scheduledAgentSetEnabled=False
   
    'constants used in this function
    Const TITLE_ITEM="$Title"
    Const ASSIST_FLAG_ITEM="$AssistFlags"
   
    'declare variables and objects necessary for further manipulation
    Dim session As New NotesSession
    Dim currDB As notesdatabase
    Dim nc As notesnotecollection
    Dim desDoc As NotesDocument
    Dim noteID As String
    Dim assistFlags As String
   
    'handle errors in case of abrupt termination
    On Error Goto errHandler
    'set the handle for the current database
    Set currDB=session.CurrentDatabase
    'get the notes collection of all the agents in the current database
    Set nc=currDB.CreateNoteCollection(False)
    nc.SelectAgents=True
    Call nc.BuildCollection()
    'get the first noteid from the notes design document collection
    noteID=nc.GetFirstNoteId
    'loop through the design document collection using the noteIDs and enable or diable the agent whose title matches
    'input parameter- agent name
    Set desDoc=currDB.GetDocumentByID(noteID)
    While Not desDoc Is Nothing       
        If Ucase(desDoc.GetItemValue(TITLE_ITEM)(0))=Ucase(scheduledAgentName) Then
            assistFlags=desDoc.GetItemValue(ASSIST_FLAG_ITEM)(0)
           
            If enable Then
                If Not Instr(Ucase(assistFlags),"E") Then
                    assistFlags=assistFlags & "E"
                End If
            Else
                While Instr(Ucase(assistFlags),"E")
                    assistFlags=Replace(Ucase(assistFlags),"E","")               
                Wend
            End If   
            Call desDoc.ReplaceItemValue(ASSIST_FLAG_ITEM,assistFlags)       
            Call desDoc.Save(True,False)
           
        End If
        noteID=nc.GetNextNoteId(noteID)
        Set desDoc=currDB.GetDocumentByID(noteID)
    Wend
   
        'mark the flow of control moving out of the current function
    scheduledAgentSetEnabled=True
   
    Exit Function
    'inform the user regarding the errors that resulted in abrupt termination
errHandler:
    If Err=4270 Then Exit Function   
    Msgbox "Error ***" & Error & "*** occured in line ***" & Cstr(Erl) & "*** with error number ***" & Cstr(Err) & "*** in agent scheduledAgentSetEnabled(enable As Boolean, agentName As String)"
    Print "Error ***" & Error & "*** occured in line ***" & Cstr(Erl) & "*** with error number ***" & Cstr(Err) & "*** in agent scheduledAgentSetEnabled(enable As Boolean, agentName As String)"
    Exit Function
End Function

Friday, March 5, 2010

My Unanswered questions in XPages

 Assume that you have a Edit box control named "MyXSPField" on a XPage.
Now If I want to retrieve the value of the same on a button click, I can do it in the following ways,
 i,
   var fieldValue=document.getElementById("#{id:MyXSPField}").value

 ii,
   var computedId= "#{id:MyXSPField}";
   var fieldValue=document.getElementById(computedId).value

But when I attempt to split the parameter as follows, no matter what ever way that I try, which makes sense to me, the attempt fails to give me the field value
 i,
   var editControlName="MyXSPField";
   var computedId= "#{id:"+editControlName+"}";
   var fieldValue=document.getElementById(computedId).value


 ii,
   var editControlName="MyXSPField";
   var fieldValue=document.getElementById("# 
   {id:"+editControlName+"}").value

 iii,
   var editControlName="MyXSPField";
   eval ('var fieldValue=document.getElementById("#
   {id:"+editControlName+"}").value');

 iv,
   var editControlName="MyXSPField";
   eval ('var fieldValue=document.getElementById("# 
   {id:"'+editControlName+'"}").value');

 v,
   I have tried replacing # by $ in all of the above mentioned attempts

Yes.. All of these attempts fail. I understand that I am breaking the EL (expression language) and that might be the issue....

But is there a way to instruct the XPage compiler to complile the dynamically created EL, 'cos this is a real worrying issue







Wednesday, March 3, 2010

Getting an xpage component's id programatically when the same is clicked

Create an XPage.

Drag and Drop a button Control on to it and give the button a name and a label

Now on the events tab of the button, in the onclick event, select client side and type in the following code

var currId = thisEvent.target.id;
alert(currId);

Now and preview your XPage and click the button.

The result would be an alert box with the id of the button control that you have mentioned in the XPage. Again it will not be exactly the same but will be along with a pattern generated by the XPage and the same will be consistent.

"onload" Event in XPages

Developers who are experienced in traditional web applications in Lotus Notes it becomes a nightmare when they start to work with XPages.

One of the initial issues that I faced is - the struggle to gain control of the onload event in the XPages as the available events in the XPages like the afterPageLoad etc... only allows Serverside script and it becomes expensive to hit the server every time in terms of application's performance.

The following code fragment shall help people who face this issue, and will help them gain access to the XPage's onload event.

<script language="Javascript">
XSP.addOnLoad(alert('I am in XPage onload'));
</script></b>

Add this snippet of code in the Source panel and ensure that it is not nested inside any other existing tags.An ideal place would beneath the lines which say (sort of),

<?xml version="1.0" encoding="UTF-8"?>
<xp:view xmlns:xp="http://www.ibm.com/xsp/core">
 

Now after performing the above step, preview your XPage and voila, you will get the alert saying "I am in XPage onload"

Tuesday, March 2, 2010

Remote Desktop from command prompt

Open up the command prompt and type in the following command.

"mstsc" and press enter. This will bring up the remote desktop connection wizrd asking for the ip of the machine to which you want to remote to.

This is an alternate way for doing the following
Start-> All Programs-> Accessories-> Remote Desktop Connection

Also you can type the same in Run Dialog
Start-> Run-> mstsc and hit enter