Bing maps to get hospitals - xaml

I am trying to fetch all the hospitals for specific cities in India using BING Map APIs for Windows 8 Metro application. However i am not able to fetch the details. Following are the two approaches that are tried
Using NearbyVenueCollection class
NearbyVenueOptions options = new NearbyVenueOptions(loc, 10000);
NearbyVenueCollection nearbyVenues = null;
try
{
nearbyVenues = await MyMap.VenueManager.GetNearbyVenuesAsync(options); ;
}
catch (Exception)
{
}
if (nearbyVenues != null && nearbyVenues.Count > 0)
{
foreach (var nearbyVenue in nearbyVenues)
{
if (nearbyVenue.Metadata.VenueType == VenueType.Hospital.ToString())
{
string name = nearbyVenue.Metadata.Name;
}
}
}
This is not providing the required details.
Using Bing Spatial Data Services
Following is the code snippet
////Create the Bing Spatial Data Services request to get nearby POI
string findNearbyPOIRequest = "http://spatial.virtualearth.net/REST/v1/data/ f22876ec257b474b82fe2ffcb8393150/ NavteqNA/NavteqPOIs? spatialfilter=nearby("
+ loc.Latitude + "," + loc.Longitude + "," + 1000 + ")"
+ "&$filter=EntityTypeID%20EQ%20'" + "8060" + "'& $select=EntityID,DisplayName,__Distance,Latitude,Longitude,AddressLine, Locality,AdminDistrict,PostalCode,Phone&$top=20"
+ "&key=" + BingCredentials;
Uri uri = new Uri(findNearbyPOIRequest);
WebRequest request = WebRequest.Create(uri);
// GetResponseAsync() returns immediately after the header is ready
WebResponse response = await request.GetResponseAsync();
Stream inputStream = response.GetResponseStream();
XDocument doc = XDocument.Load(inputStream);
XNamespace m ="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata";
XNamespace d = "http://schemas.microsoft.com/ado/2007/08/dataservices";
MapLayer pushpinLayer = new MapLayer();
pushpinLayer.Name = "Push Pin Layer";
var elements = from nodes in doc.Descendants(m + "properties")
select new
{
Name = nodes.Element(d + "DisplayName").Value,
Latitude = nodes.Element(d + "Latitude").Value,
Longitude = nodes.Element(d + "Longitude").Value,
Address = nodes.Element(d + "AddressLine").Value,
};
However i am not getting the required details for cities in India. Can someone help me figure out what need to be done in order to fetch correct details?

The Venue maps are only locations where Bing Maps has indoor floor plans. I'm not aware of any hospitals in India that are available as Venue Maps. The point of interest data in the Bing Spatial Data services is only available in North America and Europe. Your best option for finding locations in India is to use the Bing Maps SOAP Search Service.
http://msdn.microsoft.com/en-us/library/cc980849.aspx
http://msdn.microsoft.com/en-us/library/dd221354.aspx

Related

Getting (401) UnAuthorized error on some requests not all, but most

