how to get label of optionset in crm - dynamics-crm

I'm using D-CRM 2016 I'm trying to get a label of optionset in client-side (js) ,I get an error and can't find a reason why:
thats my code:
SDK.Metadata.RetrieveAttribute("myEntity", "myFieldName", null, false,
function (result) {
alert(result);
for (var i = 0; i < result.OptionSet.Options.length; i++) {
var loopText = result.OptionSet.Options[i].Label.LocalizedLabels[0].Label;
var loopValue = result.OptionSet.Options[i].Value;
}
},
function (error) { }
,false);
My error:
Uncaught TypeError: _Context(...).getServerUrl is not a function
at _getUrl (/SDev/%7B636656731400000359%7D/WebResources/xnes_SDK.MetaData?ver=1561501807:451)
at Object.RetrieveAttribute (/SDev/%7B636656731400000359%7D/WebResources/xnes_SDK.MetaData?ver=1561501807:323)
at <anonymous>:1:14
at Mscrm.CommandHandler.$Ce_1 (JsProvider.ashx:8)
at Mscrm.CommandHandler.$Ag_1 (JsProvider.ashx:8)
at Mscrm.CommandHandler.handleCommand (JsProvider.ashx:8)
at Mscrm.CommandBarData.executeCommand (JsProvider.ashx:8)
at Mscrm.ButtonControl.executeCommand (ribbon.js:1)
at Mscrm.ButtonControl.click (ribbon.js:1)
at Mscrm.CommandBar.onClickHandler (ribbon.js:1)

Anytime you're attempting to do client side rest calls, I always recommend Jason Lattimer's CRM Rest Builder (https://github.com/jlattimer/CRMRESTBuilder) You can access the text labels using the "Formatted Values" option.

The principal problem is with the SDK you are using. I can't really debug it for you.
However, here's a working sample that is returning the label and the value. There a header (Prefer) you can add to tell the api to return the label as well:
var odataEndPoint = Xrm.Page.context.getClientUrl() + '/api/data/v8.2/';
function GetDomainName(entityId) {
var result = null;
var req = new XMLHttpRequest();
req.open("GET", odataEndPoint + 'systemusers(' + TrimGuid(entityId) + ')/', false);
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Prefer", "odata.include-annotations=\"OData.Community.Display.V1.FormattedValue\"");
req.onreadystatechange = function () {
if (this.readyState == 4) {
req.onreadystatechange = null;
if (this.status == 200) {
if (this.response) {
result = JSON.parse(this.response);
}
}
else {
var parsed = JSON.parse(this.response);
console.error(parsed.error.message)
}
}
};
req.send();
return result;
};

Related

image upload to a .NET server

This is the code I'm using. How do I specify the .NET server address which should receive the image?
var form = document.forms.namedItem("fileinfo");
form.addEventListener('submit', function(ev) {
var oOutput = document.querySelector("div"),
oData = new FormData(form);
oData.append("CustomField", "extra data");
var oReq = new XMLHttpRequest();
oReq.open("POST", "abcd", true);
oReq.onload = function(oEvent) {
if (oReq.status == 200) {
oOutput.innerHTML = "Uploaded!";
}
else
{
oOutput.innerHTML = "Error " + oReq.status + " occurred when trying to upload your file.<br \/>";
}
};
oReq.send(oData);
ev.preventDefault();
}, false);
Create a generic handler. In ProcessRequest event, put this base code
public void ProcessRequest(HttpContext context)
{
HttpPostedFile doc = context.Request.Files[0];
//Your code....
doc.SaveAs("YOUR_PATH" + "/" + doc.FileName);
}
The ajax post should go to this resource...

How many API Request is considered by Parse.com?

