List<String> Syntax error google script - javascript

I can't get my head around setting up an array in Google script (Which is based off Javascript).
I have a list of countries, 'AU' and 'NZ' that I need in the array, this will be added to later. I will need to search the array later to check if a string matches a value in the array.
I've tried adding the array several ways in Google script.
First attempt:
List<String> country_list = new ArrayList<String>();
country_list.add("AU");
country_list.add("NZ");
This Throws up a Syntax error. on the 1st line.
A variation on this:
Second attempt:
var country_list = [];
country_list.add("AU")
country_list.add("NZ")
Throws up the error TypeError: Cannot find function add in object . on the 2nd line.
Third attempt:
var Country_List = ["AU","NZ"];
if (country_list.contains("AU")) {
// is valid
ui.alert("great success");
} else {
// not valid
ui.alert('Nope try again');
}
This throws up an error 'TypeError: Cannot find function contains in object...'
That makes sense so I tried converting to Array.asList().
Fourth attempt:
var original_country_list = ["AU","NZ"];
List<String> country_list = Arrays.asList(original_country_list)
if (country_list.contains("AU")) {
// is valid
ui.alert("great sucsess");
} else {
// not valid
ui.alert('Nah Mate try again');
}
This throws up the error Invalid assignment left-hand side when using [] and () to hold original_country_list. When using {} to hold original_country_list it throws up the error Missing : after property ID.
The last thing I tried was:
Fifth attempt:
var original_country_list = ["AU","NZ"];
var country_list = Arrays.asList(original_country_list)
and this throws up the error ReferenceError: "Arrays" is not defined.
Apologies if this is obvious but what is going wrong here?

Most of what I see here looks closer to Java than Javascript. But #2 can be Javascript like this:
var country_list = [];
country_list.push("AU");
country_list.push("NZ");
3 can be fixed easily too:
var Country_List = ["AU","NZ"];
if (Country_list.indexOf("AU") > -1) {
// is valid
ui.alert("great success");
} else {
// not valid
ui.alert('Nope try again');
}

Related

How to set multi-select field value using openForm in Dynamics CRM?

I've created Multi-select option-set field (category) in Dynamics CRM on-premise for Contact and Projects. Now using button click I'm trying to set the value of multi-select field on Project. But each time I am coming across with Error:
Error converting value 920650008 to type System.Collections.Generic.List 1[System.Int32].
Since the multi-select optionset field is global so there is no chance of specified values available or not.
Here is what I am trying previously:
var name = formContext.getAttribute(new.account_metada.CompanyName).getValue();
var entityFormOptions["entityName"] = "new_projects";
entityFormOptions["openInNewWindow"] = true;
var formParameters["new_company"] = id;
formParameters["new_companyname"] = name;
formParameters["new_category"] = formContext.getAttribute("new_category").getValue()
Xrm.Navigation.openForm(entityFormOptions, formParameters).then(
function (success) {
console.log(success);
},
function (error) {
console.log(error);
});
Please let me know how to can I set value of multi-select optionset using Xrm.Navigation.openForm
I got fix the issue by replacing below source code line:
Existing
formParameters["new_multiselectpicklist"] = formContext.getAttribute("new_multiselectpicklist").getValue();
Updated
formParameters["new_multiselectpicklist"] = "["+formContext.getAttribute("new_multiselectpicklist").getValue()+"]";
I tested this personally and getting the same error result with the below snippet. Though the syntax is right - Something could be wrong with the Xrm.Navigation.openForm() method or this could be expected behavior because of unsupported Array datatype.
var entityFormOptions = new Array();
entityFormOptions["entityName"] = "my_entity";
entityFormOptions["openInNewWindow"] = false;
var formParameters = new Array();
formParameters["new_multiselectpicklist"] = formContext.getAttribute("new_multiselectpicklist").getValue();
Xrm.Navigation.openForm(entityFormOptions, formParameters).then(
function (success) {
console.log(success);
},
function (error) {
console.log(error);
});
Even a hard code assignment getting the same error:
formParameters["new_multiselectpicklist"] = [962080001, 962080002];
Edit:
The above line should be like this to make it work.
formParameters["new_multiselectpicklist"] = "[962080001, 962080002]";
I tried this alternate option using extraqs and it worked.
https://mycrmdev.crm.dynamics.com/main.aspx?etn=my_entity&pagetype=entityrecord&extraqs=new_multiselectpicklist=[962080001, 962080002]

