JSON data in MS CRM 2011 - javascript

I'm having an issue using JOSN data in MS CRM 2011. I am using the correct REST syntax to pull the CRM data but my JavaScript is the remaining issue.
What I want to do is append data from my JSON to a class of my choosing. I checked the console and no errors are apparent. Originially I believed once I had the JSON object I could pull the data from it using jQuery. Here is the code I currently have:
RetrieveScoutMetadata : (function(scout_displayable){
var query = "/scout_metadataSet?$select=scout_data_type,scout_display_name,scout_display_order,scout_displayable,ImportSequenceNumber,scout_name,scout_metadataId&$orderby=scout_display_order asc&$filter=scout_displayable eq "+scout_displayable+"";
ExecuteQuery(query);
})
RetrieveScoutOpportunity : (function(scout_account){
var query = "/scout_opportunitySet?$select=*&$filter=scout_account/Id eq guid'"+scout_account+"'";
ExecuteQuery(query);
})
RetrieveScoutAccount : (function(scout_account){
var query = "/scout_accountSet?$select=*&$filter=scout_account/Id eq guid'"+scout_account+"'";
ExecuteQuery(query);
})
//
// ExecuteQuery executes the specified OData Query asyncronously
//
// NOTE: Requires JSON and jQuery libraries. Review this Microsoft MSDN article before
// using this script http://msdn.microsoft.com/en-us/library/gg328025.aspx
//
function ExecuteQuery(ODataQuery) {
var serverUrl = Xrm.Page.context.getServerUrl();
// Adjust URL for differences between on premise and online
if (serverUrl.match(/\/$/)) {
serverUrl = serverUrl.substring(0, serverUrl.length - 1);
}
var ODataURL = serverUrl + "/XRMServices/2011/OrganizationData.svc" + ODataQuery;
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: ODataURL,
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, textStatus, XmlHttpRequest) {
//
// Handle result from successful execution
//
// e.g. data.d.results
alert("OData Execution Success Occurred");
},
error: function (XmlHttpRequest, textStatus, errorObject) {
//
// Handle result from unsuccessful execution
//
alert("OData Execution Error Occurred");
}
});
$('.up-sell').append(account.scout_num_up_sells);
}
//
// Error Handler
//
function ErrorHandler(XMLHttpRequest, textStatus, errorObject)
{ alert("Error Occurred : " + textStatus + ": " + JSON.parse(XMLHttpRequest.responseText).error.message.value); }

To get response use "complete" function:
complete: function (jsondata, stat) {
if (stat == "success") {
data = JSON.parse(jsondata.responseText);
}
}

Related

JavaScript AJAX to Coinbase API, getting "request timestamp expired" error using server time

I've been working on some code that will call the List Accounts call from the Coinbase API. I am using the API Key to authenticate and CryptoJSv3.1.2 to handle the encryption. I believe that I am correctly signing my request but I haven't done a lot of encryption in JavaScript before so please double check my work.
The issue that I am having is that my request for accounts is being rejected and the message I'm getting back from Coinbase is {"errors":[{"id":"authentication_error","message":"request timestamp expired"}]}
I am aware the of the 30 second restriction for requests however I am using the Coinbase server time that I am getting back from the Get Current Time call. Also, the total run time for both calls is <1 second so my timestamp should be the current time. Any guidance would be very helpful. Thanks in advance.
Here is my code:
var LOGIN_DATA = {
Coinbase: {
apiKey: "XXXXXXXXXXXXXXXX",
apiSecret: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
version: "2018-01-05"
}
}
var Coinbase = new (function(){
var cb = this;
var baseURL = "https://api.coinbase.com/v2";
this.listAccounts = function(){
var start = new Date();
var method = "GET";
var url = baseURL + "/accounts";
var header = buildRequestHeader(method, url);
var accounts = connect(method, url, header);
var finish = new Date();
console.debug("time elapsed: ", (finish.getTime() - start.getTime()))
return accounts;
}
function buildRequestHeader(method, url, data){
var timeStamp = getServerTime();
console.debug("timeStamp: ", timeStamp)
var header = {
"CB-ACCESS-KEY": LOGIN_DATA.Coinbase.apiKey,
"CB-ACCESS-SIGN": buildSignature(timeStamp, method, url, data),
"CB-ACCESS-TIMESTAMP": timeStamp
}
console.debug("header: ", header);
return header;
}
function buildSignature(timeStamp, method, requestPath, data){
var message = timeStamp + method.toUpperCase() + requestPath + (data == null ? "" : data)
console.debug("signature message: ", message);
var hash = CryptoJS.HmacSHA256(message, LOGIN_DATA.Coinbase.apiSecret);
var hashInBase64 = CryptoJS.enc.Base64.stringify(hash);
return hashInBase64
}
function getServerTime(){
var method = "GET"
var url = baseURL + "/time";
var onSuccess = function(data){
return (new Date(data.data.iso)).getTime();
}
return connect(method, url, null, null, onSuccess);
}
function connect(method, url, header, data, onSuccess, onError){
var rtn = null;
header = (header == null ? {} : header)
data = (data === null ? {} : data)
if(header["CB-VERSION"] === undefined){
header["CB-VERSION"] = LOGIN_DATA.Coinbase.version
}
console.debug("final header: ", header);
console.debug("final data: ", data);
$.ajax({
url: url,
type: method,
async: false,
timeout: 5000,
data: data,
beforeSend: function(xhr) {
for(var key in header){
xhr.setRequestHeader(key, header[key]);
}
},
success: function(data, textStatus, jqXHR) {
console.log("Coinbase connect successful: ", data);
if(!onSuccess){
onSuccess = function(data){ return data; }
}
rtn = onSuccess(data, textStatus, jqXHR);
},
error: function(jqXHR, textStatus, errorThrown) {
console.error("Coinbase connect failed: ", textStatus, errorThrown, jqXHR);
if(onError){
rtn = onError(jqXHR, textStatus, errorThrown);
}
}
});
return rtn;
}
});
Also here is a screenshot of my console log statements incase they help:
Quoting the Coinbase API:
The CB-ACCESS-TIMESTAMP header MUST be number of seconds since Unix Epoch.
Your timestamp is in milliseconds, not seconds.
If I'm not mistaken the signature should be encoded in hex, not base64 (source):
var hash = CryptoJS.HmacSHA256(message, LOGIN_DATA.Coinbase.apiSecret);
var hexDigest = hash.toString(CryptoJS.enc.Hex)