I have a cloud code written
Parse.Cloud.define("getApartmentVendorProduct", function(request, response) {
var isApartmentCallComplete = false;
var isVendorCallComplete = false;
var isProductCallComplete = false;
var result = {};
var apartmentQuery = new Parse.Query("Apartment");
apartmentQuery.find({
success: function(results) {
isApartmentCallComplete = true;
results.apartments = results;
}
});
var vendorQuery = new Parse.Query("Vendor");
vendorQuery.find({
success: function(results) {
isVendorCallComplete = true;
results.vendors = results;
}
});
var productQuery = new Parse.Query("Product");
productQuery.find({
success: function(results) {
isProductCallComplete = true;
results.products = results;
}
});
setInterval(function () {
if (isApartmentCallComplete && isVendorCallComplete && isProductCallComplete) {
response.success(results);
}
}, 50);
});
PS: I'm well aware that setInterval wont work on Parse.. This code is just for understanding.
In this cloud function i'm making 3 Query operation.
From my Android application i'm calling this cloud code.
Here is my question.
How many API request is this considered?
1) 3 API Request made by cloud code and 1 API Request made by Android - Total 4
2) Just 1 API Request made by Android. - Total 1
The option is 1 it makes 4 requests.
I tried with a sample code to test Burst Limit
Parse.Cloud.define("testBurstLimit", function(request, response) {
var globalI = 0;
for(var i = 0; i < 500; i++) {
var productQuery = new Parse.Query("Product");
productQuery.find({
success: function(results) {
console.log("success " + i + " " + globalI);
globalI++;
if (globalI == 250) {
response.success("success");
}
},
error: function(error) {
isApartmentCallComplete = true;
if (isApartmentCallComplete && isVendorCallComplete && isProductCallComplete) {
console.log(error.message + " " + error.code);
}
}
});
}
});
One thing strange i noticed is that. Parse doesn't calculate requests/second, instead it calculates in Requests per/min. Check the response from Parse when i perform the BurstLimit cloud code again and again
{"code":155,"error":"This application performed 1814 requests over the last 28s, and exceeded its request limit. Please retry in 32s"}

Ajax is correctly returning and displaying data but error message is being activated

I'm performing AJAX using the following code:
function main() {
// get the name fields
var name1 = document.getElementById("name1").value;
var name2 = document.getElementById("name2").value;
// Encode the user's input as query parameters in a URL
var url = "response.php" +
"?name1=" + encodeURIComponent(name1) +
"&name2=" + encodeURIComponent(name2);
// Fetch the contents of that URL using the XMLHttpRequest object
var req = createXMLHttpRequestObject();
req.open("GET", url);
req.onreadystatechange = function () {
if (req.readyState == 4 && req.status == 200) {
try {
// If we get here, we got a complete valid HTTP response
var response = req.responseText; // HTTP response as a string
var text = JSON.parse(response); // Parse it to a JS array
// Convert the array of text objects to a string of HTML
var list = "";
for (var i = 0; i < text.length; i++) {
list += "<li><p>" + text[i].reply + " " + text[i].name + "</p>";
}
// Display the HTML in the element from above.
var ad = document.getElementById("responseText");
ad.innerHTML = "<ul>" + list + "</ul>";
} catch (e) {
// display error message
alert("Error reading the response: " + e.toString());
}
} else {
// display status message
alert("There was a problem retrieving the data:\n" + req.statusText);
}
}
req.send(null);
}
// creates an XMLHttpRequest instance
function createXMLHttpRequestObject() {
// xmlHttp will store the reference to the XMLHttpRequest object
var xmlHttp;
// try to instantiate the native XMLHttpRequest object
try {
// create an XMLHttpRequest object
xmlHttp = new XMLHttpRequest();
} catch (e) {
// assume IE6 or older
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHttp");
} catch (e) {}
}
// return the created object or display an error message
if (!xmlHttp) alert("Error creating the XMLHttpRequest object.");
else return xmlHttp;
}
This works exactly as planned, the code within the try block is executed perfectly. But the alert "There was a problem retrieving the data: is also activated, with req.statusText displaying "OK".
How can this be possible? How can the code within the if statement activate perfectly but at the same time the else block is activated?
I'm stumped, any ideas?
The servor code is simply:
<?php
if( $_GET["name1"] || $_GET["name2"] ) {
$data = array(
array('name' => $_GET["name1"], 'reply' => 'hello'),
array('name' => $_GET["name2"], 'reply' => 'bye'),
);
echo json_encode($data);
}
?>
And the HTML:
<input id="name1">
<input id="name2">
<div id="responseText"></div>
<button onclick="main();">Do Ajax!</button>
Your conditional is probably being activated when req.readyState == 3 (content has begun to load). The onreadystatechange method may be triggered multiple times on the same request. You only care about what happens when it's 4, so refactor your method to only test when that is true:
var req = createXMLHttpRequestObject();
req.open("GET", url);
req.onreadystatechange = function() {
if (req.readyState == 4) {
if (req.status == 200) {
try {
// If we get here, we got a complete valid HTTP response
var response = req.responseText; // HTTP response as a string
var text = JSON.parse(response); // Parse it to a JS array
// Convert the array of text objects to a string of HTML
var list = "";
for (var i = 0; i < text.length; i++) {
list += "<li><p>" + text[i].reply + " " + text[i].name + "</p>";
}
// Display the HTML in the element from above.
var ad = document.getElementById("responseText");
ad.innerHTML = "<ul>" + list + "</ul>";
} catch(e) {
// display error message
alert("Error reading the response: " + e.toString());
}
} else {
// display status message
alert("There was a problem retrieving the data:\n" + req.statusText);
}
}
};
req.send(null);

