quinta-feira, 22 de novembro de 2012

Converter campo Notes Color para RGB


1º Cria o campo do tipo COLOR, o nome vai ser 'campoColor';
2º Cria um campo computado, do tipo NUMBER com a opção 'Allow multiple values' com a formula abaixo:

t_txtRed := @Middle(campoColor; 2; 2);
t_txtGreen := @Middle(campoColor; 4; 2);
t_txtBlue := @Middle(campoColor ; 6; 2);

t_txtHexa := "0":"1":"2":"3":"4":"5":"6":"7":"8":"9":"A":"B":"C":"D":"E":"F";
t_txtDec := "0":"1":"2":"3":"4":"5":"6":"7":"8":"9":"10":"11":"12":"13":"14":"15";

t_cRed := @TextToNumber(@Replace(@Left(t_txtRed ; 1) ; t_txtHexa ; t_txtDec)) * 16 + @TextToNumber(@Replace(@right(t_txtRed ; 1) ; t_txtHexa ; t_txtDec));

t_cGreen := @TextToNumber(@Replace(@Left(t_txtGreen ; 1) ; t_txtHexa ; t_txtDec)) * 16 + @TextToNumber(@Replace(@right(t_txtGreen ; 1) ; t_txtHexa ; t_txtDec));

t_cBlue := @TextToNumber(@Replace(@Left(t_txtBlue ; 1) ; t_txtHexa ; t_txtDec)) * 16 + @TextToNumber(@Replace(@right(t_txtBlue ; 1) ; t_txtHexa ; t_txtDec));

t_cRed : t_cGreen : t_cBlue

3º Agora basta definir com a classe 'NotesColorObject':


Dim session = new NotesSession
Dim colorObject As NotesColorObject
Set colorObject = Session.CreateColorObject

 
      Call colorObject.SetRGB(doc.campoColor(0),doc.campoColor(1),doc.campoColor(2))

Converter Hexadeximal para Decimal


fonte: http://www.vbweb.com.br/dicas_visual.asp?Codigo=2086&Classificacao=4


Function Hex2Dec( hexadecimal As String)

Dim n As Long
Dim aux As Long
Dim  valores As String
Dim decimal As Long
Dim fator As Long

valores = "0123456789ABCDEF"
n = 1
decimal = 0
For n = Len( hexadecimal ) To 1 Step -1
fator= 16 ^ ( Len( hexadecimal ) - n )
aux = Instr( valores, Mid( hexadecimal, n, 1 ) ) - 1
decimal = decimal + ( aux * fator )
Next

Hex2Dec = decimal

Exit Function
End Function

segunda-feira, 17 de setembro de 2012

Replace a string in the documents in a Lotus database


Ref: http://www.lucazanini.eu/2011/lotus/replace-a-string-in-the-documents-in-a-lotus-database/?lang=en

by LUCA ZANINI
I think it might be useful to replace each occurrence of a string in all the documents or in the selected documents in a Lotus database, especially when you want to replace a user in the fields author/reader.
The use of roles or groups should be recommended to set the access to the documents, but there may be cases where the user’s name has been used as in Lotus Workflow projects.

This code only works for fields of type text, number, name, author, reader and date.

The meaning of the constants in the code:

ONLYSELECTEDDOCUMENTS : True to process only selected documents, False to process all documents in the database
FROMSTRING : string to replace
TOSTRING : new string
WHOLE_WORD : True if you want to replace only if the field or a its element in the case of multivalue field is exactly equal to FROMSTRING, False if you want to replace even if the string FROMSTRING is a substring of field or a its element in the case of multivalue field
EXCLUDEDOLLARFIELDS : True to exclude fields whose names begin with “$” symbol like $Revisions or $UpdatedBy, False to include these fields
EXCLUDEFIELDS : list of fields not to be replaced in the format of “Field1;Field2;Field3?
INCLUDEONLYFIELDS : list of fields only to be replaced in the format of “Field1;Field2;Field3?
Below there is the code to insert in a LotusScript agent, tested on Lotus Notes 8.5.2

Option Public
Option Declare