I don't think this is a code issue, but we have a list of hundreds of addresses to process. Some return data and we are able to get Long and Lat but most return (401) UnAuthorized errors. What would cause this to happen? We have tried passing Host Headers and everything else, the REST API seems to work better in our development environment but throws way more errors when deployed to our Job Server. Any help on this issue will be greatly appreciated. We would like to understand why some calls work and others don't, we pass the same apiKey each time so this is really confusing. Thanks
Here is a code snippet using c# (Work in progress):
//GET THE LATITUDE AND LONGITUDE BASED OFF THE PHYSICAL ADDRESS
String clientAddress = clientRow["home_address"].ToString() + ", " + clientRow["home_city"].ToString() + ", " + clientRow["home_state"].ToString() + ", " + clientRow["home_zip"].ToString();
Logger.Debug("CLIENT ADDRESS: {0}", clientAddress);
String geocoderUri = "https://geocode.search.hereapi.com/v1/geocode?q=" + clientAddress + "&apiKey=xxxxxxxxxxxxxxxxxxxxx"; //KEY REMOVED FOR POSTING ON STACK OVERFLOW
var syncClient = new WebClient();
var content = syncClient.DownloadString(geocoderUri);
//CREATE THE JSON SERIALIZER AND PARSE OUR RESPONSE
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(AddressData));
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(content)))
{
var addressData = (AddressData)serializer.ReadObject(ms);
if (addressData.items.Count() > 0)
{
//INSERT THE LATITUDE AND LONGITUDE IN DB
String sLat = addressData.items[0].position.lat.ToString();
String sLong = addressData.items[0].position.lng.ToString();
Logger.Debug("CLIENT GEOLOCATION - Longitude: {0} Latitude: {1}", sLong, sLat);
insertLatLong(sLat, sLong, clientRow["clientID"].ToString(), 1);
}
}
Would you please try to use RestSharp lib for rest api?
Please see below sample code.
var client = new RestClient("https://geocode.search.hereapi.com/v1/geocode?q="+ clientAddress);
client.Timeout = -1;
var request = new RestRequest(Method.GET);
request.AddHeader("Authorization", "Bearer YOUR TOKEN");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);

Crunchbase Data API v3.1 to Google Sheets

I'm trying to pull data from the Crunchbase Open Data Map to a Google Spreadsheet. I'm following Ben Collins's script but it no longer works since the upgrade from v3 to v3.1. Anyone had any luck modifying the script for success?
var USER_KEY = 'insert your API key in here';
// function to retrive organizations data
function getCrunchbaseOrgs() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Organizations');
var query = sheet.getRange(3,2).getValue();
// URL and params for the Crunchbase API
var url = 'https://api.crunchbase.com/v/3/odm-organizations?query=' + encodeURI(query) + '&user_key=' + USER_KEY;
var json = getCrunchbaseData(url,query);
if (json[0] === "Error:") {
// deal with error with fetch operation
sheet.getRange(5,1,sheet.getLastRow(),2).clearContent();
sheet.getRange(6,1,1,2).setValues([json]);
}
else {
if (json[0] !== 200) {
// deal with error from api
sheet.getRange(5,1,sheet.getLastRow(),2).clearContent();
sheet.getRange(6,1,1,2).setValues([["Error, server returned code:",json[0]]]);
}
else {
// correct data comes back, filter down to match the name of the entity
var data = json[1].data.items.filter(function(item) {
return item.properties.name == query;
})[0].properties;
// parse into array for Google Sheet
var outputData = [
["Name",data.name],
["Homepage",data.homepage_url],
["Type",data.primary_role],
["Short description",data.short_description],
["Country",data.country_code],
["Region",data.region_name],
["City name",data.city_name],
["Blog url",data.blog_url],
["Facebook",data.facebook_url],
["Linkedin",data.linkedin_url],
["Twitter",data.twitter_url],
["Crunchbase URL","https://www.crunchbase.com/" + data.web_path]
];
// clear any old data
sheet.getRange(5,1,sheet.getLastRow(),2).clearContent();
// insert new data
sheet.getRange(6,1,12,2).setValues(outputData);
// add image with formula and format that row
sheet.getRange(5,2).setFormula('=image("' + data.profile_image_url + '",4,50,50)').setHorizontalAlignment("center");
sheet.setRowHeight(5,60);
}
}
}
This code no longer pulls data as expected.
I couldn't confirm about the error messages when you ran the script. So I would like to show about the clear difference point. It seems that the endpoint was changed from https://api.crunchbase.com/v/3/ to https://api.crunchbase.com/v3.1/. So how about this modification?
From :
var url = 'https://api.crunchbase.com/v/3/odm-organizations?query=' + encodeURI(query) + '&user_key=' + USER_KEY;
To :
var url = 'https://api.crunchbase.com/v3.1/odm-organizations?query=' + encodeURI(query) + '&user_key=' + USER_KEY;
Note :
From your script, I couldn't also find query. So if the script doesn't work even when you modified the endpoint, please confirm about it. You can see the detail of API v3 Compared to API v3.1 is here.
References :
API v3 Compared to API v3.1
Using the API
If this was not useful for you, I'm sorry.