How to count all non-blank cells using Excel Javascript Addins?

I'm creating an office js addin that inserts data from the bottom of Table 1 into Table 2 but I am unable to find a method of doing this that works.
I have tried using Excel.Functions.countA() but I can't seem to get a value other than NaN out of it. Here is the code I'm using:
async function run() {
try {
await Excel.run(async context => {
var sheet1Name = "Sheet1";
var sheet1RangeAddress = "B:B";
var sheet2Name = "Sheet2";
var sheet2RangeAddress = "A2:P2";
var sheet2Range = context.workbook.worksheets.getItem(sheet2Name).getRange(sheet2RangeAddress);
sheet2Range.insert("Down");
var sheet1CellAddress = context.workbook.worksheets.getItem(sheet1Name).getRange(sheet1RangeAddress).load("address");
var sheet1RangeLength = Number(context.workbook.functions.countA(sheet1CellAddress));
var sheet1LastCell = context.workbook.worksheets.getItem(sheet1Name).getRangeByIndexes(3,1,sheet1RangeLength,1).getLastCell();
var sheet2Cell = context.workbook.worksheets.getItem(sheet2Name).getRange("A2");
sheet2Cell.values = [[ context.workbook.worksheets.getItem(sheet2Name).getRange("A2").copyFrom(sheet1LastCell) ]]
await context.sync();
});
} catch (error) {
console.error(error);
}
}
I can't find anything useful in Microsoft's documentation or a working example online. Does anyone know what I'm doing wrong?
This line in your code looks problematic:
var sheet1RangeLength = Number(context.workbook.functions.countA(sheet1CellAddress));
The Functions.countA method returns an Excel.FunctionResult object which I don't think can be cast to a Number. The count returned by the function will be in the value property of the returned object. You need to load that value to read it. Try these two lines as a replacement:
var sheet1RangeLength = context.workbook.functions.countA(sheet1CellAddress).load("value");
await context.sync();
BTW, the following line is returning a Range object, not an address. That's OK because countA accepts a Range object parameter, but your variable is misleadingly named. Also, I don't think the load("address") on the end is serving any purpose.
var sheet1CellAddress = context.workbook.worksheets.getItem(sheet1Name).getRange(sheet1RangeAddress).load("address");
If you haven't already, please see this article: Call built-in Excel worksheet functions.

Error when decoding base64 with buffer. First argument needs to be a number

