i have written a lot of javascript functions that i want to use in my vb6 app for efficiency and time saving
is it possible to call java-script function from vb6?
if possible, can you help me with some code?
I hesitate to say this, but you could use the Windows Script Control ActiveX control and embed it in your VB6 application and then run your javascript code possibly with some minor adjustments, but DON'T DO IT. You might think it is efficient and time saving for you, but the reality is you will spend all sorts of extra time dealing with your "work around." Additionally, porting your code to VB6 will make it run much faster. I would only use the scripting method if you need some sort of extensibility.
Add a reference to the scripting runtime and the script control 1.0.
NOTE: in this example the variable scode is the javascript code passed to the function as a string. Since the code is simply a string you can pass in any variables you want, however, getting things back from the code is much more complex. The code can be created on the fly or retrieved from a text file.
In the example, the code is passed as a string and then the string is searched to see if it contains a function called OnProgramLoad. If it does, that function is called.
Public Sub OnProgramLoad(byval scode as string)
Dim sctest As ScriptControl
If Len(scode) < 1 Then Exit Sub
If InStr(1, scode, "OnProgramLoad", vbTextCompare) = 0 Then Exit Sub
Set sctest = New ScriptControl
With sctest
.Language = "JScript"
.AllowUI = True
.AddObject "Application", App
.AddObject "Clipboard", Clipboard
.AddObject "Printer", Printer
.AddObject "Screen", Screen
.AddCode scode
.Run "OnProgramLoad"
End With
Set sctest = Nothing
End Sub
You would be better off porting your routines to VB6 and if you need access to a regex library in VB6 there are better ways:
http://support.microsoft.com/kb/818802
Add a reference to Microsoft VBScript Regular Expressions 5.5, then port your code...
Function TestRegExp(myPattern As String, myString As String)
'Create objects.
Dim objRegExp As RegExp
Dim objMatch As Match
Dim colMatches As MatchCollection
Dim RetStr As String
' Create a regular expression object.
Set objRegExp = New RegExp
'Set the pattern by using the Pattern property.
objRegExp.Pattern = myPattern
' Set Case Insensitivity.
objRegExp.IgnoreCase = True
'Set global applicability.
objRegExp.Global = True
'Test whether the String can be compared.
If (objRegExp.Test(myString) = True) Then
'Get the matches.
Set colMatches = objRegExp.Execute(myString) ' Execute search.
For Each objMatch In colMatches ' Iterate Matches collection.
RetStr = RetStr & "Match found at position "
RetStr = RetStr & objMatch.FirstIndex & ". Match Value is '"
RetStr = RetStr & objMatch.Value & "'." & vbCrLf
Next
Else
RetStr = "String Matching Failed"
End If
TestRegExp = RetStr
End Function
Related
I have a file called 'test.abcde.houses.csv' and I want to extract the substring 'abcde' which I will use in my next processor group to query the database.
Currently, I am using the updateAttribute Processor group to try to extract the substring.
This is the code I am using in the value section.
var userPattern = java.util.regex.Pattern.compile('(.+?)\.[0-9]{8}-[0-9]{7,9}\..+');
var userMatcher = userPattern.matcher(fileName);
var matchExists = userMatcher.matches();
var user;
var userRemove;
if (matchExists) {
user = userMatcher.group(1);
userRemove = user + ".";
}
else {
throw 'Unable to parse username from file metadata.';
}
Question:
Is this the right way to extract a substring from a flow file name in NIFI?
Am I using the right processor group?
Does this code work with Nifi?
You need to use NiFi Expression Language, a kind of NiFi's own scripting feature which provides the ability to reference attributes, compare them to other values, and manipulate their values. Please refer to this official documentation.
UpdateAttribute processor is used to update/derive new/delete attributes. So you need to use the Expression Language inside UpdateAttribute to manipulate attributes.
Example:
test.abcde.houses.csv - this is your filename and if you want to extract abcde string from filename then you can use getDelimitedField function (Expression Language string function) like below. If the expression did not evaluate, then user attribute will be having empty/null value.
Property: user (if already present then update/assign value, otherwise create new attribute)
Value: ${filename:getDelimitedField(2, '.')} (abcde is at second index/position in filename attribute value)
Expression Language has Boolean, Conditional, String Manipulation, etc. functions, so you can easily replicate your JS logic into UpdateAttribute to derive desired attribute value.
I've ran into a problem - I need to add a custom stamp (type of annotation) to a number of .pdf files. I can do it through Actions for Acrobat X Pro, but my clients do not have that license and they still need to do it. The list of files is stored in Excel spreadsheet, so ideally I am looking for a VBA solution. I have came up with the following code :
Option Explicit
Sub code1()
Dim app As Acrobat.AcroApp
Dim pdDoc As Acrobat.CAcroPDDoc
Dim page As Acrobat.CAcroPDPage
Dim recter(3) As Integer 'Array defining the rectangle of the stamp - in real code wil be calculated, simplified for ease of reading
Dim jso As Object
Dim annot As Object
Dim props As Object
Set pdDoc = Nothing
Set app = CreateObject("AcroExch.App")
Set pdDoc = CreateObject("AcroExch.PDDoc")
recter(0) = 100
recter(1) = 100
recter(2) = 350
recter(3) = 350
pdDoc.Open ("C:\Users\maxim_s\Desktop\Code_1\test1.pdf")
Set jso = pdDoc.GetJSObject
If Not jso Is Nothing Then
Set page = pdDoc.AcquirePage(0)
Set annot = jso.AddAnnot
Set props = annot.getprops
props.page = 0
props.Type = "Stamp"
props.AP = "#eIXuM60ZXCv0sI-vxFqvlD" 'this line throws an error. The string is correct name of the stamp I want to add
props.rect = recter
annot.setProps props
If pdDoc.Save(PDSaveFull, "C:\Users\maxim_s\Desktop\Code_1\test123.pdf") = False Then
MsgBox "fail"
pdDoc.Close
Else
MsgBox "success"
pdDoc.Close
End If
End If
End Sub
The problem is with the setprops and getprops procedures - it seems that at the moment when annotation is created (jso.AddAnnot) it does not posses the AP property, which is the name of the stamp I want to add. If I set the property Type= "Stamp" first and then try to specify the AP, the result is that one of the default stamps is added and it's AP is renamed to my custom stamps' AP. Also note, that if I launch acrobat and use the code below, the proper stamp is added:
this.addAnnot({page:0,type:"Stamp",rect:[100,100,350,350],AP:"#eIXuM60ZXCv0sI-vxFqvlD"})
If there is a way to execute this Javascript from VBA inside of the PDDoc object, that will solve the problem, but so far I have failed.
You can use "ExecuteThisJavaScript" from the AForm Api. Short example:
Set AForm = CreateObject("AFormAut.App")
AForm.Fields.ExecuteThisJavaScript "var x = this.numPages; app.alert(x);"
It has the advantage that you don't need to translate the js examples into jso code. If you search for ExecuteThisJavaScript you will get some more and longer examples.
Good luck, reinhard
In...
props.Type = "Stamp"
The type should be lower case. But if the pure JavaScript is working from the console, you might consider just executing the string using the jso.
Background
I have a load of Applescripts(AS) which designers use with InDesign that help process the workflow for production. There is a great deal of OS interaction that the AS does that the JavaScript can not, so moving away from AS is not possible.
Due restrictions I am unable to install pretty much anything.
I am unable to update anything. Script Editor and ExtendScript Tool Kit are what I have to work with.
Operating Environment:
OS X 10.8.5 &
Adobe CS6
How it works
User preferences are saved as Properties in local Applescripts saved in the user's documents folder.
###property grabber.scpt
set mypath to path to documents folder
set mypropertiesfile to ((mypath & "myproperties.scpt") as string)
set thePropertyScript to load script file mypropertiesfile
set designerinitials to (designerinitials of thePropertyScript) ETC...
Some of the properties are AS lists.
Why I need JS?
I'm making palettes and would prefer to use the ScriptUI rather than do it all in AS like this:
set dlgRef to make dialog with properties {name:"User Settings", can cancel:true, label:"Dialog Label"}
The string the AS hands off to the JS is this:
{"myname",{firstvalue:"test", secondvalue:"val2", thirdvalue: "val3"},{firstvalue:"test2", secondvalue:"val2", thirdvalue: "val3"}}
These are not lists, but text...
The JS
myAppleScript = new File("valid_path_to/property grabber.scpt");
var myreturn = app.doScript(myAppleScript, ScriptLanguage.applescriptLanguage);
var myname = myreturn[0];
var firstlist = myreturn[1];
var secondlist = myreturn[2];
ExtendScript data browser shows:
firstlist = {firstvalue:"test", secondvalue:"val2", thirdvalue: "val3"}
It is not an array...
I have tried using https://github.com/KAYLukas/applescript-json
to json encode the lists, but the same result.
firstlist = [{firstvalue:"test", secondvalue:"val2", thirdvalue: "val3"}]
I have also made it much simpler with just
firstlist = {"test","val2","val3"}
Still the JS treats it as a string and not an array.
Any ideas what I need to do or am doing wrong? I hope it simple and I feel stupid if I get an answer...
Glad you have something that works, but if you're passing text to ExtendScript, why not format it on the AS side to be ExtendScript-friendly, like ['firstvalue', 'secondvalue', 'thirdvalue"'] --but this would be a string in AS, like
--in AS:
"['firstvalue', 'secondvalue', 'thirdvalue"']"
Then, in ExtendScript, if that's in a variable, like, myData, you can do (as I just did in ExtendScript Toolkit):
//in JS:
myArray = eval(myData);
I know using eval() is evil in web work, but for ExtendScript stuff, it can be very useful.
I hate finding an answer after I take the time to post an elaborate question.
https://stackoverflow.com/a/14689556/1204387
var path = ((File($.fileName)).path); // this is the path of the script
// now build a path to another js file
// e.g. json lib https://github.com/douglascrockford/JSON-js
var libfile = File(path +'/_libs/json2.js');
if(libfile.exists)
$.evalFile(libfile);
Like Neo learning Kung Fu, it suddenly went, "Whoa, I know JSON!"
var firstlist = JSON.parse(myresult[1]);
Gives me workable objects
doScript can pass script args to one language to another. Here is a snippet inspired from the doc:
var aps = "tell application \"Adobe InDesign CC 2014\"\
tell script args\
set user to item 1 of {\"John\", \"Mike\", \"Brenda\"}\
set value name \"user\" value user\
\"This is the firest AppleScript script argument value.\"\
end tell\
end tell"
app.doScript(aps, ScriptLanguage.applescriptLanguage);
var user = app.scriptArgs.getValue("user");
alert( user+ "from JS" );
I don't think script args would return anything else than strings even if those could represent any kind of value. However a string can be easily turned into an array with a split method like this :
var aps = "set ls to {\"john\", \"mark\"}\
set n to count of items of ls\
set str to \"\"\
repeat with i from 1 to n\
set str to str & item i of ls\
if i < n then\
set str to str & \",\"\
end if\
end repeat\
tell application \"Adobe InDesign CC 2014\"\
tell script args\
set value name \"str\" value str\
end tell\
end tell";
app.doScript(aps, ScriptLanguage.applescriptLanguage);
var str = app.scriptArgs.getValue("str");
var arr = str.split(",");
alert( "Item 1 of APS list is \""+arr[0]+ "\" in the JS context" );
The idea is to flatten the APS list into a comma separated string that will be later splitted in the javascript context to turn it into an array.
I need to rewrite a querysting using javascript.
First I check to see if the variable is present, if it is I want to replace it with a new search term. If it is not present then I just add the new variable
I'm able to get it to work with simple terms like hat, ufc hat
whitespaces are %20, so ufc hat is really ufc%20hat
I run into problem with terms like make-up, hat -baseball, coffee & tea, etc..
What is the proper regex for this?
Below is my code, which doesn't work.
var url = String(document.location).split('?');
querystring = url[1];
if(querystring.match(/gbn_keywords=/)!=null)
querystring=querystring.replace(/gbn_keywords=[a-zA-Z0-9%20.]+/,"gbn_keywords="+term);
else
querystring=querystring+"&gbn_keywords="+term;
No Regex needed. To get the query arguments, take everything after ?. Then, split the string by & to return each argument. Split again by = to get the arg name (right of =) and the value (left of =). Iterate through each argument, a rebuild the URL with each argument, excluding the one you don't want. You shouldn't run into problems here because ?, &, and - must be escaped if they are to be used in arguments. You also said you want to add the argument if it doesn't exist, so just set a variable to true, while you are iterating through each argument, if you find the argument. If you didn't append it to the end of the query string that you rebuilt.
location objects already have perfectly good properties like pathname, hostname etc. that give you the separate parts of a URL. Use the .search property instead of trying to hack the URL as a string (? may not only appear in that one place).
It's then a case of splitting on the & character (and maybe ; too if you want to be nice, as per HTML4 B2.2) and checking each parameter against the one you're looking for. For the general case this requires proper URL-decoding, as g%62n_keywords=... is a valid way of spelling the same parameter. On the way out naturally you will need to encode again, to stop & going on to the next parameter (as well as to include other invalid characters).
Here's a couple of utility functions you can use to cope with query string manipulation more easily. They convert between the ?... string as seen in location.search or link.search and a lookup Object mapping parameter names to arrays of values (since form-url-encoded queries can have multiple instances of the same parameter).
function queryToLookup(query) {
var lookup= {};
var params= query.slice(1).split(/[&;]/);
for (var i= 0; i<params.length; i++) {
var ix= params[i].indexOf('=');
if (ix!==-1) {
var name= decodeURIComponent(params[i].slice(0, ix));
var value= decodeURIComponent(params[i].slice(ix+1));
if (!(name in lookup))
lookup[name]= [];
lookup[name].push(value);
}
}
return lookup;
}
function lookupToQuery(lookup) {
var params= [];
for (var name in lookup)
for (var i= 0; i<lookup[name].length; i++)
params.push(encodeURIComponent(name)+'='+encodeURIComponent(lookup[name][i]));
return params.length===0? '' : '?'+params.join('&');
}
This makes the usage as simple as:
var lookup= queryToLookup(location.search);
lookup['gbn_keywords']= ['coffee & tea'];
var query= lookupToQuery(lookup);
& character is used to seperate key and value pairs in the querystring. So that you can match all the characters except for & by re-writing your code as follows:
querystring=querystring.replace(/gbn_keywords=[^&]+/,"gbn_keywords="+term);
[^&]+ matches one or more characters up to & or end of string. But if there may situations where the querystring data may look like ...?gbn_keywords= (no value) then a slight modification is needed to the above line:
querystring=querystring.replace(/gbn_keywords=[^&]*/,"gbn_keywords="+term);
Just change + to * so that the regex will match 0 or more characters. I think this is better.
Why don't you run a split on url[1] and than replace the value of the gbn_keywords in that new array?
And if you use a JavaScript Framework, there might be a handy function that does all that. In Prototype there is the function toQueryParams().
I have returned object from signature device and when i make quick watch on it, it told me that its an array of long and when i pass it to web method in my code behind (vb.net) it gives me nothing.
i need some help..
note: i'm using an activeX to capture the signature from the device.
this is javascript code :
function OnSave() {
var sign = document.FORM1.SigPlus1.SignatureString;
PageMethods.Save(sign);
}
this is my webmethod:
<WebMethod()> _
Public Shared Function Save(ByVal obj As Object) As String
Dim obj1 As New PFSIGNATURELib.SigniShellSignature
obj1.SignatureMime = obj
obj1.SaveBitmapToFile(System.AppDomain.CurrentDomain.BaseDirectory() & "\sign1.bmp", 200, 200)
Return "\sign1.bmp"
End Function
I don't know much about ASP.Net, but it seems like the PageMethods.Save function can't handle an array of long. Another possibility is that the sign variable is null in the javascript code.
Try adding
alert(sign);
in the middle your Javascript function, or better yet, install firebug and do
console.log(sign);
instead. This way you'll make sure the sign var actually contains what you think it does.
If it indeed contains an array of numbers (javascript doesn't have a long type), maybe you need to convert it to something else before calling the PageMethods.Save function.
For example, this javascript snippet will convert sign into a space-separated string of numbers:
s = ""
for (i in sign) {
s += sign[i] + " ";
}
sign = s
If you manage to pass this string to your webmethod, you can use some string parsing to get back the original array.