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,
Related
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)
});
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}',
I've been trying to get my head around query parameters with UI Router and think I have finally figured out why I'm having such a hard time with it. I'm building a small search app that has 2 states:
$stateProvider
.state('home', {
url: '/',
.state('search', {
url: '/search',
},
The home state has its own template (view) and so does the search state. They share the same controller. Basically all home state does is provide a search box to enter your search query or choose from autocomplete.
Once you have submitted your search query it goes to the search state via
$state.go('search');
I've tried many ways to get the user's search term(s) in the url on the search page using UI Router's query parameter syntax in the url: '/search?q' combined with $stateParams in the controller set as
vm.searchTerms = $stateParams.q || '';
I had switched it to $state.params.q but that didn't fix it.
I have successfully been able to get the query parameters in the url, however, when I do, it breaks search functionality. The autocomplete and query parameters work and display, but search function stops.
However, I think I finally understand why its not working the way I'd like it to. I believe it has to do with the fact that I'm using 2 states and not one parent state with a nested child state and that the templates are not nested - so $scope doesn't inherit. I'm getting close to this working... it transitions from the home state to the search state displaying query parameters in the search state's url... its simply that search breaks, but autocomplete and query parameters are working.
What I'm trying to achieve is to have the user enter search terms from the home state and then have results display in the search state along with query parameters in the url. Is there anything I need to do with home state or search state that I'm not doing?
OR
Is there anything in my search() in my controller that could be the problem
//search()
vm.search = function() {
//$state.go('search', {q: vm.searchTerms});
$state.go('search');
console.log(vm.searchTerms);
console.log('success - search');
vm.currentPage = 1;
vm.results.documents = [];
vm.isSearching = true;
return coreService.search(vm.searchTerms, vm.currentPage)
.then(function(es_return) {
console.log('success - return');
var totalItems = es_return.hits.total;
var totalTime = es_return.took;
var numPages = Math.ceil(es_return.hits.total / vm.itemsPerPage);
vm.results.pagination = [];
for (var i = 0; i <= 10; i++) {
console.log('success - for');
vm.results.totalItems = totalItems;
vm.results.queryTime = totalTime;
vm.results.pagination = coreService.formatResults(es_return.hits.hits);
vm.results.documents = vm.results.pagination.slice(vm.currentPage, vm.itemsPerPage);
console.log('success - documents');
}
vm.noResults = true;
}),
function(error){
console.log('ERROR: ', error.message);
vm.isSearching = false;
},
vm.captureQuery();
console.log('success - captureQuery');
};
You can add a parameter to your URL in two ways, use colon:
'url': '/search/:query'
or curly braces:
'url': '/search/{query}'
Then you can use the go method of $state with parameter to transition:
$state.go('search', {'query', 'foobar'});
You can access the parameter's value from your controller by using the params member of your $state object:
console.log($state.params.query);
or directly from the $stateParams object:
console.log($stateParams.query);
Reference: https://github.com/angular-ui/ui-router/wiki/URL-Routing#url-parameters
I want to get only lists with basetemplate 106.
the code that i have now is :
url:
appweburl +
"/_api/SP.AppContextSite(#target)/web/lists/?#target='" + hostweburl + "'",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: onGetHostWebListsSuccess,
error: onGetHostWebListsFail
This code will get all the lists from the site, thats a lot of information. But want to narrow it down. For lowering data traffic.
Any help in this regard would be deeply appreciated. Thanks!
You can use the $filter query option to select which items to return.
So in your case, the filter would look something like this:
$filter=BaseTemplate eq 106
And your URL like this:
appweburl + "/_api/SP.AppContextSite(#target)/web/lists?$filter=BaseTemplate eq 106&#target='" + hostweburl + "'"
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.