Create SharePoint document location using Client API (JavaScript) in Powerapps - javascript

In a model-driven powerapp I’m trying to create SharePoint document location using JavaScript and Client API that should be related to a custom entity.
Here is my code:
**//creates records in table via WebAPI call
function createRecordForTable(tableName, dataObj) {
// create table record
Xrm.WebApi.createRecord(tableName, dataObj).then(
function success(result) {
console.log("Record created with ID: " + result.id);
},
function (error) {
console.log(error.message);
}
);
}
//myresponse is object that holds some of needed values
//hel__exceptions is custom entity
const data = new Object();
data.name = myresponse.name;
data.relativeurl = myresponse.relativeurl;
data.absoluteurl = myresponse.absoluteurl;
data["parentsiteorlocation_sharepointdocumentlocation#odata.bind"] = "/sharepointdocumentlocations/(" + myresponse.sharepointdocumentlocationid + ")";
data["regardingobjectid_hel__exceptions#odata.bind"] = "/hel__exceptionses/(" + exceptionId +")";
data.sitecollectionid = myresponse.sitecollectionid;
createRecordForTable("sharepointdocumentlocation", data);**
The error received is: Empty segment encountered in request URL. Please make sure that a valid request URL is specified.
It looks like I’m missing some data that I need to pass with the call Xrm.WebApi.createRecord in order to create the record in sharepointdocumentlocation table.
Please help!

Related

iterating and extracting data from xml in javascript on mirth