Google API for getting maximum number of licenses in a Google Apps domain

I have a Google Apps Script function used for setting up accounts for new employees in our Google Apps domain.
The first thing it does is makes calls to the Google Admin Settings API and retrieves the currentNumberOfUsers and maximumNumberOfUsers, so it can see if there are available seats (otherwise a subsequent step where the user is created using the Admin SDK Directory API would fail).
It's been working fine until recently when our domain had to migrate from Postini to Google Vault for email archiving.
Before the migration, when creating a Google Apps user using the Admin SDK Directory API, it would increment the currentNumberOfUsers by 1 and the new user account user would automatically have access to all Google Apps services.
Now after the migration, when creating a Google Apps user, they aren't automatically assigned a "license," so I modified my script to use the Enterprise License Manager API and now it assigns a "Google-Apps-For-Business" license. That works fine.
However, the currentNumberOfUsers is now different from the number of assigned licenses, and "Google-Apps-For-Business" is only one of several different types of licenses available.
I can get the current number of assigned "Google-Apps-For-Business" licenses by running this:
var currentXml = AdminLicenseManager.LicenseAssignments.listForProductAndSku('Google-Apps', 'Google-Apps-For-Business', 'domain.com', {maxResults: 1000});
var current = currentXml.items.toString().match(/\/sku\/Google-Apps-For-Business\/user\//g).length;
But the number that produces is different from currentNumberOfUsers.
All I really need to do now is get the maximum number of owned "Google-Apps-For-Business" licenses so the new employee setup script can determine whether there are any available.
I checked the API Reference documentation for the following APIs but...
Enterprise License Manager API → Doesn't have a method for getting the maximum or available number of licenses.
Google Admin Settings API → Doesn't deal with licenses, only "users."
Admin SDK Directory API User resource → Doesn't deal with licenses.
Google Apps Reseller API → This API seems to have what I need, but it's only for Reseller accounts.
I know I can program my new employee setup script to just have a try/catch seeing if it would be able to create the user and assign the license, and end the script execution gracefully if it can't, but that doesn't seem efficient.
Also, part of the old script was that if there were less than X seats available, it would email me a heads-up to order more. I can program a loop that attempts to repeatedly create dummy users and assign them licenses and count the number of times it can do that before it fails, then delete all the dummy users, but, once again, that's not efficient at all.
Any ideas?
Update 3/11/2020: Since the Admin Settings API had shut down a few years ago I've been using the Enterprise License Manager API to get the current number of used licenses, like this:
function getCurrentNumberOfUsedGoogleLicenses(skuId) {
var success = false, error = null, count = 0;
var adminEmail = 'admin#domain.com';
var gSuiteDomain = adminEmail.split('#')[1];
// for more information on the domain-wide delegation:
// https://developers.google.com/identity/protocols/OAuth2ServiceAccount#delegatingauthority
// the getDomainWideDelegationService() function uses this:
// https://github.com/gsuitedevs/apps-script-oauth2
var service = getDomainWideDelegationService('EnterpriseLicenseManager: ', 'https://www.googleapis.com/auth/apps.licensing', adminEmail);
if (skuId == 'Google-Apps-Unlimited') var productId = 'Google-Apps';
else return { success: success, error: "Unsupported skuId", count: count };
var requestBody = {};
requestBody.headers = {'Authorization': 'Bearer ' + service.getAccessToken()};
requestBody.method = "GET";
requestBody.muteHttpExceptions = false;
var data, pageToken, pageTokenString;
var maxAttempts = 5;
var currentAttempts = 0;
var pauseBetweenAttemptsSeconds = 3;
loopThroughPages:
do {
if (typeof pageToken === 'undefined') pageTokenString = "";
else pageTokenString = "&pageToken=" + encodeURIComponent(pageToken);
var url = 'https://www.googleapis.com/apps/licensing/v1/product/' + productId + '/sku/' + skuId + '/users?maxResults=1000&customerId=' + gSuiteDomain + pageTokenString;
try {
currentAttempts++;
var response = UrlFetchApp.fetch(url, requestBody);
var result = JSON.parse(response.getContentText());
if (result.items) {
var licenseAssignments = result.items;
var licenseAssignmentsString = '';
for (var i = 0; i < licenseAssignments.length; i++) {
licenseAssignmentsString += JSON.stringify(licenseAssignments[i]);
}
if (skuId == 'Google-Apps-Unlimited') count += licenseAssignmentsString.match(/\/sku\/Google-Apps-Unlimited\/user\//g).length;
currentAttempts = 0; // reset currentAttempts before the next page
}
} catch(e) {
error = "Error: " + e.message;
if (currentAttempts >= maxAttempts) {
error = 'Exceeded ' + maxAttempts + ' attempts to get license count: ' + error;
break loopThroughPages;
}
} // end of try catch
if (result) pageToken = result.nextPageToken;
} while (pageToken);
if (!error) success = true;
return { success: success, error: error, count: count };
}
However, there still does not appear to be a way to get the maximum number available to the domain using this API.
Use CustomerUsageReports.
jay0lee is kind enough to provide the GAM source code in Python. I crudely modified the doGetCustomerInfo() function into Apps Script thusly:
function getNumberOfLicenses() {
var tryDate = new Date();
var dateString = tryDate.getFullYear().toString() + "-" + (tryDate.getMonth() + 1).toString() + "-" + tryDate.getDate().toString();
while (true) {
try {
var response = AdminReports.CustomerUsageReports.get(dateString,{parameters : "accounts:gsuite_basic_total_licenses,accounts:gsuite_basic_used_licenses"});
break;
} catch(e) {
//Logger.log(e.warnings.toString());
tryDate.setDate(tryDate.getDate()-1);
dateString = tryDate.getFullYear().toString() + "-" + (tryDate.getMonth() + 1).toString() + "-" + tryDate.getDate().toString();
continue;
}
};
var availLicenseCount = response.usageReports[0].parameters[0].intValue;
var usedLicenseCount = response.usageReports[0].parameters[1].intValue;
Logger.log("Available licenses:" + availLicenseCount.toString());
Logger.log("Used licenses:" + usedLicenseCount.toString());
return availLicenseCount;
}
I would recommend exploring GAM which is a tool that gives command line access to the administration functions of your domain.

NetSuite API - How to send tracking number back to Invoice or Sales Order?

I'm integrating a shipping solution with NetSuite via the SOAP API. I can retrieve the shipAddress via the searchRecord call. Now I need to send the tracking number, service used, and cost back into NetSuite. Hoping someone can point me in the right direction as searching hasn't turned up any answers for me. An example XML would be great.
Im pretty much pasting what I was had an external developer attempt to implement as the response but I don't understand how to setup the envelope to receive it within NS on a record...I think this is what is handling the update post to Field:
'
var a = new Array();
a['Content-Type'] = 'text/xml; charset=utf-8';
a['POST'] = '/FedexNSService/Service1.asmx HTTP/1.1';
a['Content-Length'] = data.length;
a['SOAPAction'] = 'https://wsbeta.fedex.com:443/web-services/ship/ReturnFedexLable';
nlapiLogExecution('DEBUG', 'Results', 'data : ' + data);
var response = nlapiRequestURL('http://sonatauat.adaaitsolutions.com/FedexNSService/Service1.asmx?op=ReturnFedexLable', data, a, null,null);
nlapiLogExecution('DEBUG', 'response', response);
var responseXML = nlapiStringToXML(response.getBody());
nlapiLogExecution('DEBUG', 'responseXML', responseXML);
var responseCode = response.getCode();
nlapiLogExecution('DEBUG', 'responseCode', responseCode);
var body = response.getBody();
nlapiLogExecution('DEBUG', 'body', body);
nlapiLogExecution('DEBUG', 'responseXML '+responseXML, 'responseCode : ' + responseCode);
nlapiLogExecution('DEBUG', 'body ', 'body : ' +body);
var imageurl ='';
if(responseXML != null)
{
var rawfeeds = nlapiSelectNodes(responseXML, "//Tracking");
var FileInternalId = nlapiSelectValue(rawfeeds[0], "FileInternalId");
var TrackingIds = nlapiSelectValue(rawfeeds[1], "TrackingIds");
nlapiLogExecution('DEBUG', 'FileInternalId '+FileInternalId, 'TrackingIds : '+TrackingIds );
if(FileInternalId)
{
var image=nlapiLoadFile(5985);
imageurl=image.getURL();
imageurl = ("https://system.netsuite.com"+imageurl);
nlapiLogExecution('DEBUG','image',imageurl);
}
}
return imageurl;
'
In order to update a sales order with the information via SOAP you need to create a sales order object, set the values and call either an update, or an upsert method:
[JAVA]
SalesOrder so = new SalesOrder();
so.setExternalId("externalID"); //This should correspond to the previous external ID for updates.
...set_other_fields_as_required...
WriteResponse wr = ns.getPort().update(so); //ns = _port if you're using the samples
[C#]
var so = new SalesOrder();
so.externalId = "externalID";
...set_other_fields_as_required...
var wr = Service.upsert(so);
PHP should be similar, but I haven't used the PHP toolkit so I can't say for certain.
This should help get you started.

How to insert rule in Google Calendar ACL from Google Apps Script

How can I add a new user to the ACL for a Google Calendar? I'm trying to send a POST HTTP request. Perhaps there is something wrong with the XML? The code below generates a server error (400). (Edit: Shows the oAuth).
//---------------------------------------------------------------
// Add a rule to the Access Control List for 'Fake Calendar 1.0'
//---------------------------------------------------------------
function addRule() {
// Get Calendar ID, script user's email, and the API Key for access to Calendar API
var calId = '12345calendar.google.com';
var userEmail = Session.getActiveUser().getEmail();
var API_KEY = 'ABC123';
var newUserEmail = 'person#example.net';
// Get authorization to access the Google Calendar API
var apiName = 'calendar';
var scope = 'https://www.googleapis.com/auth/calendar';
var fetchArgs = googleOAuth_(apiName, scope);
fetchArgs.method = 'POST';
var rawXML = "<entry xmlns='http://www.w3.org/2005/Atom' " +
"xmlns:gAcl='http://schemas.google.com/acl/2007'>" +
"<category scheme='http://schemas.google.com/g/2005#kind' " +
"term='http://schemas.google.com/acl/2007#accessRule'/>" +
"<gAcl:role value='owner'/>" +
"<gAcl:scope type='user' value='"+userEmail+"'/>" +
"</entry>";
fetchArgs.payload = rawXML;
fetchArgs.contentType = 'application/atom+xml';
// Get the requested content (the ACL for the calendar)
var base = 'https://www.googleapis.com/calendar/v3/calendars/';
var url = base + calId + '/acl?key=' + API_KEY;
var content = UrlFetchApp.fetch(url, fetchArgs).getContentText();
Logger.log(content);
}
//--------------------------------------------------------------
// Google OAuth
//--------------------------------------------------------------
function googleOAuth_(name,scope) {
var oAuthConfig = UrlFetchApp.addOAuthService(name);
oAuthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope="+scope);
oAuthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
oAuthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
oAuthConfig.setConsumerKey("anonymous");
oAuthConfig.setConsumerSecret("anonymous");
return {oAuthServiceName:name, oAuthUseToken:"always"};
}
Have you gone through the oAuth authorization process before executing this piece of code. Your app has to be explicitly authorized before it can do anything significant with the Calendar API
Srik is right. You need to use oAuth Arguments in your UrlFetchApp.
Given Reference URL shows few examples for using oAuth in Apps script to work with Google's REST APIs
https://sites.google.com/site/appsscripttutorial/urlfetch-and-oauth