How to pass date variable in uri for Microsoft graph request? - string

I'm trying to get back a list of calendar events with Microsoft Graph API but having problems with passing date variable in the query parameters.
If I hardcode the uri value to:
uri: 'https://graph.microsoft.com/beta/me/calendar/events?$filter=start/dateTime ge ' + `'2018-12-10T19:30:34.654Z'`,
then the request works. But if I try to pass the date variable with toISOString, I get an error. I've tried with or without backticks, and calling toISOString in the uri value and in the nextMonday function. Still doesn't work. Anyone have any ideas? Thanks!
function nextMonday(date){
var monday = new Date(date);
monday.setDate(monday.getDate() + (1 + 7 - monday.getDay()) % 7);
return monday.toISOString();
}
let date = new Date();
let m = nextMonday(date);
const options = {
uri: 'https://graph.microsoft.com/beta/me/calendar/events?$filter=start/dateTime ge ' + `m`,
auth: {
bearer: token,
},
headers: {
'content-type': 'application/json'
},
json: true // Automatically parses the JSON string in the response
};

You need to (1) use ${m} to add the value and (2) wrap it in single quotes.
uri: https://graph.microsoft.com/beta/me/calendar/events?$filter=start/dateTime ge '${m}',

Related

Storing a specific part of a dict value into a string

import requests
import json
url = "********"
payload = json.dumps({
"username": "*****",
"password": "*****"
})
headers = {
'Content-Type': 'application/json'
}
response = requests.request("POST", url, headers=headers, data=payload)
#*** Convert response into a dictionary ***
r = json.loads(response.text)
# *** print the value of they key 'accessToken'
bearerToken = r['accessToken']
print(bearerToken)
Output
{'accessToken': 'e************************************', 'tokenType': 'Bearer'}
What am I trying to achieve?
Grab only the censored code after 'accessToken' and store the new Access Token in a string to use it in HTTP requests.
Note: 'accessToken' is a value of another key called accessToken. So the traditional method of printing the value of the key has already been used in the output shown above.
Complete output:
{
"accessToken" : {
"accessToken" : "e******************",
"tokenType" : "Bearer"
},
"refreshToken" : {
"id" : "6*************",
"lastAccessedTime" : 1***********,
"refreshToken" : "e*************"
}
}
In Python, you can use substrings to accomplish what you want. If the length of the prefix is constant, then all you would need to do is use a slice with constant index,
In your example, it looks like you have an accessToken key, and inside that key is another dictionary holding a key that can change between entries. Assuming that you want the censored portion after e in accessToken, you can access that using:
bearerToken = r['accessToken'][accessToken][1:]
This will give you the access token "******************", which is everything from index 1 onwards. If you just want the entire string, you can omit the [1:] portion.
The solution was to edit the code provided by yeeshue99, the 2nd value to 'accessToken' with the '' marks. the [1:] was also not needed.
Solution
bearerToken = r['accessToken']['accessToken']

Multiple urls in a get request with axios.all, how do I match response.data to its appropriate url object?