I'm using mirth connect 3.7, java version 1.8. i am new to both mirth and javascript. I have set up a channel destination to a javascript writer to get data out of xml files inserted into a mysql db. a sample section of xml file as follows:
...
<DG1>
<DG1.1>
<DG1.1.1>1</DG1.1.1>
</DG1.1>
<DG1.2>
<DG1.2.1>I10</DG1.2.1>
</DG1.2>
<DG1.3>
<DG1.3.1>R10.9</DG1.3.1>
</DG1.3>
<DG1.4>
<DG1.4.1>UNSPECIFIED ABDOMINAL PAIN</DG1.4.1>
</DG1.4>
<DG1.5/>
<DG1.6>
<DG1.6.1>A</DG1.6.1>
</DG1.6>
<DG1.7/>
<DG1.8>
<DG1.8.1>391</DG1.8.1>
</DG1.8>
<DG1.9/>
<DG1.10/>
<DG1.11>
<DG1.11.1>4252.21</DG1.11.1>
</DG1.11>
<DG1.12/>
<DG1.13/>
<DG1.14/>
<DG1.15/>
<DG1.16/>
<DG1.17/>
<DG1.18>
<DG1.18.1>N</DG1.18.1>
</DG1.18>
</DG1>
<DG1>
<DG1.1>
<DG1.1.1>2</DG1.1.1>
</DG1.1>
<DG1.2>
<DG1.2.1>I10</DG1.2.1>
</DG1.2>
<DG1.3>
<DG1.3.1>R10.9</DG1.3.1>
</DG1.3>
<DG1.4>
<DG1.4.1>UNSPECIFIED ABDOMINAL PAIN</DG1.4.1>
</DG1.4>
<DG1.5/>
<DG1.6>
<DG1.6.1>A</DG1.6.1>
</DG1.6>
<DG1.7/>
<DG1.8>
<DG1.8.1>391</DG1.8.1>
</DG1.8>
<DG1.9/>
<DG1.10/>
<DG1.11>
<DG1.11.1>4252.21</DG1.11.1>
</DG1.11>
<DG1.12/>
<DG1.13/>
<DG1.14/>
<DG1.15/>
<DG1.16/>
<DG1.17/>
<DG1.18>
<DG1.18.1>N</DG1.18.1>
</DG1.18>
</DG1>
...
I am trying to get the datapoints out of the xml iteratively so i can insert these diagnosis codes in a mysql table. my script at this point:
try {
var dbConn = DatabaseConnectionFactory.createDatabaseConnection ('com.mysql.jdbc.Driver', 'jdbc:mysql://127.0.0.1:3306/adt', 'xxx', 'xxx');
var xml = new XML(connectorMessage.getEncodedData());
var myNodeList = xml.querySelectorAll("DG1");
for (i = 0; i < myNodelist.length; i++) {
var myQuery = 'INSERT INTO adt.diagnosis (AcctNum, MRN, ICD10) VALUES ("'+ $('AcctNum') + '", "' + $('MedRecNum') + '", "' + myNodelist[i]['DG1.3']['DG1.3.1'] + '")';
//do something with myVar to get a query...
dbConn.executeUpdate(myQuery);
}
} catch (ex) {
//handle any exceptions...
}
it runs without exceptions but i am not capturing the intended data obviously. Again, new to javascript, mirth and parsing xml. Questions:
obviously, i'm referencing the data points inappropriately, what is the nomenclature in javascript?
is there a dev environment in mirth that i can step through code and better troubleshoot?
are there any good recommended resources for javascript and xml as it pertains to mirth?
Mirth uses Mozilla Rhino for its Javascript engine. Rhino uses a deprecated standard called e4x for XML processing. If you search Google for e4x you'll find several pages at developer.mozilla.org with scary "obsolete" banners everywhere that can be helpful. The mirth user guide is very detailed when it comes to workflow within mirth.
https://github.com/mozilla/rhino
https://web.archive.org/web/20181120184304/https://wso2.com/project/mashup/0.2/docs/e4xquickstart.html (another good e4x resource)
https://www.nextgen.com/products-and-services/NextGen-Connect-Integration-Engine-Downloads (for the user guide)
I'm surprised querySelectorAll wasn't throwing an error. With minimal changes to your code:
try {
var dbConn = DatabaseConnectionFactory.createDatabaseConnection ('com.mysql.jdbc.Driver', 'jdbc:mysql://127.0.0.1:3306/adt', 'xxx', 'xxx');
var xml = new XML(connectorMessage.getEncodedData());
// This should work, but is not typically how hl7 segments are accessed. Would need to see more than a segment for typical usage.
var myNodeList = xml.descendants("DG1"); // returns type XMLList
// length is a function instead of property on XMLList objects
for (i = 0; i < myNodelist.length(); i++) {
var myQuery = 'INSERT INTO adt.diagnosis (AcctNum, MRN, ICD10) VALUES ("'+ $('AcctNum') + '", "' + $('MedRecNum') + '", "' + myNodelist[i]['DG1.3']['DG1.3.1'] + '")';
dbConn.executeUpdate(myQuery);
}
} catch (ex) {
//handle any exceptions...
}
Using a for each loop and parameterized sql statement:
try {
var dbConn = DatabaseConnectionFactory.createDatabaseConnection ('com.mysql.jdbc.Driver', 'jdbc:mysql://127.0.0.1:3306/adt', 'xxx', 'xxx');
var xml = new XML(connectorMessage.getEncodedData());
var myQuery = 'INSERT INTO adt.diagnosis (AcctNum, MRN, ICD10) VALUES (?, ?, ?)';
for each (var dg1 in xml.descendants('DG1')) {
dbConn.executeUpdate(myQuery, new java.util.ArrayList([$('AcctNum'), $('MedRecNum'), dg1['DG1.3']['DG1.3.1'].toString()]));
}
} catch (ex) {
//handle any exceptions...
}
You'll want a finally block after your try to close your database connection. If you remove the catch block, mirth will automatically set the message status to ERROR, write the exception to the server log, and fire an event which you can act on with a defined alert. That's usually easier than trying to handle the exception yourself.
Hi this is not quite right.
First ensure your data type is HL7.
Then do this (this is for insurance but you get the idea)
for each ( in1 in msg['IN1']) {
var effdate = in1['IN1.12']['IN1.12.1'];
// etc
}

ServiceNow UI Page GlideAjax