Sub Initialize()

    Dim s As New NotesSession
    Dim db As NotesDatabase
    Dim dc As NotesDocumentCollection
    Dim doc As NotesDocument
    Dim value As Variant
    Dim formula As String
    Dim FROMSTRING As String
    Dim TOSTRING As String
    Dim i As Integer
    Dim newValue As Variant
    Dim replaceValue As Variant
    Dim modifiedDocument As Boolean
    Dim modifiedField As Boolean
    Dim itemType As Integer
    Dim replaceVariant As Variant
    Dim ONLYSELECTEDDOCUMENTS As Boolean
    Dim WHOLE_WORD As Boolean
    Dim EXCLUDEDOLLARFIELDS As Boolean
    Dim EXCLUDEFIELDS As string
    Dim excludeField As Variant
    Dim INCLUDEONLYFIELDS As String
    Dim includeOnlyField As Variant
    Dim foundField As Boolean
    Dim newDateTime As NotesDateTime
   
    ONLYSELECTEDDOCUMENTS = True
    WHOLE_WORD = False
    EXCLUDEDOLLARFIELDS = True
    EXCLUDEFIELDS = "" ' "Field1;Field2..."
    INCLUDEONLYFIELDS = "" ' "Field1;Field2..."
    FROMSTRING ="aaa"
    TOSTRING = "zzz"

    Set db = s.Currentdatabase
    If ONLYSELECTEDDOCUMENTS Then
        Set dc = db.Unprocesseddocuments
    Else
        Set dc = db.Alldocuments
    End If
   
    Set doc = dc.Getfirstdocument()
    Do While Not(doc Is nothing)
       
        modifiedDocument = False
       
        ForAll item In doc.Items
           
            If not(item.type=1280 Or item.type=768 Or item.type=1074 Or item.type=1075 Or item.type=1076 Or item.type=1024) Then
                GoTo nextItem
            End If
           
            If EXCLUDEDOLLARFIELDS Then
                If (Left(item.name, 1)="$") Then
                    GoTo nextItem
                End If
            End If
           
            If (EXCLUDEFIELDS<>"") Then
                excludeField = Split(EXCLUDEFIELDS, ";")
                ForAll v In  excludeField
                    If (Trim(v)=item.name) Then
                        GoTo nextItem
                    End If
                End ForAll            
            End If

            If (INCLUDEONLYFIELDS<>"") Then
                includeOnlyField = Split(INCLUDEONLYFIELDS, ";")
                foundField = false
                ForAll v In  includeOnlyField
                    If (Trim(v)=item.name) Then
                        foundField = True
                    Exit forall
                    End If
                End ForAll
                If Not(foundField) Then
                    Print item.name
                    GoTo nextItem
                End If        
            End If
           
            i = 0
            modifiedField = False
            value = item.values
            newValue = ""
            itemType = item.Type
            replaceVariant = value
           
            If (IsArray(value)) then
                ForAll v In value
                   
                    formula = ""
                   
                    If WHOLE_WORD then
                        If (CStr(v)=FROMSTRING) Then
                            formula = |@ReplaceSubstring("|+CStr(v)+|";"|+FROMSTRING+|";"|+TOSTRING+|")|
                        End If
                    Else
                        formula = |@ReplaceSubstring("|+CStr(v)+|";"|+FROMSTRING+|";"|+TOSTRING+|")|      
                    End If
                   
                    If (formula<>"") then
                        replaceValue = Evaluate(formula, doc)
                       
                        If (CStr(v)<>CStr(replaceValue(0))) Then
                            modifiedField = True
                        End If

                        If (itemType=1280) Then ' TEXT
                            replaceVariant(i) = CStr(replaceValue(0))
                        ElseIf (itemType=768) Then ' NUMBERS
                            replaceVariant(i) = CDbl(replaceValue(0))
                        ElseIf (itemType=1074) Then ' NAMES
                            replaceVariant(i) = replaceValue(0)
                        ElseIf (itemType=1075) Then ' READERS
                            replaceVariant(i) = replaceValue(0)
                        ElseIf (itemType=1076) Then ' AUTHORS
                            replaceVariant(i) = replaceValue(0)
                        ElseIf (itemType=1024) Then ' DATETIMES
                            replaceVariant(i) = replaceValue(0)
                        End If
                    End If

                    i = i + 1
                End ForAll
            End If
           
            If modifiedField Then
                If (itemType=1280) Then ' TEXT
                    newValue = replaceVariant
                    Call doc.Replaceitemvalue(item.name, newValue)
                ElseIf (itemType=768) Then ' NUMBERS
                    newValue = replaceVariant
                    Call doc.Replaceitemvalue(item.name, newValue)
                ElseIf (itemType=1074) Then ' NAMES
                    newValue = replaceVariant
                    Call doc.Replaceitemvalue(item.name, newValue)
                ElseIf (itemType=1075) Then ' READERS
                    newValue = replaceVariant
                    Call doc.Replaceitemvalue(item.name, newValue)
                ElseIf (itemType=1076) Then ' AUTHORS
                    newValue = replaceVariant
                    Call doc.Replaceitemvalue(item.name, newValue)
                ElseIf (itemType=1024) Then ' DATETIMES
                    Set newDateTime = New NotesDateTime(replaceVariant(0))
                    Call doc.Replaceitemvalue(item.name, newDateTime)
                End If
               
                modifiedDocument = True
            End If
           
nextItem:  
        End forall
       
        If modifiedDocument then
            Call doc.save(True, True, False)
        End If
       
        Set doc = dc.Getnextdocument(doc)
    Loop

End Sub


sexta-feira, 14 de setembro de 2012

Alteração de documento(s) a partir de uma Action no ToolsBar do Notes



1º Primeiro cria uma base local (no data). "Ex.: base.nsf"

2º Criar um formulário nesta base: Ex.: "fo_formAcao"

3º Criar a action no ToolsBar do Notes
@Command([Compose]; "":" base .nsf" ; " fo_formAcao ");

4º No Declarations adicionar o código: Dim ws As NotesUiWorksPace
Obs.: Essa variável deve estar não pode ser declarada na rotina que irá executar o código, a mesma deve ser global.

5º  Adicione no QueryOpen o código abaixo:


Sub Queryopen(Source As Notesuidocument, Mode As Integer, Isnewdoc As Variant, Continue As Variant)
On Error Goto trataerro

Set ws = New NotesUIWorkspace

Dim db As NotesDatabase

If( Not ws.CurrentView Is Nothing) Then
Set db = ws.CurrentView.View.Parent
Else
Msgbox "Visão corrente não encontrada!",16,"Operação Cancelada!"
Continue = False
Exit Sub
End If

If Not db Is Nothing Then
If  Not db.IsOpen Then
Call db.Open("","")
If Not db.IsOpen Then
Call db.Open(ws.CurrentView.View.Parent.Server,ws.CurrentView.View.Parent.filepath)
If Not db.IsOpen Then
Msgbox "Não foi possível setar a base",16,"Operação Cancelada!"
Continue = False
Exit Sub
End If
End If
End If

Dim col As NotesDocumentCollection
Set col = ws.CurrentView.Documents

If Not col Is Nothing Then
If col.Count > 0 Then

'EXECUTA O CÓDIGO NO(S) DOCUMENTO(S) SELECIONADO(S)

Msgbox "Alteração OK",48,"OK"
Else
Msgbox "Nenhum documento selecionado!",16,"Operação Cancelada"
End If
Else
Msgbox "Coleção não definida!",16,"Operação Cancelada"
End If
Continue = False
Else
Msgbox " Erro, base não setada!",16,"Operação CAncelada"
End If
Continue = False
Exit Sub

trataerro:
Msgbox " Erro na linha " & Cstr(Erl) & " do tipo " & Cstr(Err) & " " & Cstr(Erl),16,"Operação CAncelada"
Continue = False
Exit Sub
End Sub




segunda-feira, 9 de julho de 2012

How to send HTML formatted mail messages using a LotusScript agent

