how to use GUID in oData query and parse JSON as well - json

I try to figure out how to deal with Odata query and XMLhttprequet in dynamics CRM
However, whatever I tried to do, eventially hasn't been working.
So, the trouble is how to send a oDAta query with GUID by creating a XMLhttprequest.
I checked that from lookup in the next code GUID gof record gets as well.
Also, I noticed that oData query works well too, I think it because I have some issue by dealing with JSON. I wonder, does it work sinchronically in my way?
Eventially, I'd like to parse a responseText in order to get a "new_address1" variable.
actually this code works fine if I change GUID on a text data of a lookup, but it's not the best solution cos sometimes it duplicates
Did anyone use a GUID in a oData queries?
thanks in advance
function test()
{
//take a value from lookup
var lookupItem = new Array();
lookupItem = Xrm.Page.getAttribute("custom").getValue();
var name = lookupItem[0].id;
var oDataPath = "http://`ServerName`/`Organization`/xrmservices/2011/OrganizationData.svc/AccountSet(guid'" + name + "')";
var retrieveRecordsReq = new XMLHttpRequest();
retrieveRecordsReq.open("GET", oDataPath, true);
retrieveRecordsReq.setRequestHeader("Accept", "application/json");
retrieveRecordsReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
retrieveRecordsReq.onreadystatechange = function () {
if (this.readyState == 4) {
if (this.status == 200) {
var retrievedRecords = JSON.parse(retrieveRecordsReq.responseText).d;
var address = retrievedRecords.results[0].new_address1;
alert(address);
}
}
};
retrieveRecordsReq.send();}

The OData Query Designer and XrmServiceToolkit are two excellent, freely available resources out there to do the heavy lifting for you.
A bit of google research with the above and you should get further than you have.

Related

Crossfilter - Loading a JSON file from localStorage

I'm fairly new to Javascript and I'm trying to create a simple bar chart with d3.js using some data saved in the localStorage.
The data in the localStorage is acquired by the following function:
function logScore() {
var name = prompt("Please enter your name to add to the high scores list:");
var score = game.count;
var gameDate = today;
var scoreObj = { name: name, score: score, date: gameDate };
scoresArray.push(scoreObj);
window.localStorage.setItem('scoresRecord', JSON.stringify(scoresArray));
}
In a separate Javascript file, I parse the JSON object in order to store the object in an array.
var scoreData = JSON.parse(window.localStorage.getItem('scoresRecord'));
queue()
.defer(d3.json, "scoreData")
.await(makeGraph);
function makeGraph(error, scoreData) {
var ndx = crossfilter(scoreData);
var name_dim = ndx.dimension(dc.pluck('name'));
var score_dim = ndx.dimension(dc.pluck('score'));
var date_dim = ndx.dimension(dc.pluck('date'));
dc.barChart("#high-score-chart")
.width(300)
.height(150)
.margins({ top: 10, right: 50, bottom: 30, left: 50 })
.dimension(date_dim)
.group(score_dim)
.transitionDuration(500)
.x(d3.scale.ordinal())
.xUnits(dc.units.ordinal)
.xAxisLabel("Date")
.yAxisLabel("Score");
dc.renderAll();
}
Once loaded, I then try to use the data in a d3.js barchart using crossfilter, but I get the below error from the console:
https://ifd-project-simon-georgefairbairn.c9users.io/scoreData 404 (Not Found)
I think I'm loading the data correctly, but I wondered if anyone would be able to let me know if I can use crossfilter and d3.js with a JSON object stored in localStorage, and if so how?
Thanks for taking the time to read my problem - hoping someone can help!
If you're able to get the data synchronously, loading it from local storage, then you don't need queue() and d3.json
You should be able to do
var scoreData = JSON.parse(window.localStorage.getItem('scoresRecord'));
var ndx = crossfilter(scoreData);
The error you're getting indicates that d3.json is trying to do an HTTP request for the data. In this case, you don't need d3.json because JSON parsing is built into the language.
If you were using CSV data, then you might use the synchronous parse version d3.csv.parse. There is no d3.json.parse because it's provided directly by the language.