I created a form using UI Page and am trying to have some fields autopopulated onChange. I have a client script that works for the most part, but the issue arises when certain fields need to be dot-walked in order to be autopopulated. I've read that dot-walking will not work in client scripts for scoped applications and that a GlideAjax code will need to be used instead. I'm not familiar with GlideAjax and Script Includes, can someone help me with transitioning my code?
My current client script looks like this:
function beneficiary_1(){
var usr = g_user.userID;
var related = $('family_member_1').value;
var rec = new GlideRecord('hr_beneficiary');
rec.addQuery('employee',usr);
rec.addQuery('sys_id',related);
rec.query(dataReturned);
}
function dataReturned(rec){
//autopopulate the beneficiary fields pending on the user selection
if(rec.next()) {
$('fm1_ssn').value = rec.ssn;
$('fm1_address').value = rec.beneficiary_contact.address;
$('fm1_email').value = rec.beneficiary_contact.email;
$('fm1_phone').value = rec.beneficiary_contact.mobile_phone;
var dob = rec.date_of_birth;
var arr = dob.split("-");
var date = arr[1] + "/"+ arr[2] + "/" + arr[0] ;
$('fm1_date_of_birth').value = date;
}
}
fm1_address, fm1_email, and fm1_phone do not auto populate because the value is dot walking from the HR_Beneficiary table to the HR_Emergency_Contact table.
How can I transform the above code to GlideAjax format?
I haven't tested this code so you may need to debug it, but hopefully gets you on the right track. However there are a couple of steps for this.
Create a script include that pull the data and send a response to an ajax call.
Call this script include from a client script using GlideAjax.
Handle the AJAX response and populate the form.
This is part of the client script in #2
A couple of good websites to look at for this
GlideAjax documentation for reference
Returning multiple values with GlideAjax
1. Script Include - Here you will create your method to pull the data and respond to an ajax call.
This script include object has the following details
Name: BeneficiaryContact
Parateters:
sysparm_my_userid - user ID of the employee
sysparm_my_relativeid - relative sys_id
Make certain to check "Client callable" in the script include options.
var BeneficiaryContact = Class.create();
BeneficiaryContact.prototype = Object.extendsObject(AbstractAjaxProcessor, {
getContact : function() {
// parameters
var userID = this.getParameter('sysparm_my_userid');
var relativeID = this.getParameter('sysparm_my_relativeid');
// query
var rec = new GlideRecord('hr_beneficiary');
rec.addQuery('employee', userID);
rec.addQuery('sys_id', relativeID);
rec.query();
// build object
var obj = {};
obj.has_value = rec.hasNext(); // set if a record was found
// populate object
if(rec.next()) {
obj.ssn = rec.ssn;
obj.date_of_birth = rec.date_of_birth.toString();
obj.address = rec.beneficiary_contact.address.toString();
obj.email = rec.beneficiary_contact.email.toString();
obj.mobile_phone = rec.beneficiary_contact.mobile_phone.toString();
}
// encode to json
var json = new JSON();
var data = json.encode(obj);
return data;
},
type : "BeneficiaryContact"
});
2. Client Script - Here you will call BeneficiaryContact from #1 with a client script
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
if (isLoading || newValue === '') {
return;
}
var usr = g_user.userID;
var related = $('family_member_1').value;
var ga = new GlideAjax('BeneficiaryContact'); // call the object
ga.addParam('sysparm_name', 'getContact'); // call the function
ga.addParam('sysparm_my_userid', usr); // pass in userID
ga.addParam('sysparm_my_relativeid', related); // pass in relative sys_id
ga.getXML(populateBeneficiary);
}
3. Handle AJAX response - Deal with the response from #2
This is part of your client script
Here I put in the answer.has_value check as an example, but you may want to remove that until this works and you're done debugging.
function populateBeneficiary(response) {
var answer = response.responseXML.documentElement.getAttribute("answer");
answer = answer.evalJSON(); // convert json in to an object
// check if a value was found
if (answer.has_value) {
var dob = answer.date_of_birth;
var arr = dob.split("-");
var date = arr[1] + "/"+ arr[2] + "/" + arr[0];
$('fm1_ssn').value = answer.ssn;
$('fm1_address').value = answer.address;
$('fm1_email').value = answer.email;
$('fm1_phone').value = answer.mobile_phone;
$('fm1_date_of_birth').value = date;
}
else {
g_form.addErrorMessage('A beneficiary was not found.');
}
}

ASP Web Pages Razor using AJAX to return array from Database

I'm working with ASP for my coursework and I am using Razor Web Pages to do an application. Now, I would like some help with retrieving information from the SQL database.
As it stands I make an ajax call like this:
$.ajax({
type: "POST",
url: "/timetabler/Includes/ajaxModulesByUserId",
data: { id: UserId },
success: function (data) {
alert(data);
if (data == "ERROR") {
alert("We are unable to store the theme you have selected, therefore the change will not be permanent.");
}
}
});
This quite simply calls ajaxModulesByUserId.cshtml passing a userID of like 1. Now this calls the file fantastically.
Now what I'm trying to do in my CSHTML is take the requested ID, then use my C# function:
public IEnumerable<dynamic> getAllQuery(string query)
{
return _db.Query(query);
}
To execute my query.
Now I call it in my Razor code like this:
string input = "";
input = Request["id"];
var arr = new List<string>();
if (!string.IsNullOrEmpty(input))
{
// Add new sheet to database
using (var repo = new initDatabase("SQLServerConnectionString"))
{
foreach (var row in repo.getAllQuery("SELECT * FROM Module WHERE userID = " + input))
{
arr.Add(""+row.moduleCode+","+row.moduleTitle+"");
}
#session.Serialize(arr);
}
}
So I return the rows from the database and put them into an array, now my problem is, getting those values to the javascript.
As it stands I'm using a trick I read from here Stackoverflow, by using a function like this:
public static string Serialize(object o)
{
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Serialize(o);
}
This will actually let me see the values in Javascript, but I'm getting stuck as I end up with values like this:
How can I receive a clean array? and possibly even return ALL the rows from the database as I've had to do a messy way of passing the code and title in 1 array field but separated by a comma.
Would really appreciate it if you could help me get my output correct.
Thanks
The Web Pages framework includes a Json helper which can take your data and return it as JSON.
if (!Request["id"].IsEmpty())
{
using (var repo = new initDatabase("SQLServerConnectionString"))
{
var data = repo.getAllQuery("SELECT * FROM Module WHERE userID = #0", Request["id"])
Json.Write(data, Response.Output);
}
}