jquery ajax inside loop return statusText error, Status 0 after certain time in IE

I m trying to update bulk of data one by one using Jquery ajax,so that i can show update progress. every thing goes well at beginning but after 5 min, it throw an error like in
Image while checking network request/respond:.
Error on error function of ajax:.
MainData is array of json object and is contain around 3000 number of json object.
function DoPost()
{
$.each(MainData, function (key, value) {
var mainCode = value.MainCode;
var companyCode = value.CompanyCode;
$.ajax({
url: "Allotment.asmx/DoAllotment",
data: "{MainCode:'" + mainCode + "', sNoOfAllotment:'" + noOfAllot + "',CompanyCode:'" + companyCode + "'}",
dataType: 'text',
contentType: "application/json; charset=utf-8",
type: "Post",
success: function (res){
Progress(res); // this funtion will show progress of update.
},
error: function (res) {
console.log(res);
}
});
});
}
I am using web service of asp.net webform
The issue could be maximum number of concurrent connections to same URL. You can schedule next $.ajax() call when current $.ajax() completes.
See also multiple, sequential fetch() Promise
function DoPost(value) {
var mainCode = value.MainCode;
var companyCode = value.CompanyCode;
return $.ajax({
url: "Allotment.asmx/DoAllotment",
data: "{MainCode:'" + mainCode + "', sNoOfAllotment:'"
+ noOfAllot + "',CompanyCode:'" + companyCode + "'}",
dataType: 'text',
contentType: "application/json; charset=utf-8",
type: "POST",
success: function(res) {
Progress(res); // this funtion will show progress of update.
},
error: function(res) {
console.log(res);
}
});
}
var copy = MainData.slice(0);
var res = (function re(value) {
return DoPost(value).then(function() {
return copy.length ? re(copy.shift()) : "complete"
})
})(copy.shift());
res.then(function(complete) {
console.log(complete)
}, function(err, textStatus, jqxhr) {
console.log(err)
});
The error 0x2ee2 is IE's representation of timeout error. The occurrence of this error shows that the server has stopped responding to the requests due to a high number of requests sent from the same client. This is the server avoiding DOS attacks from the client.
The proper method is to optimize the code and try to utilize the maximum available bandwidth in order to minimize the number of requests to the server.

Javascript Create and Update Record In Dynamics CRM from Custom Button