I am building a tool to use for work. Basically I upload a csv to extract details which will act as parameters in an axios get request.
I am using multiple urls in axios.all, and my problem is I cannot match up the reponse data to each object of that specific url. The details are below with code snippets. I hope I've made it clear enough below, but this has to do with mass requesting many urls at once, and receiving response data. The problem lies in matching up that response data to its correct url from which it was called.
Here we go...to start, I am mapping an array of vehicle data I am uploading from an external csv file. 'resultsArray' is my array and it holds the year, make, model, trim, price, a url to locate the original posting, and location of the vehicle.
let vehicle_specs = resultsArray.map(function(d, index) {
let values = {
year: d['Title_name'].split(' ')[0], // Iterate with bracket notation
make: d['Title_name'].split(' ')[1],
model: d['Title_name'].split(' ')[2],
trim: d['Title_name'].split(' ')[3],
price: d['Title_Price'],
cl_url: d['Title_Price_url'],
cl_location: d['Title_Location'],
}
return values;
});
I use the new keyword to create an object of the vehicle.
let Vehicle = function(year, make, model, trim, price, url, cl_url, cl_location) {
this.year = year;
this.make = make;
this.model = model;
this.trim = trim;
this.price = price;
this.url = url;
this.cl_url = cl_url;
this.cl_location = cl_location;
}
I then build the object with a new instance of Vehicle and return each vehicle as I need it to be.
let vehicle_data = vehicle_specs.map(function(s) {
let url = `http://api.marketcheck.com/v2/stats/car?api_key={}&ymm=${s.year}|${s.make}|${s.model}`;
let new_vehicle = new Vehicle(`${s.year}`, `${s.make}`, `${s.model}`, `${s.trim}`, `${s.price}`, `${url}`, `${s.cl_url}`, `${s.cl_location}`);
return new_vehicle;
});
I extract the URL's in the following code snippet and use axios.all to request data from each one.
let urls = vehicle_data.map(function(m) {
return m.url;
})
let options = {
'method': 'GET',
'headers': {
'Host': 'marketcheck-prod.apigee.net'
}
};
axios.all(urls.map(url => {
request(url, options, function (error, response, body) {
if(error) {
console.log(error);
} else {
console.log(response);
}
});
}))
My Problem:
I am using a 3rd Party API (Marcketcheck) - Holds data on vehicles.
The response data comes back (See below as an example. This is data for just 1 url)
{"price_stats":{"geometric_mean":3413,"min":899,"median":3595,"population_standard_deviation":1323,"variance":1750285,"ax":7995,"mean":3655,"trimmed_mean":3572,"standard_deviation":1323,"iqr":1800},"miles_stats":{"geometric_mean":97901,"min":2,"median":125000,"population_standard_deviation":51713,"variance":2147483647,"max":230456,"mean":125182,"trimmed_mean":125879,"standard_deviation":51713,"iqr":74734},"dom_stats":{"geometric_mean":100,"min":1,"median":100,"population_standard_deviation":399,"variance":159152,"max":2513,"mean":247,"trimmed_mean":162,"standard_deviation":399,"iqr":217},"count":101}
I cannot figure out how to match up each response data to the vehicle object of that specific url.
For example, if I request 3 urls from the vehicle object. Let's name them:
Url-1
Url-2
Url-3
I get my response data back as objects:
OBJ-1
OBJ-2
OBJ-3
I have no way as far as I know with my level of knowledge, how to assign each object back to it's specific URL and THEN, match up that OBJ data with it's specific vehicle.
I haven been beating my head against a wall for about 4 days, I cannot figure this out.
Any suggestions are welcome and I really appreciate anybody looking at this post to help out.
Check this out
let requests = urls.map((url) => {
return axios.get(url, {
headers: {
'Host': 'marketcheck-prod.apigee.net'
}
});
});
Promise.all(requests).then((responces) => {
console.log(responces);
}).catch((err) => {
console.log(err)
});

bing news search API