Google Translate free api assist

I am kind of new to javascript and building websites, I program c# most of the times.
I am trying to build something and I need to use google translate api, the problem that is cost money so I prefer use Free API so I found this.
https://ctrlq.org/code/19909-google-translate-api
so I changed it a bit and tried alone, because I wasn't sure what e type ment.
so this is my code:
function doGet(text) {
var sourceText = text;
var translatedText = LanguageApp.translate('en', 'iw', sourceText);
var urllog = "https://translate.googleapis.com/translate_a/single?client=gtx&sl="
+ "en" + "&tl=" + "iw" + "&dt=t&q=" + encodeURI(text);
var result = JSON.parse(UrlFetchApp.fetch(urllog).getContentText());
translatedText = result[0][0][0];
console.log(translatedText);
}
so the url is downloading me a text file called "f.txt" that include the translate code the problem is that I doesnt want it to download File,
I just need the translate inside the txt file its gives me,
also the problem is I am not sure how to get that info inside a javascript variable, And I doesnt want it to give me that file as well..
So how Can I read it?
how can I use the file without download it, and How can I push it to a string variable?
And How I can cancel the download and get only the translate?
THANKS!
By the way
and if anyone know the function doGet(e) that I showed on the link, what is "e"? what does the function wants?
I know I'm a year late but I came to same problem and fixed it using PHP. I have created this simple PHP function:
function translate($text, $from, $to) {
if($text == null)
echo "Please enter a text to translate.";
if($from == null)
$from = "auto";
if($to == null)
$to = "en";
$NEW_TEXT = preg_replace('/\s+/', '+', $text);
$API_URL = "https://translate.googleapis.com/translate_a/single?client=gtx&sl=" . $from . "&tl=" . $to . "&dt=t&q=" . $NEW_TEXT;
$OUTPUT = get_remote_data($API_URL);
$json = json_decode($OUTPUT, true); // decode the JSON into an associative array
$TRANSLATED_OUTPUT = $json[0][0][0];
echo $TRANSLATED_OUTPUT;
}
Example usage (English to Spanish):
translate("Hello", "en", "es"); //Output: Hola
/*
sourceLanguage: the 2-3 letter language code of the source language (English = "en")
targetLanguage: the 2-3 letter language code of the target language (Hebrew is "iw")
text: the text to translate
callback: the function to call once the request finishes*
* Javascript is much different from C# in that it is an asynchronous language, which
means it works on a system of events, where anything may happen at any time
(which makes sense when dealing with things on the web like sending requests to a
server). Because of this, Javascript allows you to pass entire
functions as parameters to other functions (called callbacks) that trigger when some
time-based event triggers. In this case, as seen below,
we use our callback function when the request to google translate finishes.
*/
const translate = function(sourceLanguage,targetLanguage,text,callback) {
// make a new HTTP request
const request = new XMLHttpRequest();
/*
when the request finishes, call the specified callback function with the
response data
*/
request.onload = function() {
// using JSON.parse to turn response text into a JSON object
callback(JSON.parse(request.responseText));
}
/*
set up HTTP GET request to translate.googleapis.com with the specified language
and translation text parameters
*/
request.open(
"GET",
"https://translate.googleapis.com/translate_a/single?client=gtx&sl=" +
sourceLanguage + "&tl=" + targetLanguage + "&dt=t&q=" + text,
true
);
// send the request
request.send();
}
/*
translate "This shouldn't download anything" from English to Hebrew
(when the request finishes, it will follow request.onload (specified above) and
call the anonymous
function we use below with the request response text)
*/
translate("en","iw","This shouldn't download anything!",function(translation) {
// output google's JSON object with the translation to the console
console.log(translation);
});

HTTP server response 409 // Google web app

