I tried convert UTF8 from Base64 string but returning results have a meaningless characters
Public Module Base64Decoder
Sub Main()
Dim inputText As String
inputText = "BgAAAFOUR1Ue36wvZwOGNkPEStG/lFZ+L0llB7KsvMRw0mqchfgIzwR144c87V6xOsiRCgACAACAW9H7Z15JQe+MwYVJ3tQJUkIzIqILi6+P7JFpgq6cNR6CvIumW5jspbPvEWkWFwNVOB7eG9o9ngeL3X5qYd2JWjOOVvL9Jwh4fG6C8GcxMCDfx3WaOSYLP+W3A9csE00EkgFU3z40YTnoZfweHcatgvZdH3O1xRQDmFEpfEOosQmhrX7+EMTz/kHr9n8UlWUg7fuI6Mk+Evg4gn6oNriXCkrCYmgv1qfq6+u0njE76wnIOnQyMeoLQI7FfqiXgQbQF7/MkisG+R/7tF0kzVu7Zjgsa2RPuAvLKNjMGc6wHI6cIy59AZWuGs3yqS/Z0Je5F17Bt4QWI9GVqawMfbzlnzwqho2umkdNVSwNnJ+nBEfJQIjsNdY2NYjDakeNSn1ayDbfHnJHKjgOWVAfM6YxkEEFXvdZ8bY8PTC2Kr42zefh5XLUPK2bvyUHTHB+hryhQnCGQqS7JPXInfRaPiJWi2C//u/4SSk6WDiEVmBbrM5pkDKeWoC8Cpr+7m8YlzwUfgT3qz4JgtSjmqFIJMkyAUWN24zZDYMSrQ8If5L+CNOZuy/FqcDwBzONocOUbn+t93zp7vfaUlxvmQc8l3cKvROA7TlvOnZRdcK0UerGhf9C+rZLtSFlk+xdiHqiZQ7mnKcHg1cukqG7WNBzMItRjM3Gn3HjZIM3baa5PlU3TQ=="
Console.Out.WriteLine("Input text: {0}", inputText)
Dim decodedBytes As Byte()
decodedBytes = Convert.FromBase64String(inputText)
Dim decodedText As String
decodedText = Encoding.UTF8.GetString(decodedBytes)
Console.Out.WriteLine("Decoded text: {0}", decodedText)
End Sub
End Module
Result:
???+???]$?[?f8,kdO??(?????#.}????/???^???#???}??<*????GMU,
???G?#??5?65??jG?J}Z?6?rG*8YP3?1?A^?Y?<=0?*?6????r?<???%Lp~???Bp?B??$???Z>"V?`????I):X8?V`[??i?2?Z??
???o?<~??> ????H$?2E???
??????/u??3??Ôn??|????R\o?<?w
???9o:vQu´Q???B??K?!e??]?z?e??W.???X?s0?Q??Oq?d?7m??>U7M
Related
Sub Process_Globals
'These global variables will be declared once when the application starts.
'These variables can be accessed from all modules.
Type DBResult (Tag As Object, **Columns As Map**, Rows As List)
Type DBCommand (Name As String, Parameters() As Object)
Private const rdcLink As String = "http://192.168.8.100:17178/rdc"
End Sub
This is the methods for process globals . Here columns As Map is initialized .
However the line bolded in the below code gives an error as , "Object converted to String. This is probably a programming mistake. (warning #7)"
Sub GetRecord
Dim req As DBRequestManager = CreateRequest
Dim cmd As DBCommand = CreateCommand("selectAllNames", Null)
Wait For (req.ExecuteQuery(cmd, 0, Null)) JobDone(j As HttpJob)
If j.Success Then
req.HandleJobAsync(j, "req")
Wait For (req) req_Result(res As DBResult)
'work with result
'req.PrintTable(res)
***Log(res.Columns)***
ListViewListTable.Clear
For Each row() As Object In res.Rows
Dim oBitMap As Bitmap
Dim buffer() As Byte
buffer = row(res.Columns.Get("gambar"))
oBitMap = req.BytesToImage(buffer)
ListViewListTable.AddTwoLinesAndBitmap(row(1), "See more...", oBitMap)
Next
Else
Log("ERROR: " & j.ErrorMessage)
End If
j.Release
End Sub
So what should I do to remove the error?
If columns is a map? (which it looks to be?).
Then to display the columns you can use this:
For Each MyKey As String in res.Columns.Keys
log("Key name = " & MyKey)
log("Key value = " & res.Columns.Get(MyKey))
Next
I am trying to get the part of the string after the second /.
For instance if I have the string "25/S17/874"
I would like to get "874"
Thanks
you can split the string by "/" and the call back from the array.
Example:
Dim string_sample As String
Dim string_arr As String()
string_sample = "25/S17/874"
string_arr = string_sample.Split("/")
Dim string_Result As String
string_Result = string_arr(2)
MsgBox(string_Result)
the string_Result is "874"
Dim result As String = "25/S17/874".Split("/"c)(2)
Obviously, some validation, error trapping, etc might be required if the string content is prone to variation.
I want to check a file for a particular word the way I have found posted on various forums is to use the following code...
Dim content = My.Computer.FileSystem.ReadAllText(filePath)
If content.Contains("stringToSearch") Then
'Do your stuff
End If
Which is okay until you discover that it will search and match compound words and the likes. For instance If I search for the string light in a file and it's not there but instead the word lightning is, it will still register as having found a match... Is there a way to find and exact word using VB.net?
As mentioned by Andrew Morton, Regex makes this kind of thing very easy. For instance, if you made a function like this:
Public Function ContainsWord(input As String, word As String) As Boolean
Return Regex.IsMatch(input, $"\b{word}\b")
End Function
You could use it like this:
Dim content = My.Computer.FileSystem.ReadAllText(filePath)
If ContainsWord(content, "stringToSearch") Then
'Do your stuff
End If
If you wanted to, you could even make it an extension method on the String type, by putting it in a Module and adding the ExtensionAttribute, like this:
<Extension>
Private Function ContainsWord(input As String, word As String) As Boolean
Return Regex.IsMatch(input, $"\b{word}\b")
End Function
And then you could call it like this:
Dim content = My.Computer.FileSystem.ReadAllText(filePath)
If content.ContainsWord("stringToSearch") Then
'Do your stuff
End If
Another method, using Regex.Matches, which allows to search for a collection of words and returns a Dictionary(Of String, Integer()).
The Dictionary Key represent the matched word, the Value, as an Array of Integers, all the positions inside the File where the word was found.
The extension method requires 2 parameters:
- the path of the file to search
- a boolean value, used to specify whether the search should be case sensitive.
Proposed as an extension method of IEnumerable(Of String):
Dim fileName As String = "[File Path]"
Dim searchWords As String() = {"light", "lighting", "clip", "clipper", "somethingelse"}
Dim result = searchWords.FindWords(fileName, False)
Print a result of the matches found:
result.ToList().ForEach(
Sub(w)
Console.WriteLine($"Word: {w.Key} Positions: {String.Join(", ", w.Value)}")
End Sub)
Extension method:
Imports System.IO
Imports System.Runtime.CompilerServices
Imports System.Text
Imports System.Text.RegularExpressions
Module modIEnumerableExtensions
<Extension()>
Public Function FindWords(words As IEnumerable(Of String),
fileName As String,
caseSentive As Boolean) As Dictionary(Of String, Integer())
Dim pattern As StringBuilder = New StringBuilder()
pattern.Append(String.Concat(words.Select(Function(w) $"\b{w}\b|")))
Dim options As RegexOptions = RegexOptions.Compiled Or
If(caseSentive, RegexOptions.Multiline, RegexOptions.IgnoreCase Or RegexOptions.Multiline)
Dim regx As New Regex(pattern.ToString().TrimEnd("|"c), options)
Dim matches As MatchCollection = regx.Matches(File.ReadAllText(fileName))
Dim groups = matches.OfType(Of Match).
GroupBy(Function(g) g.Value).
ToDictionary(Function(g) g.Key, Function(g) g.Select(Function(m) m.Index).ToArray())
Return groups
End Function
End Module
The shortest and fastest way to do this is using ReadLines with LINQ queries, specialy when you are working with a large files.
Dim myword As String = "Book"
Dim reg = New Regex("\b" & myword & "\b", RegexOptions.IgnoreCase)
Dim res = From line In File.ReadLines(largeFileName)
Where reg.IsMatch(line)
If your file containts "Book", "Books", "Book." and "Book," the results will be:
Book
Book,
Book.
And you can working with results as following
TextBox1.Text = resLines.Count
Or
TextBox1.Text = resLines(0)
Edited to make it consering "." and "," etc.
Hi friends i want to access the properties file from machine from the specified path. For java Agent i used Properties method and extracted the data from the properties file. but now i want it to be done in lotuscript. I tried using properties method but it didnt work so i thought to read properties with the below code.
'Dim ColFileName As String
'ColFileName="C:\abcd.properties"
Open ColFileName For Input As 1
Do While Not EOF(1)
Line Input #1,txt$
MsgBox "TEXT FILE:"+txt$
In properties file i have a written it as
col=start
where i want to get the property of the col using getProperty method in java same way for lotusscript.
I added the above code but it is not working. Can anyone tell what mistake i have committed.
In Options
%Include "lserr.lss" 'This is just a list of constants.
Add these functions somewhere:
%REM
Function fstreamOpenFile(sPath As String, bTruncate As Boolean, bConfirmExists As Boolean) As NotesStream
<dl>
<dt>sPath</dt><dd>Filepath of the file to be opened/created.</dd>
<dt>bTruncate</dt><dd>Boolean. True if file is for output and any existing file should be replaced rather than appended to.</dd>
<dt>bConfirmExists</dt><dd>Boolean. If True, and the opened file is empty, then an ErrFileNotFound error will be thrown.</dd>
</dl>
%END REM
Function fstreamOpenFile(sPath As String, bTruncate As Boolean, bConfirmExists As Boolean) As NotesStream
Dim session as New NotesSession Dim stream As NotesStream
Set stream = session.Createstream()
If Not stream.Open(sPath) Then Error ErrOpenFailed, {Could not open file at "} + sPath + {"}
If bConfirmExists And stream.Bytes = 0 Then Error ErrFileNotFound, {File at "} + sPath + {" is missing or empty.}
If bTruncate Then Call stream.Truncate()
Set fstreamOpenFile = stream
End Function
Function fsPropertyFileValue(sFilePath As String, sPropertyName As String, sDefaultValue As String) As String
On Error GoTo ErrorQuietly
Dim stream As NotesStream
Dim sLine As String
Dim sLeft As String
Dim iLeftLen As Integer
Set stream = fstreamOpenFile(sFilePath, False, True)
sLeft = sPropertyName + "="
iLeftLen = Len(sLeft)
Do
sLine = stream.Readtext
If Left(sLine, iLeftLen) = sLeft Then
fsPropertyFileValue = Right(sLine, Len(sLine) - iLeftLen)
Exit Function
End If
Loop Until stream.Iseos
ReturnDefault:
fsPropertyFileValue = sDefaultValue
Exit Function
ErrorQuietly:
Print Now, Error$
Resume ReturnDefault
End Function
(Notes: I have not tested/debugged fsPropertyFileValue. The html tags in the comment is because, when editing an agent or script library, the designer client will parse and display the HTML tags.)
Then you can use fsPropertyFileValue("C:\abcd.properties", "col", "start") to get the value of the col property within C:\abcd.properties and, if that fails, use "start".
Through LotusScript I am consuming a webpage that returns json values and I have been unable to find any library out there for lotusscript, other than ls.snapps.JSONReader from openntf. It works, but documentation is limited. I am having trouble reading a nested array in the value list. I was able to get it to work in java using the ibm.common.utils.... library, but was having trouble with mac client and another library (javax.swing.*) so I switched to LotusScript.
I am hoping someone else has experience with the ls.snapps.JSONReader library, or maybe a different idea on how to do this. Here is the sample:
to read it I use
Dim jsonReader As jsonReader
Dim vResults As Variant
Dim vPieces As Variant
Dim sJSON As string
sJson= |{ "colorsArray":[{
"red":"#f00",
"green":"#0f0",
"blue":"#00f",
"cyan":"#0ff",
"magenta":"#f0f",
"yellow":"#ff0",
"black":"#000"
}
]
}|
Set jsonReader = New JsonReader
Set vResults = jsonReader.parse(sJson)
vPieces = vResults.items
I have no trouble when I set a single level object such as:
sJSON = |{"a":"a4255524","a24":true,"ax":"WER!!","b":"Some text"}|
I use the getItemValue method
msgbox vResults.getitemValue("a24")
will return a 'true' value
Has anyone used this JSON parser and can you give me some advice on how to get the data out?
UPDATE and interim solution:
To get json values I had to do one of two things:
use ls Replace functions to extract the single dimension data (ie, remove {"colorsArray":[ on the left side and ]} on the right side., then use snapps json reader.
I created a java library using the SBT JSON libs and called it from LotusScript. Paul Bastide put a good writeup on using the java lib http://bastide.org/2014/03/15/using-the-ibm-social-business-toolkit-to-process-json-objects/
Here is the java code:
import com.ibm.commons.util.io.json.JsonException;
import com.ibm.commons.util.io.json.JsonJavaFactory;
import com.ibm.commons.util.io.json.JsonJavaObject;
import com.ibm.commons.util.io.json.JsonParser;
import com.ibm.sbt.services.client.base.datahandlers.JsonDataHandler;
import lotus.domino.*;
public class GetJSON extends AgentBase {
public static String pJSON( String jData, String jEntry, String jValue ) {
String result2="";
try {
System.out.println("data: " + jData + "\n" + "\n" + "jEntry & jValue: " + jEntry + ", " + jValue);
// print to debug console
// System.out.println("jData: " + jData);
JsonJavaObject jsonObject = (JsonJavaObject) JsonParser.fromJson(JsonJavaFactory.instanceEx, jData );
JsonDataHandler handler = new JsonDataHandler();
handler.setData(jsonObject);
JsonJavaObject entryJson=handler.getEntry(jEntry);
result2=entryJson.getAsString(jValue);
} catch (Exception e) {
System.out.println("Error: " + e);
e.printStackTrace();
result2="";
}
return result2; }
}
and I call it from LotusScript as follows:
Option Public
Option Declare
Use "($getJson)"
UseLSX "*javacon"
Dim mySession As JavaSession
Dim myClass As JavaClass
Dim getJson As JavaObject
result = ""
'....
'add vars here
'....
Set mySession = New JavaSession()
Set myClass = mySession.GetClass("GetJSON")
Set GetJson = myClass.CreateObject()
MsgBox GetJson.pJSON( result2, "colorsArray", "red" )
IMPORTANT NOTE on the above, in the array string I had to remove the brackets [ and ] because I was getting an SBT array incompatibility error in java. I think by doing that it may have turned it into a single level object, but if you look at Paul's example from above URL, you'll see he doesn't add them to his example either.
I would rather do this in all Java or all LotusScript, and will probably use the modified json string with snapps, just looking for a better solution.
Here is the working code for your JSON string. Try it.
Dim jsonReader As JSONReader
Dim vResults As Variant
Dim vPieces As Variant
Dim sJSON As String
sJson= |{ "colorsArray":[{
"red":"#f00",
"green":"#0f0",
"blue":"#00f",
"cyan":"#0ff",
"magenta":"#f0f",
"yellow":"#ff0",
"black":"#000"
}
]}|
Set jsonReader = New JSONReader
Set vResults = jsonReader.parse(sJson)
Set vResultData = vResults.GetItemValue("colorsArray")
Forall vResult In vResultData.Items
Msgbox Cstr(vResult.GetItemValue("red"))
Msgbox Cstr(vResult.GetItemValue("green"))
Msgbox Cstr(vResult.GetItemValue("blue"))
Msgbox Cstr(vResult.GetItemValue("cyan"))
Msgbox Cstr(vResult.GetItemValue("magenta"))
Msgbox Cstr(vResult.GetItemValue("yellow"))
Msgbox Cstr(vResult.GetItemValue("black"))
End Forall