JavaScript Class Objects not returning value - javascript

I've been working with the Microsoft Bot Framework to create a bot that can interface between MS Teams and AWS. I've been trying to write some JS functions but have been unsuccessful in getting them to operate how I want them to.
Here is what I am currently working on and am stuck on:
I am creating a 'ping' like functionality so a bot user can ping an instance in AWS and receive its status whether its running and has passed the system checks or not. My code is currently able to take the user request for the ping, retrieve the information from AWS, and can even print that info to the console. However, when I am trying to retrieve that information back out of the object that I set it to and print it to MS Teams, it says my variable is undefined.
Some code snippets are below:
class aws_Link {
constructor (mT, ping_1, i_state, i_status) {
this.myTag = mT;
this.ping = ping_1;
this.instance_state = i_state; // I declare this here, but should I?
this.instance_status = i_status; // I declare this here, but should I?
}
//i_state and i_status are just passed NULL when the object is initialized
//so they would be holding some value, not sure if I have to do this
api_link () {
var mainLink = API_LINK_TAKEN_OUT_FOR_OBVIOUS_REASONS;
var myTagFill = "myTag=";
var ampersand = "&";
var pingFill = "ping=";
var completeLink = String(mainLink + myTagFill + this.myTag + ampersand + pingFill + this.ping);
var finalLink = completeLink;
finalLink = finalLink.split(' ').join('');
//set up API-key authenticication
var options = {
url: finalLink,
headers: {
'x-api-key': 'AWS-PRIVATE-TOKEN'
}
};
if(this.ping == "TRUE") { // if the user wants to use /ping
var res = request(options, function(error, response, body) {
console.log("PING REQUEST"); //debug
body = JSON.parse(body);
var h_state = body['instanceState'];
var h_status = body['instanceStatus'];
this.instance_state = h_state;
this.instance_status = h_status;
console.log("STATE: " + h_state); //debug
console.log("STATUS: " + h_status); //debug
});
}
}
pingFunction () {
var tmp = "Instance State: " + this.instance_state + " Instance Status: " + this.instance_status;
return tmp;
}
}
And here is where I call the api_link() function and pingFunction():
var apiLink1 = new aws_Link("MY_TAG_VALUE", "TRUE", "NULL", "NULL");
var completeAPILink = apiLink1.api_link();
session.send('Request complete.');
session.send("PING: " + apiLink1.pingFunction());
So essentially the user enters in some info which gets passed to where I create the "new aws_Link" which then a my understanding is, creates an object called apiLink1. From there, it makes the request to AWS in my api_link() function, which retrieves the info I want. I thought I was then saving this info when I do the: this.instance_state = h_state; & this.instance_status = h_status;. So then when I call pingFunction() again on apiLink1, I thought I would be able to retrieve the information back out using this.instance_state and this.instance_status, but all it prints out is undefined. Any clarification on why my current code isn't working and any changes or improvements I can make would be greatly appreciated.
Thanks!

Related

How do I access a data nested in JSON in javascript?