I'm having issues lately with my web app written in Google Apps Script.. From time to time it doesn't load properly and returns a 409 response.. It seems as it has no real reason, it's randomly. If I try to reload the page sometimes it loads properly, sometimes returns 409. The issue also just occurs some days and times. I can't figure out what can be the reason, the only thing I've noticed is that when the issue occurs also Google Apps Script Program seem to be slow / failing (for example takes longer than usual to save a file, sometimes fails on saving or showing logs etc).
Screenshot from web inspector when the issue occurs..
If the issue is on Google's end on their servers I guess there's not much I can do, but still checking if anyone else experienced these issues? Or is there anything I can do?
Also want to make sure it's not in my code.. I'm not in anyway a pro when it comes to programming, but a happy amateur. But if it was in my code, at least in my mind it would fail every time and not just only sometimes? I googles a bit and found on this site that when making POST requests you need to have your parameters correct, I'm using Twilio in my script but it's in a separate function and is not initiated when the script loads and I have it written as the linked documentation suggests..
Inserting some code snippets here - if anyone sees something that looks weird or could be the reason for my issues I would much appreciate your help!
SMS Function - can this be the reason??
function sendSms_(to, body) {
var messages_url = "https://api.twilio.com/2010-04-01/Accounts/ACe5***************/Messages.json";
var payload = {
"To": to,
"Body" : body,
"From" : "Killnoise"
};
var options = {
"method" : "post",
"contentType": "application/x-www-form-urlencoded", //This line I added after reading the linked documentation
"payload" : payload
};
options.headers = {
"Authorization" : "Basic " + Utilities.base64Encode("AC********************:f8be***************")
};
try { UrlFetchApp.fetch(messages_url, options); } catch(Err) {}
return;
}
doGet function - anything wrong here??
function doGet(e){
var staffId = e.parameter.staffId;
var key = e.parameter.key;
var lang = e.parameter.lang
// staffId = "S102", key = "abc"
if(auth_(staffId, key, lang) == true){
var output = HtmlService.createTemplateFromFile('StaffHtml').getRawContent();
/*/
Am I doing right above and below when the output is returned? I'm a bit green
here - should I write this in another way? Not seeing this could be the reason
for my current issue though..
/*/
output = output.replace('{{selectAlert}}', language('selectAlert', lang));
output = output.replace('{{takenAlert}}', language('takenAlert', lang));
output = output.replace('{{declineGivenAlert}}', language('declineGivenAlert', lang));
output = output.replace('{{beta}}', language('beta', lang));
output = output.replace(/{{surgePrompt}}/g, language('surgePrompt', lang));
output = output.replace('<%staffId%>', lang + staffId);
output = output.replace('{{invitationSent}}', language('invitationSent', lang));
output = output.replace('{{timeOutAlert}}', language('timeOutAlert', lang));
output = output.replace('{{newNotifications}}', language('newNotifications', lang));
var out = HtmlService.createHtmlOutput(output)
.addMetaTag('viewport', 'width=device-width, initial-scale = 1, user-scalable = no')
.setTitle('Killnoise').setXFrameOptionsMode(HtmlService.XFrameOptionsMode.DEFAULT);
return out;
} elseĀ {
return HtmlService.createHtmlOutput('Invalid URLS');
}
}

Only fetch objects with specified keys in Firebase from large index