Using Parse Javascript SDK Query GeoPoint withinMiles

I am creating a Parse App and I want to be able to get all objects within a certain distance of a single object using GeoPoints. Seems simple, but the following code returns [] (No matches):
app.get('/photos', function(req, res) {
var Photo = Parse.Object.extend("Photo");
var query = new Parse.Query(Photo);
query.equalTo("owner", Parse.User.current());
query.find({
success: function(results) {
// Do something with the returned Parse.Object values
//res.send(results);
var photo = results[0];
// Create a query for places
var Photo = Parse.Object.extend("Photo");
var query = new Parse.Query(Photo);
// Interested in photos taken near this photo.
query.withinMiles("coordinates", photo.coordinates, 500000);
// Final list of objects
query.find({
success: function(photoObjects) {
res.send(photoObjects);
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
});
Oddly, if I change the line
query.withinMiles("coordinates", photo.coordinates, 500000);
to
query.near("coordinates", photo.coordinates);
then it works without a hitch and returns all photos (Every single one has a GeoPoint within about a 5 mile radius of all the others in the sample data set, so I used a maxDistance of 500000 to test the extent of the issue).
The problem is I need to be able to limit to a specific radius, which is what I thought the "withinMiles" was doing. Any ideas what I may be doing wrong?
In case someone is finding this and shares my troubles, the following was the issue:
I was assuming that all "columns" of data objects in parse are treated as attributes. i.e. - You can access them using the . operator (photo.coordinates).
In fact, you must access them via photo.get("coordinates") to get the actual objects contained within the data structure.
Not sure why the above scenario was working in the case of the "near" function, but nonetheless the behavior works correctly when I started using the get accessor method for the Parse data objects.

jQuery Appending unwanted data

Some jQuery function in my code is inserting the string:
jQuery15206649508478338135_1314906667378
into user-provided feedback. This is happening from multiple forms and it's getting stored in the database, which is really annoying our users. One sample of such code:
$(".sendFeedback").live("click", function() {
var feedbackText = $(".feedbackText:visible").val();
var errorElement = $(".feedbackError:first");
if (isEmptyTrimmed(feedbackText)) {
errorOut(errorElement, language.pleaseEnterFeedbackText);
return false;
}
var sendFeedback = { email : userSettings.email, firstName : "",lastName : "",primaryRole : "", description : "<br />Feedback text: <pre>" + feedbackText + "</pre>",
sendNotification : false, isPartner : false , formType : 3};
callService("sendFeedback", sendFeedback);
currentMessage = language.thankYouForTheFeedback;
loadScreenByHash("mainScreen");
});
function callService(serviceName, data, callbackFunction) {
var json = $.toJSON(data);
json = "{ " + serviceName + ": " + json + " }";
$.post(serviceUrl, json,
function(response) {
if (callbackFunction) {
callbackFunction(response);
}
}, 'json').error(function() {
if (callbackFunction) {
callbackFunction();
}
});
}
The callService function directs to a Java server, so I'm doubting it's getting inserted there. The java server writes to the DB, so I'm pretty sure it's getting inserted in the javascript code.
It happens other places as well, and they follow the same formula: read user input with .val(), pass to callService (sometimes through additional JS function). A sample of the output data:
I created a quiz but can not figure out how to run it for my class.
there are no buttons that say run
quizjQuery15206649508478338135_1314906667378? Customer Name
I've also seen it appended at the end of a string. Let me know if anyone has seen this before.
I found the cause of the problem. User data was entered, sent to the database, but the database was not set for UTF-8. The problem occurred every time the character encoding was messed up in the database. When the database returned garbage, it would trigger the string to be added.
Changing the database encoding solved this problem.

Categories

Resources