I have been trying to figure this out for hours. I've seen this SO question and I still cannot figure this out.
I have some Jason data that I know begins like this:
{
"0x123454843eacf5c5318e1234504251b937d12345": [
{
"poolIndex": 0,
"stakingStrategy": "masterchef",
"farmName": "sushiChef",
....
I've written the following to get at the information like "poolIndex" and "stakingStrategy":
function parseTheDataFunctionSushi(walletAddress, networkName){
// calls a funciton to pull and parse the api data
var walletAddress = "0x123454843eacf5c5318e1234504251b937d12345";
var networkName = "polygon";
var theparsedJSONdata = pullAndParseAPISushi(walletAddress, networkName)
console.log("object keys are " + Object.keys(walletAddress));
var firstCrack = theparsedJSONdata[walletAddress][0]['poolIndex']
console.log("firstCrack is " + firstCrack)
This does not work. I've written firstCrack every way I can think of
theparsedJSONdata[walletAddress].poolIndex
theparsedJSONdata[walletAddress][0].poolIndex
None of them work. So frustrating. Any help would be appreciated.
For what it's worth, `Object.keys(walletAddress) returns
object keys are 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41
Here's the other function:
function pullAndParseAPISushi (walletAddress, networkName){
console.log("walletAddress inside pullAndParseAPISushi is = " + walletAddress);
console.log("network is " + networkName);
var apiKEY = "96e0cc51-a62e-42ca-acee-910ea7d2a241"; // API key from Zapper
var url = "https://api.zapper.fi/v1/staked-balance/masterchef?addresses%5B%5D="+ walletAddress + "&network=" + networkName + "&api_key=" + apiKEY;
// assembles the API URL with the wallet addressa, network and name
console.log("url is " + URL);
var response = UrlFetchApp.fetch(url); // pulls data from the API
console.log(response)
var theparsedJSONdata = JSON.parse(response); // parses the JSON response from the API
console.log(theparsedJSONdata)
return theparsedJSONdata
}
If the data structure is indeed as you specified, then one of the attempts you tried should work. See below for a functional example.
const data = {
"0x123454843eacf5c5318e1234504251b937d12345": [
{
"poolIndex": 0,
"stakingStrategy": "masterchef",
"farmName": "sushiChef",
}
]
}
const walletAddress = "0x123454843eacf5c5318e1234504251b937d12345";
console.log(data[walletAddress][0].poolIndex);
console.log(data[walletAddress][0].stakingStrategy);
Have you tried?
theparsedJSONdata.walletAddress[0].poolIndex
don't have enough rep to make a comment but I think this might work, let me know!

update spreadsheet in serverside code run from client html javascript not working

I have an html where user requests add and enters data. The javascript in the body of the html calls the server side. I am unable to connect with the sheet either with saved ID or URL in order to add the row.
I cannot update of my spreadsheet despite #Serge insas comment that openById "it means "open for read and write". Am I making a simple mistake or is this impossible. The code initiated from the client side is running in the server.
const ssId = PropertiesService.getScriptProperties().getProperty('ssId');
var sheet = SpreadsheetApp.openById("[ssId]").getSheetByName('Sheet1');
const ssId = PropertiesService.getScriptProperties().getProperty('ssId');
var sheet = SpreadsheetApp.openById("ssId").getSheetByName('Sheet1');
Both get Error: Exception: Unexpected error while getting the method or property openById on object SpreadsheetApp.
const ssUrl = PropertiesService.getScriptProperties().getProperty('ssUrl');
var sheet = SpreadsheetApp.openByUrl("ssUrl").getSheetByName('Sheet1');
Gets error: Exception: Invalid argument: url
ABOVE IS THE IMPORTANT PART
/**
* this code is run from the javascript in the html dialog
*/
function addMbrCode(myAddForm) {
// removed logging
console.log("Beginning addMbrCode" );
paragraph = body.appendParagraph('Beginning addMbrCode.');
// Exception: Unexpected error while getting the method or property openById on object SpreadsheetApp.
// const ssId = PropertiesService.getScriptProperties().getProperty('ssId');
// var sheet = SpreadsheetApp.openById("[ssId]").getSheetByName('Sheet1');
// var sheet = SpreadsheetApp.openById("ssId").getSheetByName('Sheet1');
// Exception: Invalid argument: url
const ssUrl = PropertiesService.getScriptProperties().getProperty('ssUrl');
var sheet = SpreadsheetApp.openByUrl("ssUrl").getSheetByName('Sheet1');
myAddForm = [ fName, lName, inEmail, fallNum, winNum, sprNum];
var fName = myAddForm[0];
var lName = myAddForm[1];
var inEmail = myAddForm[2];
var fallNum = myAddForm[3];
var winNum = myAddForm[4];
var sprNum = myAddForm[5];
var retCd = '';
/**
* 10 - successful add
* 20 - duplicate - not added
*/
var combNameRng = sheet.getRange(2, 4, numRows).getValues();
var inCName = (fName + '.' + lName).toString().toLowerCase();
if (combNameRng.indexOf(inCName) > 0 ) {
console.log("Alert: Not adding duplicate "
+ fName + ' ' + lName + " retCd: " + 20 );
paragraph = body.appendParagraph("Not adding duplicate "
+ fName + ' ' + lName + " retCd: " + 20);
retCd = 20;
return retCd;
}
sheet.appendRow([fName.toString().toLowerCase()
, lName.toString().toLowerCase()
,
, inEmail.toString().toLowerCase()
]);
const currRow = sheet.getLastRow().toString();
);
retCd = 10;
return retCd;
}
If this makes a difference, here is the javascript from the body of my html in the dialog window.
<script>
document.querySelector("#myAddForm").addEventListener("submit",
function(e)
{
alert('begin addEventListener');
e.preventDefault(); //stop form from submitting
var retCd = google.script.run.addMbrCode(this); // client side validation
document.getElementById('errMsg').textContent = 'Successful member
return false; // do not submit - redisplay html
}
);
</script>
Removed unneeded coding detail
Per #iansedano I created an object/array to use instead of this and added the successhandler and failurehandler. In either case I want to see the html again with my message. This is the current script. Response is so doggy I am not seeing alerts, Logger.log, or console.log. Crazy shoppers using my internet!
<script>
document.querySelector("#myRmvForm").addEventListener("submit",
function(e)
// removed alerts and logging
// removed client side validation for simplicity
cSideValidate();
// Then we prevent the form from being submitted by canceling the event
event.preventDefault();
});
function cSideValidate() {
dataObj = [
document.getElementById('fName').value,
document.getElementById('lName').value,
document.getElementById('email').value
];
var retCd = google.script.run.withSuccessHandler(serverReply)
.withFailureHandler(serverReply)
.rmvMbrCode(dataObj); // server side validation
}
function serverReply {
// logic to set the correct message - this is an example
document.getElementById('errMsg').textContent
= 'Successful delete using email.';
}
</script>
Nothing is being added to my spreadsheet so the server side code is not working. I see my loggin so I know it is getting there.
You're getting ssId from the script properties and assigning it to the ssId variable, but then you pass a string ("ssId") to the openById() function, not the value of the variable.
Try the following please:
const ssId = PropertiesService.getScriptProperties().getProperty('ssId');
var sheet = SpreadsheetApp.openById(ssId).getSheetByName('Sheet1');

Uncaught TypeError: Cannot read property 'toLowerCase' of undefined when adding object to field in Sharepoint

I want to fill a nintex form people picker field automatically using JavaScript on a SharePoint page.
The problem is that I keep getting an error:
When I click on the first link, it shows this
In the formMain.js, the error is caused by this line:
ins.add(object);
I've been trying for hours to fix this issue, but I can't find a solution.
As you can see in the console, ins and the object are both defined.
Here's the JavaScript I use to add the user to the field:
var personProperties;
function onChangeProductManagement() {
var curvalue = NWF$('#' + TeilnehmerStatus10).find("input:checked").val();
var ins = new NF.PeoplePickerApi('#' + TeilnehmerName10);
if (curvalue == "offen") {
SP.SOD.executeFunc('SP.js', 'SP.ClientContext', function() {
// Make sure PeopleManager is available
SP.SOD.executeFunc('userprofile', 'SP.UserProfiles.PeopleManager', function() {
// Replace the placeholder value with the target user's credentials.
var targetUser = "opmain\\eoblae";
// Get the current client context and PeopleManager instance.
var clientContext = new SP.ClientContext.get_current();
var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
// Get user properties for the target user.
// To get the PersonProperties object for the current user, use the
// getMyProperties method.
personProperties = peopleManager.getPropertiesFor(targetUser);
// Load the PersonProperties object and send the request.
clientContext.load(personProperties);
clientContext.executeQueryAsync(onRequestSuccess, onRequestFail);
});
});
} else {
console.log("Test2");
console.log("NWF value: " + NWF$('#' + TeilnehmerName10).val());
}
}
// This function runs if the executeQueryAsync call succeeds.
function onRequestSuccess() {
var accountName = personProperties.get_accountName();
var displayName = personProperties.get_displayName();
var email = personProperties.get_email();
var object = { value: accountName, label: displayName, type: "user", email: email };
console.log("object: ", object);
var ins = new NF.PeoplePickerApi('#' + TeilnehmerName10);
console.log("ins: ", ins);
ins.add(object);
}
// This function runs if the executeQueryAsync call fails.
function onRequestFail(sender, args) {
console.log("Error: " + args.get_message());
}
Any help is appreciated!
Adding the id in var object fixed the issue.

Creating record using JS and JSON not correctly using owner value

I'm attempt to create a record in Dynamics 365 using JavaScript however the Owner field is not being set properly. The record creates just fine if I remove the setting of the 'ownerid' field. I have also tried formatting the guid both in lowercase and uppercase with no success (see comments in code). The fields are displayed as expected in the alert.
When the script is run both with the code that makes the guid lowercase or not, I get the following error:
Error: An error occurred while validating input paramters: Microsoft.OData.ODataException: A node of type 'StartArray' was read from the JSON reader when trying to read the contents of the property 'ownerid'; however, a 'StartObject' node or 'PrimitiveValue' node with null value was expected.
var managingDirector = Xrm.Page.getAttribute("new_managingdirector").getValue();
var md_id = managingDirector[0].id;
var md_name = managingDirector[0].name
var md_entityType = "systemuser"
//md_id = md_id.replace(/[{}]/g,"");
//md_id = md_id.toLowerCase();
//md_id = "{" + md_id + "}";
if (managingDirector != null) {
console.log(managingDirector[0]);
alert("MD is " + md_name + " with id " + md_id + " and type " + md_entityType);
} else {
alert("MD is null");
}
var md_owner = new Array();
md_owner[0] = new Object();
md_owner[0].name = md_name;
md_owner[0].id = md_id;
md_owner[0].entityType = md_entityType;
var data =
{
"new_name": "Sample Practice Management",
"new_totalamountdue": amountDue,
"new_deductions": deductionAmount,
"new_deductionsnotes": deductionNotes,
"ownerid": md_owner
}
// create pm record
Xrm.WebApi.createRecord("new_practicemanagement", data).then(
function success(result) {
alert("Practice Management record created with ID: " + result.id);
// perform operations on record creation
},
function (error) {
alert("Error: " + error.message);
// handle error conditions
}
);
When I attempt to restructure the data variable like this (with both lowercase and uppercase ID)
var data =
{
"new_name": "Sample Practice Management",
"new_totalamountdue": amountDue,
"new_deductions": deductionAmount,
"new_deductionsnotes": deductionNotes,
"ownerid": {
name: md_name,
id: md_id,
entityType: md_entityType
}
}
I get the following error:
An error occurred while validating input paramters: Microsoft.OData.ODataException: Does not support untyped vvalue in non-open type.
When I see your code you have data i.e field and it's value as below
var data =
{
"new_name": "Sample Practice Management",
"new_totalamountdue": amountDue,
"new_deductions": deductionAmount,
"new_deductionsnotes": deductionNotes,
"ownerid": md_owner
}
Now if you look at my code owner id is set as
entity["ownerid#odata.bind"] = "/systemusers(58127B9D-AFBC-E811-A958-000D3AB42BE8)";
Below is the code which worked for me, I just tried creating contact record.
var entity = {};
entity.firstname = "Webapi1";
entity["ownerid#odata.bind"] = "/systemusers(58127B9D-AFBC-E811-A958-000D3AB42BE8)";
Xrm.WebApi.online.createRecord("contact", entity).then(
function success(result) {
var newEntityId = result.id;
},
function(error) {
Xrm.Utility.alertDialog(error.message);
}
);
To make your life easier w.r.t developement try CRMRESTBuilder you will find most of your code auto generated here.

firebase: How to get a reference key for an object node

// Creates local "temporary" object for holding employee data
var newTrain = {
tname: trainName,
dest: destination,
firstTime: firstTrainTime,
freq: frequency
};
// Uploads train data to the database
trainDataBase.ref().push(newTrain);
THIS IS THE PART I CAN"T figure out how do I get a key for the object I just created on the server? I tired the below but it comes back undefined, also also tired var = newKey = trainDatabase.ref.push(newTrain).key but then it creates to object versus one but I do get a key
// newKey = trainDataBase.ref(newTrain).key
// console.log("nodeKey" , newKey)
// Alert
console.log("train successfully added");
// Clears all of the text-boxes
$("#trainName").val("");
$("#destination").val("");
$("#firstTrainTime").val("");
$("#frequency").val("");
// Prevents moving to new page
return false;
});
Perhaps there's a better way, but I've used this to make it work:
var trainDataBaseRef = trainDataBase.ref().push();
trainDataBaseRef.set({
id: trainDataBaseRef.key,
// rest of object data
});
Take a look at their docs for an additional way to do this (Updating or deleting data section):
function writeNewPost(...) {
var postData = {
// data
};
// Get a key for a new Post.
var newPostKey = firebase.database().ref().child('posts').push().key;
// Write the new post's data simultaneously in the posts list and the user's post list.
var updates = {};
updates['/posts/' + newPostKey] = postData;
updates['/user-posts/' + uid + '/' + newPostKey] = postData;
return firebase.database().ref().update(updates);
}

Categories