Retrieve rows in crm2011 subgrid with JScript

As an JScript newbie, I have a problem with a subgrid in MS CRM 2011.
I have a form with a subgrid and in OnSave of that form, I want to loop over all the rows in the subgrid.
How can I do this with JScript ? Or is it possible another way, ex plugin ?
Thx
Here is the sample code which you can do on save of the form
var gridControl = document.getElementById('grdrelatedcontacts').control;
for (var intRowNumber = 0; intRowNumber < gridControl.getRecordsFromInnerGrid().length; intRowNumber++)
for (var intCellNumber = 0; intCellNumber < gridControl.getRecordsFromInnerGrid()[intRowNumber][3].cells.length; intCellNumber++)
alert(gridControl.getRecordsFromInnerGrid()[intRowNumber][3].cells[intCellNumber].outerText);
You can inspect the subgrid values on save by doing the following:
var gridControl = document.getElementById('subgrid_id').control;
var ids = gridControl.get_allRecordIds();
for(i = 0; i < ids.length; i++) {
var cellValue = gridControl.getCellValue('column_name', ids[i]);
// logic
}
Doing this on load is a bit more challenging since subgrids are loaded asynchronously and aren't likely to be done loading when the form onload event fires. You can check the grid periodically though to see when it's done loading by calling a function like the following in your form onload:
function subGridOnload() {
var grid = document.getElementById('subgrid_id');
if (grid.readyState!="complete") {
// delay one second and try again.
setTimeout(subGridOnload, 1000);
return;
}
// logic
}
Use a Rest call and retrieve the corresponding records :S
You can do something like this:
var req = new XMLHttpRequest();
req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.0/pws_streedandhousenodatas?$filter=_pws_streetandhousenumberid_value eq " + Xrm.Page.data.entity.getId(), true);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
req.onreadystatechange = function() {
if (this.readyState === 4) {
req.onreadystatechange = null;
if (this.status === 200) {
var results = JSON.parse(this.response);
for (var i = 0; i < results.value.length; i++) {
var pws_streedandhousenodataid = results.value[i]["pws_streedandhousenodataid"];
}
} else {
Xrm.Utility.alertDialog(this.statusText);
}
}
};
req.send();
In this case the Xrm.Page.data.entity.getId() get you your current record id and you are looking all the lookups (that are in the sub-grid), you can also add some fields to select more info from them.

Control flow with XmlHttpRequest?

XmlHttpRequest works through callbacks. So how can I return a value? I tried to set a global variable, but that doesn't seem to be working.
var response = null; // contains the most recent XmlHttpRequest response
// loads the info for this username on the page
function loadUsernameInfo(username) {
getUserInfo(username);
var profile = response;
if (profile) {
// do stuff
}
else {
indicateInvalidUsername(username);
}
}
getUserInfo() can't return a result, because of the callback:
function getUserInfo(username) {
var request = createRequest();
request.onreadystatechange = userObjFromJSON;
var twitterURL = "http://twitter.com/users/show/" + escape(username) + ".json";
var url = "url.php?url=" + twitterURL;
request.open("GET", url, true);
request.send(null);
}
The callback:
function userObjFromJSON() {
if (this.readyState == 4) {
alert(this.responseText);
response = this.responseText;
}
}
How can I get the response back to loadUsernameInfo()?
You can do synchronous requests, though it is not recommended - the A is for Asynchronous... But the general idea to implement this correctly would be:
var response = null; // contains the most recent XmlHttpRequest response
// loads the info for this username on the page
function loadUsernameInfo(username) {
getUserInfo(username, onLoadUsernameComplete);
}
function getUserInfo(username, oncomplete) {
var request = createRequest();
request.__username = username;
request.onreadystatechange = oncomplete;
var twitterURL = "http://twitter.com/users/show/" + escape(username) + ".json";
var url = "url.php?url=" + twitterURL;
request.open("GET", url, true);
request.send(null);
}
function onLoadUsernameComplete(req) {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
var profile = req.responseXML;
if (profile) {
// do stuff
}
else {
indicateInvalidUsername(req.__username);
}
}
}
}

Resources