I have an array = [ 'something', 'other' ]
And I want to retrieve only the values of those 2 ids from Firebase, which contains more than 2 items ( potentially millions ), but if I do this:
var questionRef = new Firebase(fireBaseURL+"/morethanamillionitems/");
loadUID.once('value', function (dataSnapshot) {
dataSnapshot.forEach(function(childSnapshot) { // Firebase method
console.log(dataSnapshot.numChildren()); // potentially outputs 1.000.000 +
var uid = childSnapshot.name();
var childData = childSnapshot.val();
console.log(uid.indexOf('something'));
result.push(uid)
});
}
I first basically load the whole database, which is not that efficient
Now I could do:
array.forEach(key, function() {
var questionRef = new Firebase(fireBaseURL+"/morethanamillionitems/"+key);
refID = questionRef.val();
result.push(refID);
})
Or maybe:
questionRef = new Firebase(fireBaseURL+"/morethanamillionitems/");
array.forEach(key, function() {
if ( questionRef.child(key) !== null ){
refID = questionRef.val();
result.push(refID);
}
})
The last one seems the nicest, the previous one seems a bit expensive on the old RAM.
However, I apparently have to call questionRef.once('value', function(){}) each time, hence already loading the whole document-root...
Or am I misunderstanding how Firebase handles these requests? is the .numChildren() just an answer directly from the server?
Is the .forEach actually remotely executed?
I'm wondering if there is any other way to reduce traffic per request. Which brings me to another question: it seems that firebase searches locally first, but eventually will search remotely, but it's not clear when this exactly happens. Does it periodically check if something has changed? Or will that only happend when I use .on() and not .once().
Or am I using the wrong backend for this purpose? Any other suggestions? I tried hood.ie which is still very beta, looked at Parse but firebase seemed to have the simplicity I need.
(sorry for the sloppy syntax, but you can see what I intended)
[update]
I now have this:
load: function(uids){
var FB = new Firebase(URL);
uids.map(function(uid) {
var currentRef = FB.child( uid+"/_current" );
currentRef.once('value', function (each) {
eachVal = each.val()
if (eachVal !== null){
var localSave = {};
localSave[uid] = eachVal;
this.saveLocal(localSave)
} else {
console.error("Not found: [%s]", uid)
}}, function (err) { });
});
}
But I'm still wondering when the request actually happens, on .child()? or in .once() and if the latter, what is the use of .child() exactly? It seems it's only used for referencing.
Then the second thing, if I want to retrieve an array of a hundred items, this would still mean a hundred seperate requests? or does Firebase have a way of collecting requests and then send them in a batch?
In that last case .once would be a more 'conservative' option for initial retrieval, then later you could attach a .on listener if you need real-time updates.

JSONP and invalid label

Using mootools and JsonP I get "invalid label" error in Firefox Error console
JsonP seems to work (I get the data correctly)
{"jsondata":[{"title":"title1","link":"http://xxxx.xxx.xxx","thumbsrc":"http://xxxx.xxx.xxx/17_t.jpg" ,"description":".......","pubDate":"2009-03-09 06:26:00",},{"title":"title2","link":"http://xxxx.xxx.xxx","thumbsrc":"http://xxxx.xxx.xxx/16_t.jpg" ,"description":".......","pubDate":"2009-03-09 06:08:09",}]}
but I get the Invalid label error on "jsondata"
the same file works good with request.json
comma removed... nothing
this is the code I'm using
window.addEvent('domready', function() {
var gallery = $('gallery');
new JsonP('http://myjsoncodeurl',{
onComplete: function(jsonObj) {
addImages(jsonObj.jsondata);
}
}).request();
var addImages = function(images) {
images.each(function(image) {
var el = new Element('div', {'class': 'item'});
var name = new Element('h3').inject(el);
var a1 = new Element('a', {'href': image.link,'html': image.title}).inject(name);
var desc = new Element('span', {'html': image.description}).inject(name, 'after');
var a2 = new Element('a', {'href': image.link}).inject(desc,'after');
var img = new Element('img', {'src': image.thumbsrc}).inject(a2);
el.inject(gallery);
});
};
});
it works with normal request.Json, but JSONP that doesn't like my code :(
the same file works good with
request.json
With JSONP, your response should be returning a JavaScript function call (i.e. callback) with the JSON data passed in as the argument. If your response is a plain old JSON text, it won't work in the context of JSONP. You have to tailor your backend to accept a callback argument and call that callback with the JSON data.
You need to put brackets (normal ones, not curly ones) around your object, because sometimes Javascript gets horribly confused and thinks you're doing a label statement, a statement type that I didn't know existed until I Googled this problem.
https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Statements#label_Statement
Try passing your object, {"jsondata":[ ... ]} , as ({"jsondata":[ ... ]}) instead. That seems to sort it.
Putting it in here:
http://json.parser.online.fr/
Shows that its valid, but has the extra comma (which will bork IE, although FF should handle it). If removing the comma doesn't fix it, you'll need to post more of your code to help us find the error.
This could be due to the extra commas after the dates