I have a requirement to create and update some records from custom button. This custom button placed on homepage of the contact. First, i need to check one or more contact. Once the custom button is clicked, its creating an account in account entity then update look up field of the contact that i checked before with account that we create.
I am trying the step inside this link and this, but it's seem doesn't work for Dynamics CRM 2016 on-premis
Could you please help me and give me a suggestion or another documentary that you think it can satisfy my requirement above.
EDITED:
on the sdk, there is an example to use JQueryRestDataOperation. From there, i write a code like this:
function createAccount() {
startButton.attr("name");
var account = {};
account.Name = "Test Account Name";
account.Description = "This account was created by the JQueryRESTDataOperations sample.";
//Create the Account
SDK.JQuery.createRecord(
account,
"account",
function (account) {
writeMessage("The account named "" + account.Name + "" was created with the AccountId : "" + account.AccountId + "".");
writeMessage("Retrieving account with the AccountId: "" + account.AccountId + "".");
retrieveAccount(account.AccountId)
},
errorHandler
);
}
I add this code as webresource in my solution, then call it from custom button. But nothing happen.
Thanks
To Create Account you can use code given below. On click of button give call to function CreateAccount()
function CreateAccount() {
var accountId, accountName;
var context = Xrm.Page.context;
var serverUrl = context.getServerUrl();
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
var CRMObject = new Object();
/////////////////////////////////////////////////////////////
// Specify the ODATA entity collection
var ODATA_EntityCollection = "/AccountSet";
/////////////////////////////////////////////////////////////
// Define attribute values for the CRM object you want created
CRMObject.Name = "TEST";
accountName = "TEST";
CRMObject.Telephone1 = "123";
CRMObject.Fax = "456";
//Parse the entity object into JSON
var jsonEntity = window.JSON.stringify(CRMObject);
//Asynchronous AJAX function to Create a CRM record using OData
$.ajax({ type: "POST",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: serverUrl + ODATA_ENDPOINT + ODATA_EntityCollection,
data: jsonEntity,
beforeSend: function (XMLHttpRequest) {
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, textStatus, XmlHttpRequest) {
alert("success");
var NewCRMRecordCreated = data["d"];
accountId = NewCRMRecordCreated.AccountId;
UpdateContact(accountId,accountName);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("failure");
}
});
}
To Uppdate contact
function UpdateContact(accountId, accountName) {
var serverUrl = Xrm.Page.context.getServerUrl().toString();
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
var ODATA_EntityCollection = "/AccountSet";
var objContact = new Object();
// set the name of Account
objContact.Id = Xrm.Page.data.entity.getId();
// set the Primary Contact lookup field
objContact.AccoutId = { Id: accountId, LogicalName: "account", Name: accountName };
// Parse the entity object into JSON
var jsonEntity = window.JSON.stringify(objContact);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: serverUrl + ODATA_ENDPOINT + ODATA_EntityCollection,
data: jsonEntity,
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (response) {
if (response != null && response.d != null) {
alert(response.d.ContactId);
}
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus + "; ErrorThrown: " + errorThrown);
}
});
}

On Save of when creating account record create a task (capturing current time and user in description field) using odata

**
function task()
{
var date=Date.now();
var accountid=Xrm.Page.data.entity.getId();
var entity = {};
entity.Description = date;
entity.Subject = "Hi.....";
entity.RegardingObjectId = {
Id:accountid,
LogicalName: "account"
};
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: Xrm.Page.context.getClientUrl() + "/XRMServices/2011/OrganizationData.svc/TaskSet",
data: JSON.stringify(entity),
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
async: false,
success: function (data, textStatus, xhr) {
var result = data.d;
var newEntityId = result.TaskId;
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus + " " + errorThrown);
}
});
}
//I try to get date from system and inserted in to task description but it showing.
Blockquote
Error bad request
Blockquote
so please help me out ,thanks in advance.
the statement :
var date=Date.now();
captures current date and time and returns as DateTime format.
here is where you went wrong
entity.Description = date;
entity.Description accepts sting only ..not datetime try converting the variable to string with toString() also check the other possible methods
check for demo
instead of var date=Date.now(); we can use `var date=Date();' it will work.
Instead of var date=Date.now(); we can use var date=Date();

Retrieving Records From Entity in Dynamics Crm using odata and jquery

I want to print the values retrieved from my entity in an alert message.I store the values in relatedproduct array i want to print these value.When it try to print them it gives undefined message.Plz help me
relatedProducts = [];
function onload() {
var oDataUri="https://yanceyworksllc.crm.dynamics.com/xrmservices/2011/OrganizationData.svc/ProductSet?$select=new_price,ProductId&$filter=new_TaxInformation/Value eq 1";
GetRecords(oDataUri);
var totalRecords = relatedProducts .length;
}
function GetRecords(url) {
jQuery.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: url,
async: false,
beforeSend: function (XMLHttpRequest) {
var x= XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, textStatus, XmlHttpRequest) {
if (data && data.d != null && data.d.results != null) {
AddRecordsToArray(data.d.results);
FetchRecordsCallBack(data.d);
}
},
error: function (XmlHttpRequest, textStatus, errorThrown) {
// FetchRecordsCallBack(data.d);
alert("Error : has occured during retrieval of the records ");
}
});
}
function AddRecordsToArray(records) {
for (var i = 0; i < records.length; i++) {
relatedProducts .push(records[i]);
alert(relatedProducts[i].Value) ;
}
}
function FetchRecordsCallBack(records) {
if (records.__next != null) {
var url = records.__next;
GetRecords(url);
}
}
A very easy way to troubleshoot OData calls is to copy the URI into your browser and navigate to the page. If it does not bring you to a page with data, that means your uri is wrong. If it does, then you are handling the resulting data incorrectly (ie if the debugger hits the success block in GetRecords, then your AddRecordsToArray or FetchRecordsCallBack is broken).
Side note - I have never seen a space before a ".[Attribute Name]". Is that even a valid JavaScript syntax (as in your relatedProducts .push or relatedProducts .length)?

Categories