REF: http://www-01.ibm.com/support/docview.wss?uid=swg21098323

Question

How can you send HTML formatted mail messages using LotusScript?
Prior to the expansion of the NotesMIMEEntity class in Lotus Notes and Lotus Domino Designer 6.x, it was not possible to use a scheduled agent to send mail messages with HTML formatting. When you added HTML code to the body of a mail message, even setting the PassThruHTML NotesRichTextStyle property, Notes sent only the raw HTML code to the recipient without rendering it into HTML.

Answer

New methods and properties in the NotesMIMEEntity class, as well as the addition of the NotesStream class, make it possible to send HTML formatted mail directly from a scheduled agent in Notes/Domino 6.x and later. This functionality is useful for sending HTML newsletters or for responding to users who submit information into a mail-in database. You can create an agent that sends an HTML file stored on the local file system or that creates the HTML dynamically. The agents below demonstrate this functionality.
IMPORTANT NOTE: The following is a sample script, provided only to illustrate one way to approach this issue. In order for this example to perform as intended, the script must be laid out exactly as indicated below. IBM Support will not be able to customize this script for a customer's own configuration.


Using a local HTML file

The following agent sends an HTML file from the local file system (server's hard drive):

Dim s As New NotesSession
Dim db As NotesDatabase
Dim doc As NotesDocument
Dim body As NotesMIMEEntity
Dim header As NotesMIMEHeader
Dim stream As NotesStream
Set db = s.CurrentDatabase
Set stream = s.CreateStream
s.ConvertMIME = False ' Do not convert MIME to rich text
Set doc = db.CreateDocument
doc.Form = "Memo"
Set body = doc.CreateMIMEEntity
Set header = body.CreateHeader("Subject")
Call header.SetHeaderVal("HTML message") ' this is the subject
Set header = body.CreateHeader("SendTo")
Call header.SetHeaderVal("user@us.ibm.com")
'The file named below is located on the Domino server because the scheduled agent runs on the Domino server
Call stream.Open("c:\newsletter.html")
Call body.SetContentFromText(stream, "text/HTML;charset=UTF-8", ENC_IDENTITY_7BIT)
Call doc.Send(False)
s.ConvertMIME = True ' Restore conversion



Using dynamic HTML content
    The following agent builds an HTML file dynamically. It is also possible to add dynamic content into the HTML as demonstrated.

    Notice that the stream.WriteText method uses the pipe ( | ) string delimiter rather than quotation marks. This usage makes it easier to place quotation marks directly into the string. Also, the WriteText lines are separated for easier reading, but they could be concatenated together.

    The example code contains EOL_CRLF characters to make the message source properly formatted. This is important because many spam filters block improperly formatted MIME messages.

    Dim s As New NotesSession
    Dim db As NotesDatabase
    Dim doc As NotesDocument
    Dim body As NotesMIMEEntity
    Dim header As NotesMIMEHeader
    Dim stream As NotesStream
    Set db = s.CurrentDatabase
    Set stream = s.CreateStream
    s.ConvertMIME = False ' Do not convert MIME to rich text
    Set doc = db.CreateDocument
    doc.Form = "Memo"
    Set body = doc.CreateMIMEEntity
    Set header = body.CreateHeader("Subject")
    Call header.SetHeaderVal("HTML message")
    Set header = body.CreateHeader("To")
    Call header.SetHeaderVal("user@us.ibm.com")
    Call stream.writetext(||)
    Call stream.writetext(||)
    Call stream.writetext(||)
    Call stream.writetext(||)
    Call stream.writetext(||)
    Call stream.writetext(||)
    Call stream.writetext(|
    Hello World!
    |)
    user$ = s.CommonUserName 'if scheduled agent this returns the name of the server
    'Below uses the ampersand (&) to concatenate user$
    Call stream.writetext(|
    | & user$ &||)
    Call stream.writetext(||)
    Call stream.writetext(||)
    Call body.SetContentFromText(stream, "text/HTML;charset=UTF-8", ENC_IDENTITY_7BIT)
    Call doc.Send(False)
    s.ConvertMIME = True ' Restore conversion - very important



    Using a prompt for subject, name(s), and HTML file

    Sub Initialize
    Dim uiwk As New NotesUIWorkspace
    Dim s As New NotesSession
    Dim db As NotesDatabase
    Dim doc As NotesDocument
    Dim body As NotesMIMEEntity
    Dim header As NotesMIMEHeader
    Dim stream As NotesStream
    Dim vname As Variant
    Dim vfile As Variant
    Dim ssubject As String
    Dim snames As String
    Dim sfile As String

    ssubject = CStr(InputBox("Please enter a subject","Subject input dialog"))
    vname = uiwk.PickListStrings(PICKLIST_NAMES,True)
    vfile = uiwk.OpenFileDialog(False,"Please select the HTML file to import")
    ForAll names In vname
    Set db = s.CurrentDatabase
    Set stream = s.CreateStream
    s.ConvertMIME = False ' Do not convert MIME to rich text
    Set doc = db.CreateDocument
    doc.Form = "Memo"
    Set body = doc.CreateMIMEEntity
    Set header = body.CreateHeader("Subject")
    Call stream.Open(vfile(0))
    Call body.SetContentFromText(stream, "text/HTML;charset=UTF-8", ENC_IDENTITY_7BIT)
    Call header.SetHeaderVal(ssubject) ' this is the subject
    Set header = body.CreateHeader("SendTo") 'alternatively you can use "BlindCopyTo" instead of "SendTo"
    Call header.SetHeaderVal(names)
    Call doc.Send(False)
    s.ConvertMIME = True ' Restore conversion
    End ForAll
    End Sub

    sexta-feira, 6 de julho de 2012

    Botões / ações ( actions) para ajudar no desenvolvimento




    Caminho
    Base:= @Subset(@DbName;-1);
    Server:= @Name([CN];@Subset(@DbName;1));
    @Prompt([OkCancelEdit];"Caminho";"Caminho";Server + "\\" + Base)

    AtualizaDocSelecionado
    @Command([ToolsRefreshSelectedDocs])

    Bt Ninja
    $campo:=@Prompt([OkCancelList];"Super Mega Button";"Selecione o campo que será alterado:";"";@DocFields);
    $perg01:=@Text(@Prompt([YesNo];"Super Mega Button";"O valor do campo " + $campo + " é numérico?"));

    @If(
    $perg01="1";
    @Do(
    $valor_num:=@Prompt([OkCancelEdit];"Super Mega Button";"Informe o valor numérico do campo " + $campo +":";"");
    @SetField($campo;@TextToNumber($valor_num))
    );
    @Do(
    $perg02:=@Text(@Prompt([YesNo];"Super Mega Button";"O valor do campo " + $campo + " é data (formato: dd/mm/aaaa)?"));
    @If(
    $perg02="1";
    @Do(
    $valor_dia:=@Prompt([OkCancelEdit];"Super Mega Button";"Informe o valor do dia (2 dígitos) para o campo " + $campo +":";"");
    $valor_mes:=@Prompt([OkCancelEdit];"Super Mega Button";"Informe o valor do mês (2 dígitos) para o campo " + $campo +":";"");
    $valor_ano:= @Prompt([OkCancelEdit];"Super Mega Button";"Informe o valor do ano (4 dígitos) para o campo " + $campo +":";"");
    $valor_data:=@Date(@TextToNumber($valor_ano);@TextToNumber($valor_mes);@TextToNumber($valor_dia));
    @SetField($campo;$valor_data)
    );
    @Do(
    $perg03:=@Text(@Prompt([YesNo];"Super Mega Button";"O campo " + $campo + " é multi-valorado?"));
    @If(
    $perg03="1";
    @Do(
    $valor_multi:=@Prompt([OkCancelEdit];"Super Mega Button";"Informe o valor texto para incluir na lista do campo " + $campo +":";"");

    $lista:=@Implode(@GetField($campo);",");
    @SetField($campo;@Explode($lista+","+@Text($valor_multi);","))
    );
    @Do(
    $valor_texto:=@Prompt([OkCancelEdit];"Super Mega Button";"Informe o valor texto do campo " + $campo +":";"");
    @SetField($campo;@Text($valor_texto))
    ))))))


    Bt Ninja 2
    REM { v1.2 - if field exists, uses default value and default field type in @Prompt dialogs [Raphael Rodrigues, 2007-08-08]};

    unid:= @Text(@DocumentUniqueID);

    theField := @Prompt([OkCancelList]; "Change Field"; "Select Field"; ""; "":@DocFields);

    currValueTemp:= @If( @IsAvailable(theField); @GetDocField(unid; theField); "errorTemp" );
    currValue:= @If( @IsError(currValueTemp); "errorValue"; @If(@Elements(currValueTemp)>1;@Implode(@Text(currValueTemp);";");@Text(currValueTemp)) );
    theValue := @Prompt([OkCancelEdit]; "Change Field"; "New Value: use semicolon separator for lists."; currValue);

    currType:= @If( @IsNumber(currValueTemp); "Number"; @IsTime(currValueTemp); "Time"; "Text" );
    theType := @Prompt([OkCancelList]; "Change Field"; "Data Type"; currType; "Text" : "Time" : "Number" : "Text List" : "Number List" : "Time List");

    @If(

    theType = "Time";
    @SetField(theField; @TextToTime(theValue));

    theType = "Number";
    @SetField(thefield; @TextToNumber(theValue));

    theType = "Text List";
    @SetField(theField; @Trim(@Explode(theValue;";")));

    theType = "Number List";
    @SetField(theField; @TextToNumber(@Explode(@Trim(@ReplaceSubstring(theValue;" ";""));";")));

    theType = "Time List";
    @SetField(theField; @TextToTime(@Explode(theValue;";")));

    @SetField(theField; @Text(theValue))
    )

    segunda-feira, 14 de maio de 2012

    Zipar um arquivo no Notes

    No exemplo abaixo, foi criado um agente chamando uma  biblioteca de scripts java:

    AGENTE:
    ######################################################################
    (Options)

    Uselsx "*javacon" 'Which lets you use Java from LotusScript
    Use "ZipFile" 'A Java library that holds a function to do zipping



    Sub Zip()
    Dim js As JAVASESSION
    Dim zipClass As JAVACLASS
    Dim zipFileObject As JavaObject
    Dim strOutFilePath As String, strReturnCode As String

    Set js = New JAVASESSION
    Set zipClass = js.GetClass("ZipFile")
    Set zipFileObject = zipClass.CreateObject
    strOutFilePath = Strleft(StrArquivo, ".") + ".zip"

    strReturnCode = zipFileObject.zipMyFile(StrArquivo, strOutFilePath, 1) 'Calling the zip function

    Kill StrArquivo
    StrArquivo = strOutFilePath

    If Not strReturnCode = "OK" Then Error 1010, "An Error occurred"

    End Sub
    ######################################################################


    Código da biblioteca de scripts:
    ######################################################################

    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.util.zip.Deflater;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipOutputStream;

    public class ZipFile {
     public String zipMyFile(String fileToZip, String zipFilePath, int intType) {
      String result = "";

          byte[] buffer = new byte[18024];

          // Specify zip file name
          String zipFileName = zipFilePath;
       
          try {

            ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));

            // Set the compression ratio
    out.setLevel(Deflater.BEST_COMPRESSION);

              System.out.println(fileToZip);
              // Associate a file input stream for the current file
    FileInputStream in = new FileInputStream(fileToZip);

    if (intType == 1)
    {
    fileToZip  = fileToZip.substring(fileToZip.lastIndexOf("\\"), fileToZip.length());
    }

              // Add ZIP entry to output stream.
              out.putNextEntry(new ZipEntry(fileToZip));

              // Transfer bytes from the current file to the ZIP file
              //out.write(buffer, 0, in.read(buffer));

              int len;
             while ((len = in.read(buffer)) > 0)
             {
             out.write(buffer, 0, len);
            }

              // Close the current entry
              out.closeEntry();

              // Close the current file input stream
              in.close();

            // Close the ZipOutPutStream
            out.close();
          }
          catch (IllegalArgumentException iae) {
            iae.printStackTrace();
       return "ERROR_ILLEGALARGUMENTSEXCEPTION";
          }
          catch (FileNotFoundException fnfe) {
            fnfe.printStackTrace();
        return "ERROR_FILENOTFOUND";
          }
          catch (IOException ioe)
          {
          ioe.printStackTrace();
          return "ERROR_IOEXCEPTION";
          }


      return "OK";

      }
    }

    ######################################################################




    quarta-feira, 18 de abril de 2012

    Lotus Connector Data Access


    USO DA FUNCIONALIDADE:


    Use "Lotus Connector Data Access"
    Dim objOracle As LotusConnectorDataAccess

    aux  = |QUERY|


    Set objOracle = New LotusConnectorDataAccess("oracle", "DatabaseName", usuario, senha)

    If objOracle.Connect Then
    If objOracle.ExecuteSQL(aux) Then
    msgbox "QUERY EXECUTADA"
    Exit Function

    Else

    Call objOracle.Disconnect
    Exit Function

    End If




    SCRIPT LIBRARIES:

    Option Public
    Uselsx "*lsxlc"
    Public Class LotusConnectorDataAccess
    objConn As LCConnection

    Private strLocalDBType As String
    Private strLocalDatabase As String
    Private strLocalUser As String
    Private strLocalPassword As String
    Private lngLocalRowsReturned As Long
    Private flLocalFieldList As LCFieldList

    '------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
    'OBJETIVO: Construtor da classe
    'PARAMETROS: strDBType -> Tipo de banco de dados (oracle, db2, etc)
    '            strDatabase -> Nome do banco de dados a ser acessado
    '                                   strUser -> O nome do usuário a conectar no banco de dados. Se não precisar e só passar ""
    '                          strPassword -> A senha do usuário a conectar no banco de dados. Se não precisar e só passar ""
    '------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
    Public Sub New(strDBType As String, strDatabase As String, strUser As String, strPassword As String)
    DBType = strDBType
    DatabaseName = strDatabase
    UserName = strUser
    Password = strPassword

    Set OracleConection = New LCConnection(strDBType)
    End Sub

    '------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
    'OBJETIVO: Destrutor da classe
    '------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
    Public Sub Delete
    Set objConn = Nothing
    End Sub

    Public Property Get RowsReturned As Long
    RowsReturned = lngLocalRowsReturned
    End Property

    Public Property Set RowsReturned As Long
    lngLocalRowsReturned = RowsReturned
    End Property

    Public Property Get DBType As String
    DBType = strLocalDBType
    End Property

    Public Property Set DBType As String
    strLocalDBType = DBType
    End Property

    Public Property Get DatabaseName As String
    DatabaseName = strLocalDatabase
    End Property

    Public Property Set DatabaseName As String
    strLocalDatabase = DatabaseName
    End Property

    Property Get UserName As String
    UserName = strLocalUser
    End Property

    Property Set UserName As String
    strLocalUser = UserName
    End Property

    Property Get Password As String
    Password = strLocalPassword
    End Property

    Property Set Password As String
    strLocalPassword = Password
    End Property

    Public Property Get FieldListReturned As LCFieldList
    Set FieldListReturned = flLocalFieldList
    End Property

    Public Property Set FieldListReturned As LCFieldList
    Set flLocalFieldList = FieldListReturned
    End Property

    Public Property Get OracleConection As LCConnection
    Set OracleConection = objConn
    End Property

    Public Property Set OracleConection As LCConnection
    Set objConn = OracleConection
    End Property

    '------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
    'OBJETIVO: Conecta no banco de dados
    'RETORNO: TRUE -> Se a conexão foi realizada com sucesso
    '                   FALSE -> Se a conexão não foi estabelecida
    '------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
    Public Function Connect() As Integer
    On Error Goto Error_Handler

    Select Case DBType
    Case "oracle":
    objConn.Server = DatabaseName
    objConn.Userid = Username
    objConn.Password = Password
    objConn.Connect
    Connect = True

    Case "db2":
    objConn.Database = DatabaseName
    objConn.Userid = Username
    objConn.Password = Password
    objConn.Connect
    Connect = True

    Case Else
    Msgbox "A classe não implementa acesso ao banco da dados " + DBType, 0+16, "Atenção"
    Connect = False
    End Select

    Goto Fim

    Error_Handler:
    Msgbox "Ocorreu um erro ao tentar conectar ao banco de dados." + Chr(13) + Chr(10) + _
    "Número: " + Cstr(Err) + " - Descrição: " + Error, 0+16, "Erro"
    Connect = False
    Resume Fim

    Fim:
    End Function

    Public Sub Disconnect
    '------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
    'OBJETIVO: Desconecta do SQL
    'PARAMETROS: Nenhum
    'RETORNO: Nenhum
    '------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
    If objConn.IsConnected Then
    objConn.Disconnect
    End If
    End Sub

    Public Function ExecuteSQL(strSQL As String) As Variant
    '------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
    'OBJETIVO: Executa um comando SQL que pode ser SELECT, DELETE, UPDATE, INSERT
    'PARAMETROS: strSQL -> A query que sera enviada ao banco de dados
    '           fieldListReturned -> Retorna uma coleção de dados caso a query seja um select.
    'RETORNO: TRUE -> Se a query foi executada com sucesso
    '                   FALSE -> Se a query não foi executada com sucesso
    '------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
    On Error Goto Error_Handler

    If objConn.IsConnected Then
    Set FieldListReturned = New LCFieldList
    RowsReturned = objConn.Execute(strSQL, FieldListReturned)
    ExecuteSQL = True
    Else
    ExecuteSQL = False
    End If
    Goto Fim

    Error_Handler:
    Msgbox "Ocorreu um erro na função ExecuteSQL: " + Chr(13) + Chr(10) + _
    "Número: " + Cstr(Err) + " - Descrição: " + Error, 0+16, "Erro"
    ExecuteSQL = False
    Resume Fim

    Fim:
    End Function
    End Class

    quarta-feira, 8 de fevereiro de 2012

    Retorna a posição do maior valor dentro de um array

    Ref: Notes/Domino 4 and 5 Forum


    Function MaxIndex( inputArray As Variant ) As Integer
    ' ----------------------------------------------------------------------------------------------------------------------------------
    ' MaxIndex( ) written by Trent Overton - toverton@wgcinc.com
    ' ----------------------------------------------------------------------------------------------------------------------------------
    ' Description
    ' Finds the maximum value in an array and returns the index to that element.
    ' Note: Array must contain values which can be compared with standard operators.

    ' Parameters
    ' inputArray - array passed as variant data type
    '
    ' Return value
    ' integer representing index to largest element in array.
    ' error conditions cause return value to be -1
    '
    ' ---------------------------------------------------------------------------------------------------------------------------------- 

    On Error Goto ErrorHandler

    Dim rc As Integer
    rc = -1
    If Isarray( inputArray ) Then
    Dim index As Integer
    For index = Lbound( inputArray ) To Ubound( inputArray )
    If rc = -1 Then 
    rc = index
    Elseif inputArray( index ) > inputArray( rc ) Then
    rc = index
    End If
    Next
    End If

    MaxIndex = rc

    ErrorHandler:
    rc = -1
    Resume Next

    End Function

    @Min and @Max on LotusScript lists

    Ref: Notes/Domino 6 and 7 Forum


     ********** MAX **********
    Function Max(numList List As Integer) As Integer

    Dim iMax As Integer
    iMax = -32768

    Forall num In NumList
    If(num > iMax) Then iMax = num
    End Forall
    Max = iMax

    End Function

    ' ********** MIN **********
    Function Min(numList List As Integer) As Integer

    Dim iMin As Integer
    iMin = 32767

    Forall num In NumList
    If(num > iMin) Then iMin = num
    End Forall
    Min = iMin

    End Function

    terça-feira, 31 de janeiro de 2012

    LotusScript code to embed a picture into a Notes richtext item

    Follows a simple LotusScript function that will embed a file system picture (strFilePath As String) into the Body RichText field of a Notes document (doc As NotesDocument). This will not embed as an icon, but as the image itself.
    Function EmbedPictureIntoRichText(doc As NotesDocument, strFilePath As String) As Boolean

    EmbedPictureIntoRichText = False

    Dim session As New NotesSession
    Dim db As NotesDatabase
    Dim body As NotesMIMEEntity
    Dim header As NotesMIMEHeader
    Dim child As NotesMIMEEntity
    Dim stream As NotesStream
    Dim fileFormat As String
    Dim rtitemA As NotesRichTextItem
    Dim rtitemB As NotesRichTextItem

    Set db = doc.Parentdatabase
    Set stream = session.CreateStream
    Call stream.Open(strFilePath)
    Set body = doc.CreateMIMEEntity("DummyRichText")
    Set header = body.CreateHeader("Content-Type")
    Call header.SetHeaderVal("multipart/mixed")
    Set child = body.CreateChildEntity() 'Set childEntity = richTextItemObj.CreateChildEntity()
    fileFormat = "image/jpeg" 'Other formats are "image/gif" "image/bmp"
    Call child.Setcontentfrombytes(stream, fileFormat, 1730)
    Call stream.Close()
    Call doc.save(false, false) 'JUST TO REFRESH

    Set rtitemA = doc.GetFirstItem("Body")
    Set rtitemB = doc.GetFirstItem("DummyRichText")
    Call rtitemA.AppendRTItem( rtitemB )
    Call rtitemB.Remove()
    Call doc.save(False, False)

    EmbedPictureIntoRichText = True

    End Function

    Classe XML

    REF http://www.vbweb.com.br/dicas_visual.asp?Codigo=2256

    .. classe para trabalhar com XML, espero q ajude. Na verdade, a classe serve mais para criar XML, sem ter q ficar dando um monte de comandos...

    Class ClsXML
         Public Root
         Public XML
       
         Private PIs
       
         Sub NewXML(TagPai, versao)
           Set XML = CreateObject ("Msxml2.DOMDocument" & Versao)
           XML.Async = False
           Set Root = XML.CreateElement(TagPai)
           XML.AppendChild(Root)
         
           Set PIs = XML.CreateProcessingInstruction("xml", "version='1.0' encoding='ISO-8859-1'")
           XML.InsertBefore PIs, Root
         End Sub

         Function Open(Path, versao)
              Dim Result
           Set XML = CreateObject ("Msxml2.DOMDocument" & Versao)
           XML.Async = False
             
              Result = XML.Load(Path)
              if Result = true then
                   Set Root = XML.DocumentElement
              end if
              Open = Result
         End Function

         Function CriaNodo(TagPai, Nome, Atributos, ValorAtributos,ValorNodo)
           Dim Nodo
           Dim Valor
           Set Nodo = XML.CreateElement(Nome)
           If TagPai Is Nothing Then
             XML.AppendChild(Nodo)
           Else
             TagPai.AppendChild(Nodo)
           End If
         
           If Isarray(Atributos)  And Isarray(ValorAtributos) Then
             NumAtributos = Ubound(Atributos)
             For i = 0 To NumAtributos
               Call Nodo.setAttribute(Atributos(i), ValorAtributos(i))
             Next
           End If
           If ValorNodo <> "" Then
             Set Valor = XML.CreateTextNode(ValorNodo)
             Nodo.AppendChild(Valor)
           End If
           Set CriaNodo = Nodo
           Set Nodo = Nothing
           Set Valor = Nothing
         End Function

         Function RemoveNodo(Expressao)
              Dim Nodo
             
              Set Nodo = Xml.GetElementsByTagName(Expressao)
              if not Nodo is nothing then
                   Call Nodo.RemoveAll
                   RemoveNodo = true
              else
                   RemoveNodo = false
              end if
         End Function

         Sub Save (Caminho)
           Call XML.Save(Caminho)
         End Sub

    End Class

    Usando a Classe para criar um XML com a seguinte estrutura:


     
         Rodrigo
         Lotus Notes
     


    Dim NomeAtributos(), ValorAtributos()
    Set objXML = New ClsXML()

    'O primeiro parâmetro é a Tag pai de todas, o segundo é a versão do MSXML q você quer usar
    Call NewXML("teste", "")
    Redim NomeAtributos(0), ValorAtributos(0)
    NomeAtributos(0) = "nome"
    ValorAtributos(0) = "Teste"
    Set Tag1 = objXML.CriaNodo(objXML.root, "tag1", NomeAtributos, ValorAtributos, "")
    Call objXML.CriaNodo(Tag1, "nome1", "", "", "Rodrigo")
    Call objXML.CriaNodo(Tag1, "ferramenta", "", "", "Lotus Notes")

    Call objXML.Save("teste")

    Exportação Genêrica para Excel

    DECLARATION

    Dim session          As NotesSession
    Dim wks                As NotesUIWorkspace
    Dim db       As NotesDataBase

    Dim Uiview            As NotesUIView
    Dim view                As NotesView
    Dim column           As NotesViewColumn

    Dim doc         As NotesDocument
    Dim qtdePlanilha   As Long
    Dim Linha As Long
    Dim Coluna As Long
    Dim ExcelApp         As Variant
    Dim WorkBook  As Variant
    Dim NomePlanilha As Variant
    Dim ConteudoColuna As Variant
    Dim PrimeiroTraco As Variant

    ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    INICIALIZE

    Sub Initialize
    On Error Goto TratarErro

    Dim Path                   As String
    Dim QtdeTotalDocs        As Long
    Dim qtdedocs As Long


    Set session                     = New NotesSession
    Set  wks                           = New NotesUIWorkspace
    Set uiView                       = wks.CurrentView
    Set db            = session.CurrentDataBase
    Set view                           = db.GetView( uiView.ViewName ) ' seta a visão corrente
    Set doc                             = view.GetFirstDocument

    QtdeTotalDocs                  = view.AllEntries.Count
    NomePlanilha                = view.Aliases
    Path                                  = "N:\GJD_Online\EXPORTACAO_JAN2012\"

    If doc Is Nothing Then
    Msgbox "Não existem documentos para exportar."
    Exit Sub
    End If

    Set ExcelApp                    = CreateObject("Excel.Application")

    With ExcelApp

    .Visible     = True
    Set WorkBook     = .Workbooks
    WorkBook.Add

    '*****************************************************************************************************************************************************************************************
    If QtdeTotalDocs > 65536 Then ' se quantidade de documentos da visão corrente for maior que o total de linhas do excel
    QtdePlanilha                 = 1 ' inicializa QtdePlanilha para gerar varias planilhas da mesma visão
    Else
    QtdePlanilha                 = 0
    End If
    '*****************************************************************************************************************************************************************************************

    '*************************************************************PREENCHIMENTO DO CABEÇALHO EXCEL****************************************************************************
    Coluna                            = 1  'inicializa a coluna para preencher o cabeçalho
    Call sub__Cabecalho()
    '******************************************************************************************************************************************************************************************
    Linha                               = 2 'preenche as informações a partir da linha 2

    qtdedocs = 1 ' quantidade de documentos exportados

    While Not doc Is Nothing


    %REM
    '******************************************************************** criação de novas planilhas no mesmo arquivo excel***************************************************
    If Linha > 65536 Then
    NomePlanilha = "Plan" + Cstr(qtdePlanilha)
    ExcelApp.Sheets(NomePlanilha).Select ' seleciona a proxima planilha da mesma pasta

    If qtdePlanilha > 3 Then
    ExcelApp.Sheets.Add ' adiciona nova planilha
    End If

    Coluna = 1 ' inicializa a coluna para preencher o cabeçalho
    Call sub__Cabecalho()

    Coluna = 1 ' inicializa a coluna para preencher as informações
    Linha = 2 ' inicializa a linha

    qtdePlanilha = qtdePlanilha + 1
    Else
    Coluna = 1
    End If
    '********************************************************************************************************************************************************************************
    %END REM

    Coluna = 1
    Forall col In view.Columns
    '*****************************************************INCLUSÃO DE UM ESPAÇO VAZIO NO INICO DO TEXTO PARA TRATAR O ERRO NA EXPORTAÇÃO ( automation object error)**********************
    If Instr(col.Title,"COMENTARIO") > 0 Or Instr(col.Title,"DESCRICAO") > 0  Or  Instr(col.Title,"OBSERVA") Then
    If Not Isarray(doc.ColumnValues(Coluna-1))  Then
    PrimeiroTraco = Left(doc.ColumnValues(Coluna-1),1)
    If PrimeiroTraco = "-"  Or PrimeiroTraco = "=" Then
    ConteudoColuna = "  " + doc.ColumnValues(Coluna-1)
    Else
    ConteudoColuna = doc.ColumnValues(Coluna-1)
    End If
    End If
    Else ' não é campo de comentario
    ConteudoColuna = doc.ColumnValues(Coluna-1)
    End If
    '****************************************************************************************************************************************************************************************
    If  Isempty(ConteudoColuna)Then
    .cells(Linha,Coluna) = ""
    Else
    If Isarray(ConteudoColuna)  Then ' é um array

    .cells(Linha,Coluna)  = Join(ConteudoColuna,",") ' transforma array em uma string

    Else ' não é array
    If Isnumeric(ConteudoColuna) Then
    If Instr(Ucase(col.Title),"DAT") > 0 Or  Instr(Ucase(col.Title),"DT") > 0 Or Instr(Ucase(col.Title),"AJUIZAMENTO")_ ' CAMPOS DE DATA
    Or  Instr(Ucase(col.Title),"ID") > 0 Then
    .cells(Linha,Coluna) =    Cstr(ConteudoColuna)
    Else
    .cells(Linha,Coluna).FormulaR1C1 =   ConteudoColuna ' Retorna ou define a fórmula para o objeto, usando notação em estilo L1C1 no idioma do usuário
    End If

    Else ' não é numero
    .cells(Linha,Coluna) =  Cstr(ConteudoColuna)
    End If ' IS NUMERIC
    End If ' IS ARRAY
    End If ' IS EMPTY

    Coluna = Coluna + 1
    End Forall


    If QtdeTotalDocs > 65536 And Linha = 65536  Then ' ultimo registro do excel

    'salva a planilha
    .ActiveWorkbook.SaveAs Path & NomePlanilha(0) & "_" + Cstr(QtdePlanilha)

    'Criar outro arquivo excel ( pasta)
    .Workbooks.Add

    Coluna = 1 ' inicializa a coluna para preencher o cabeçalho
    Call sub__Cabecalho()

    Coluna = 1 ' inicializa a coluna para preencher as informações
    Linha = 2 ' inicializa a linha

    QtdePlanilha     = QtdePlanilha  + 1

    Elseif (QtdeTotalDocs  =  qtdedocs) And (QtdePlanilha > 0)   Then ' ultimo doc exportado
    .ActiveWorkbook.SaveAs Path & NomePlanilha(0) & "_" + Cstr(QtdePlanilha) ' salva arquivo
    Else
    Linha = Linha + 1
    End If


    Set doc = view.GetNextDocument(doc)

    If Not doc Is Nothing Then
    qtdedocs = qtdedocs + 1
    End If

    Wend

    '********************************************CONVERTE AS COLUNAS DE DATA PARA O TIPO GERAL***********************************
    Coluna = 1
    Forall col In view.Columns
    Set column = view.Columns( Coluna -1)
    If column.Formula<>"""1""" And column.Formula<>"1" Then
    If  Instr(Ucase(col.Title),"DAT") > 0 Or  Instr(Ucase(col.Title),"DT") > 0  Or Instr(Ucase(col.Title),"AJUIZAMENTO")_
    Or  Instr(Ucase(col.Title),"VALOR") > 0  Or Instr(Ucase(col.Title),"LITRO") >0 Or  Instr(Ucase(col.Title),"ID") > 0 Then
    ExcelApp.Columns(Coluna).NumberFormat =  "Geral" ' Converte a coluna para o tipoGeral
    End If
    End If
    Coluna = Coluna + 1
    End Forall
    '*****************************************************************************************************************************************************

    If QtdePlanilha  =  0 Then
    .ActiveWorkbook.SaveAs Path & NomePlanilha(0)
    End If

    Set ExcelApp = Nothing
    Set WorkBook = Nothing

    End With

    Exit Sub
    TratarErro:

    If Not ExcelApp Is Nothing Then
    Set ExcelApp = Nothing
    Set WorkBook = Nothing
    'Call ExcelApp.Quit
    End If

    Msgbox "Erro " + Cstr(Err) +  " " + Error + " Na linha " + Cstr(Erl)
    End Sub



    ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    FUNCTION REPLACESUBSTRING

    Function ReplaceSubstring(StrConteudo As String, StrDe As String, StrPara As String) As String
       ' Essa Função substitui caracteres na String que é passada atraves da variavel StrConteudo
       ' StrDe é(são) o(s) caracter(es) a ser(em) alteardo(s)
    'StrPara  (é(são) o(s) novo(s) caracter(es)
    Dim StrTemp As String
    Dim StrConvertido As String
    Dim i As Long
    Dim length As Long
    StrTemp = StrConteudo
    If Len(StrDe) = 0 Then
    ReplaceSubstring = StrConteudo
    Exit Function
    End If
    If Instr(StrPara, StrDe) <> 0 Then
    i = 128
    length = 1
    StrConvertido = ""
    While StrConvertido = ""
    If Instr(StrTemp, String$(length, Chr$(i))) = 0 Then StrConvertido = String$(length, Chr$(i))
    i = i + 1
    If i = 256 Then
    length = length + 1
    i = 128
    End If
    Wend

    While Instr(StrTemp, StrDe) <> 0
    StrTemp = Left(StrTemp, Instr(StrTemp, StrDe)-1) & StrConvertido _
    & Mid(StrTemp, Instr(StrTemp, StrDe)+Len(StrDe))
    Wend
    While Instr(StrTemp, StrConvertido) <> 0
    StrTemp = Left(StrTemp, Instr(StrTemp, StrConvertido)-1) & StrPara _
    & Mid(StrTemp, Instr(StrTemp, StrConvertido)+Len(StrConvertido))
    Wend
    Else
    While Instr(StrTemp, StrDe) <> 0
    StrTemp = Left(StrTemp, Instr(StrTemp, StrDe)-1) & StrPara _
    & Mid(StrTemp, Instr(StrTemp, StrDe)+Len(StrDe))
    Wend
    End If
    ReplaceSubstring = StrTemp
    End Function


    ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    SUB_CABECALHO

    Sub sub__Cabecalho ()
    'preencher o cabeçalho

    Forall col In view.Columns
    Set column = view.Columns( Coluna -1)

    If column.Formula<>"""1""" And column.Formula<>"1" Then
    'As colunas com valores de data, foram convertidas para texto para o tratamento do erro "automation object error" devido a data invalida com ano de 3 digitos
    If Instr(Ucase(col.Title),"COMENTARIO") > 0 Or Instr(Ucase(col.Title),"DESCRICAO") > 0  Or  Instr(Ucase(col.Title),"OBSERVA") Or  Instr(Ucase(col.Title),"DAT") > 0_
    Or   Instr(Ucase(col.Title),"DT") > 0 Or Instr(Ucase(col.Title),"AJUIZAMENTO") > 0 Or  Instr(Ucase(col.Title),"VALOR") > 0  Or Instr(Ucase(col.Title),"LITRO") >0_
    Or  Instr(Ucase(col.Title),"ID") > 0 Then
    ExcelApp.Columns(Coluna).NumberFormat = "@" ' Converte a coluna para o tipo Texto
    End If
    ExcelApp.cells(1,coluna) = column.Title
    ExcelApp.Columns(Coluna).EntireColumn.AutoFit
    Coluna = Coluna + 1
    End If
    End Forall
    End Sub