I am working on running different encoding statements based on the URL.
My code:
var parsedUrl = url.parse(req.url, true);
var queryAsObject = parsedUrl.query;
var myString = queryAsObject["string"];
var myFunction = queryAsObject["function"];
if (myFunction == "encodeb64") {
var bufEncode = new Buffer(JSON.stringify(myString));
var myEncode = bufEncode.toString('base64');
console.log(myEncode);
}
else {
console.log("Error1");
};
if (myFunction == "decodeb64") {
// var bufDecode = new Buffer(myEncode, 'base64');
// var myDecode = bufDecode.toString('utf8');
var myDecode = new Buffer(myEncode, 'base64').toString('utf8');
console.log(myDecode);
}
else {
console.log("Error2");
};
URL used: http://127.0.0.1:8020/?string=text&function=decodeb64
The issue is that I am having is with the last if statement. If its looking for decodeb64 and the first statement is looking for encodeb64 it crashes when function=decodeb64 is in the URL. If both if statements are looking for either encodeb64 or decodeb64, it runs perfectly. It also works if function=encodeb64 is in the URL.
The error message I get is:
buffer.js:188
throw new TypeError('First argument needs to be a number, ' +
^
It points to:
var myDecode = new Buffer(myEncode, 'base64').toString('utf8');
The given number on the error is pointed to the n in new.
I have located the problem to be inside the decode if statement by moving and reversing the order on the code.
As you can see in my code notes, I have tried two different methods of decoding with no success.
The reason that it crashes I believe is that when function=decode64, the variable myEncode is not declared and initialized, as the if(myFunction=="encode64") block is not run.
So when the code tried to new Buffer(myEncode...) it would fail as myEncode is undefined.
I think you meant to code :
var myDecode = new Buffer(myString, ...)
instead

Call a Stored Procedure in HANA

I am trying to call a stored procedure in java from my .xsjs file. The procedure gets 2 input parameters and returns one. I can call it from an SQL console without any problem by writing:
call "MYSCHEMA"."MyPackage.procedures::addUserC50" ('name', 'lastname', ?)
This is the code in my .xsjs file, I think that it fails in the prepareCall statement. I have tried different combinations (with and without double quotation marks, with and without the name of the schema/package, with and without "(?,?,?)", with and without "{ }".... But nothing works, I always get the 500 Internal server error when I try to execute it.
Does anybody know where the error is or what is the exact syntax for the prepareCall method?
var output = 0,
query = "";
var conn;
var cstmt;
try {
conn = $.db.getConnection();
query = "{ call \"MYSCHEMA\".\"MyPackage.procedures/addUserC50\"(?,?,?) }";
cstmt = conn.prepareCall(query); // <-- Fails
cstmt.setString(1, userName);
cstmt.setString(2, userLastname);
cstmt.execute();
output = cstmt.getInteger(3);
conn.commit();
$.response.status = $.net.http.OK;
$.response.setBody("Successfully created: " + output);
}
catch (e) {
$.response.status = $.net.http.BAD_REQUEST;
$.response.setBody("0");
}
finally {
if (cstmt !== null)
cstmt.close();
if (conn !== null)
conn.close();
}
This is the error that gives back: InternalError: dberror(Connection.prepareCall): 328 - invalid name of function or procedure: MyPackage.procedures/addUserC50: line 1 col 18 (at pos 17) at ptime/query/checker/check_call.cc:21
According to this documentation, it should be something like
var myCallableStatement = myconnection.prepareCall("{call myprocedure(?)}");
Thank you
I managed to make it run, this is the syntax that worked:
query = "call \"MyPackage.procedures::addUserC50\"(?, ?, ?)";
Thank you for your help #shofmn
There could be different reasons why the call is failing. You can investigate your error much easier if you return the error message in the HTTP response. You can do this easily:
try {
// Your code execution here
}
catch (e) {
$.response.contentType = "text/html";
$.response.setBody(e.name + ": " + e.message));
}
If the error message doesn't help you solving the problem, paste the error message in here so that it is more easy for us to investigate as well.

Invalid object initializer issue in jquery get request?

I want to code an html button with jQuery, when chart button is pressed, will take values from some text inputs, prepare a json of them and will perform a get request including the json with values.
$(".chart").click(function(){
var args = {}
args['fx'] = $("#tolerancia").val()
args['a'] = $("#a").val()
args['b'] = $("#b").val()
args['tolerancia'] = $("#tolerancia").val()
args['iteracionesMaximas'] = $("#iteracionesMaximas").val()
$.get("/taylor",{args},function(resultado){
console.log(resultado)
})
})
I'm getting an Invalid object initializer message in console right on line of:
$.get("/taylor",{args},function(resultado){
What have I got wrong?
Change your code to:
$.get("/taylor", args, function(resultado) {
console.log(resultado)
});
Note: {args} is invalid syntax. args is already an object, so you don't need to wrap it in any other brackets.

Categories

Resources