How does the "freshness" parameter of the Bing news search API work?
I am writng a program to call the Bing news search API.
I set the "freshness" parameter to be "Month". Yet, Bing returned content that can be as old as 6 months ago. How did I find out? I use the offset parameter to retrieve the last new pages of the returned result and found out that they are can be as old as 6 months (some even 2 years odl). Clarly, this result is contradict to the fresness parameter that I put in. Can anyone shed some light on this? Many thanks,
The following is the code snippet:
Basically, I set the freshness to be Month (freshness=Month) and sort the output by day (sortBy=Day).
let bing_news_search = function (search) {
console.log('Searching news for: ' + term);
let request_params = {
method: 'GET',
hostname: host,
path: path + '?q=' + encodeURIComponent('Microsoft') +'&count=100'+'&freshness=Month'+'&sortBY=Date'+'&offset=4979900',
headers: {
'Ocp-Apim-Subscription-Key': subscriptionKey,
}
Moving this to the Answer as verified in comments:
The issue is that the &count is set to 100. The current limit is 50. Once setting this number correctly the API will work as expected.
So it will look like so:
let bing_news_search = function (search) {
console.log('Searching news for: ' + term);
let request_params = {
method: 'GET',
hostname: host,
path: path + '?q=' + encodeURIComponent('Microsoft') +'&count=50'+'&freshness=Month'+'&sortBY=Date'+'&offset=4979900',
headers: {
'Ocp-Apim-Subscription-Key': subscriptionKey,

Dialogs OData Set name?

Ok in crm 2011 using Odata Query - if a workflows Odata Set name is AsyncOperationSet What is the equivalent for a dialog?
I have tried to figure this out with no luck
Please help
Thank you
P.s I need to get the dialogs id from its name
When searching for a dialog to launch via javascript:
Category = 1 (Dialog)
Type = 1 (Definition) - This is important if trying to call a dialog from javascript!
Solution:
triggerDialog = function (name, entityName, recordId) {
var dialogId = "";
var request = Xrm.Page.context.getServerUrl() + "/XRMServices/2011/OrganizationData.svc/WorkflowSet?$select=Name,WorkflowId&$filter=Type/Value eq 1 and Category/Value eq 1 and Name eq '"+name+"'";
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: request,
async: false,
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, textStatus, XmlHttpRequest) {
if (data.d.results.length > 0) {
dialogId = data.d.results[0].WorkflowId;
}
},
error: function (XmlHttpRequest, textStatus, errorThrown) {
/*Error Occurred*/
}
});
var serverUrl = Xrm.Page.context.getServerUrl();
window.showModalDialog(
serverUrl + "/cs/dialog/rundialog.aspx?DialogId=" + encodeURIComponent(dialogId) + "&EntityName=" + encodeURIComponent(entityName) + "&ObjectId=" + encodeURIComponent(recordId), null, "dialogHeight:600px;dialogWidth:800px;center:yes; resizable:1;maximize:1;minimize:1;status:no;scroll:no");
Hope this helps
Just for your information. AsyncOperation is not instances of workflows only. It could be anything that is executed asynchronously (async plugins, calculating of matchcodes for dupdetection rules and many other).
Not sure what exactly do you want to get from Odata. What exactly do you need to get? If you need an instance of dialog - you will need to use AsyncOperation as well.

CRM 2011 - setting a default value with JScript

We have CRM 2011 on premise. The Contact entity was customized to use a lookup to a custom entity Country instead of just a text field. When creating a new Contact we would like the country field to be set to Canada by default. I have the following function that does that:
function SetDefaultCountryCode(countryFieldId) {
var _canadaId = "{FC167B4D-1C3B-E111-8904-F2EA3FE25706}";
var countryControl = Xrm.Page.getAttribute(countryFieldId);
// only attempt the code if the control exists on the form
if (countryControl != null) {
var currentCountry = countryControl.getValue();
// if country is not specified, then set it to the default one (Canada)
if (currentCountry == null) {
var defaultCountry = new Object();
defaultCountry.entityType = "cga_country";
defaultCountry.id = _canadaId;
defaultCountry.name = "Canada";
var countryLookupValue = new Array();
countryLookupValue[0] = defaultCountry;
countryControl.setValue(countryLookupValue);
}
}
}
On the form OnLoad I invoke the function like that:
// set Country fields to Canada if not set
SetDefaultCountryCode('cga_address1country');
We have two servers - DEV and TEST. This JScript works fine in DEV. When I run it in TEST it does not work because the Canada in TEST has different id (GUID) - when I create it manually. I was hoping I could export the Country entity values from DEV and import them in TEST preserving their GUIDs. Unfortunately this did not work. I export the data to Excel file and it has the GUIDs of the countries. I also delete any existing Country records in TEST before importing. When I try to import it the import succeeds but does not create any records. If I add a new row in the excel file without specifing a Guid it will import it. It seems to me the import functionality was not meant to preserve the GUIDs of the records. But this also means my script will not work because it depends on the GUIDs.
I have two questions here:
Is it possible to export / import entity data preserving the GUIDs ?
If I cannot have the same GUIDs in DEV and TEST how I can make the JScript to work properly?
Thank you in advance for any help / feedback.
It's very bad practice to hard code your GUIDs and you discovered the problems of it.
As you stated above, we cannot have the same GUIDs but we have the same name. So, we have to query the name of the country using JScript and jQuery to retrieve the GUID.
In order to retireve information from client-side (or Entity Form):
We will use/consume REST Endpoint (testing in browser).
Upload jQuery lib.
Upload Json2 lib.
Use the AJAX function from the jQuery library.
Define your entity, columns and criteria.
Lets, look for querying REST Endpoint.
http://yourHostName/yourOrg/XRMServices/2011/OrganizationData.svc/new_CountrytSet?$select=new_Name,new_CountryId&$filter=new_Name eq 'Canada'
Take this URL, subsitute your actual values and paste it into your browser, you'll find that the response is returned in XML format. If there is any error, please ensure that the Entity name and its attribute are case senisitve.
After seeing your your results, we are going to call this URL using an AJAX call.
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: 'http://yourHostName/yourOrg/XRMServices/2011/OrganizationData.svc/new_CountrytSet?$select=new_Name,new_CountryId&$filter=new_Name eq 'Canada'',
beforeSend: function (XMLHttpRequest) {
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data) {
if (data.d && data.d.results) {
//var _canadaId = "{FC167B4D-1C3B-E111-8904-F2EA3FE25706}"; no longer be used
var _canadaId = data.d.results[0].ContactId;
// now we have the GUID of Canada, now I can continue my process
}
},
error: function (XmlHttpRequest) {
alert("Error : " + XmlHttpRequest.status + ": " + XmlHttpRequest.statusText + ": " + JSON.parse(XmlHttpRequest.responseText).error.message.value);
}
});
But before you copy the code to your form, you have to download the jQuery lib from here
Then upload it as a Web resource, add this web resource to the Form load libs.
Here is the complete code to be put in the form load event handler:
var context = GetGlobalContext();
// retireve the invoice record id (Opened Form)
var invoiceId = context.getQueryStringParameters().id;
var customerId;
//Retrieve the server url, which differs on-premise from on-line and
//shouldn't be hard-coded.
// this will return something like http://yourHostName/yourOrg
var serverUrl = context.getServerUrl();
//The XRM OData end-point
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
var odataUri = serverUrl + ODATA_ENDPOINT;
function SetDefaultCountryCode(countryFieldId, odataUri) {
odataUri = odataUri + '/ContactSet?$select=ContactId,FullName&$filter=FullName eq \'Ahmed Shawki\'';
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: odataUri,
beforeSend: function (XMLHttpRequest) {
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data) {
if (data.d && data.d.results) {
//var _canadaId = "{FC167B4D-1C3B-E111-8904-F2EA3FE25706}"; no longer be used
var _canadaId = data.d.results[0].ContactId;
var countryControl = Xrm.Page.getAttribute(countryFieldId);
// only attempt the code if the control exists on the form
if (countryControl != null) {
var currentCountry = countryControl.getValue();
// if country is not specified, then set it to the default one (Canada)
if (currentCountry == null) {
var defaultCountry = new Object();
defaultCountry.entityType = "cga_country";
defaultCountry.id = _canadaId;
defaultCountry.name = "Canada";
var countryLookupValue = new Array();
countryLookupValue[0] = defaultCountry;
countryControl.setValue(countryLookupValue);
}
}
}
},
error: function (XmlHttpRequest) {
alert("Error : " + XmlHttpRequest.status + ": " + XmlHttpRequest.statusText + ": " + JSON.parse(XmlHttpRequest.responseText).error.message.value);
}
});
}
One more thing, don't forget to check "Pass execution context as first parameter" box on the form properties.
EDIT: Beside adding the jQuery library into the form load event handler, add the Json2 lib as a web resource.
For more information about the REST Endpoint.
It is indeed possible to export and import records along with their guids, just not natively. You'd have to build an app that would export the data for you, then create identical records through the CRM API in the target environment. You just have to clear out fields that aren't valid for create (createdon, statecode, etc.) and just specify the same Guid. CRM will then create the record with that Guid.
The old 4.0 Configuration Data Tool does this. I can't recall if it works against a 2011 org, but it could be a starting point.

Resources