I am trying to get the total count of api keys in my API gateway via SDK.
However I am unsure on the proper implementation of the parameters that the GetApiKeysRequest takes in. My main objective is to get the count of all API keys that are already existing for my account.
The code I have so far looks like this :
class Program
{
public static void Main(string[] args)
{
var awsUserAccessKey = "xxxxx";
var awsUserSecretKey = "yyyyyyyyyyy";
var regionEndpoint = "us-west-2";
var keysInRepository = new GetApiKeysRequest
{
CustomerId = "",
IncludeValues = true||false,
Limit=0,
NameQuery = "",
Position = ""
};
var client = new AmazonAPIGatewayClient(awsUserAccessKey, awsUserSecretKey, regionEndpoint);
var apiKeys =client.GetApiKeys(keysInRepository);
Console.Read();
}
}
This code throws an error saying that The security token included in the request is invalid (Amazon.APIGateway exception).I am unsure on how to set the parameters for this request.
Because the AmazonAPIGatewayClient you are using as described here takes three string arguments and the last one is awsSessionToken i think you are confusing with this one which takes as third argument RegionEndpoint
Do something like that instead :
var client = new AmazonAPIGatewayClient(awsUserAccessKey, awsUserSecretKey, RegionEndpoint.USWest2);
For someone looking for a solution to similar problems, this worked :
var awsUserAccessKey = "xxxx";
var awsUserSecretKey = "yyyyy";
var regionEndpointName = "us-west-2";
var regionEndpoint = RegionEndpoint.GetBySystemName(regionEndpointName);
var keysInRepository = new GetApiKeysRequest
{
Limit = 500
};
//define the key and its fields
var client = new AmazonAPIGatewayClient(awsUserAccessKey, awsUserSecretKey, regionEndpoint);
var apiKeys = client.GetApiKeys(keysInRepository);
Console.WriteLine("Current number of api keys:{0}", apiKeys.Items.Count);
Using this query api how to get the nearby places in to our mapcontrol in windows phone 8.1. When I placed the code from the above link it shows the 404 error (i.e resource not found).
I got bing maps key. But how to place the access id. How the data source are named. Please help me.
string BingMapsKey = "MY_BING_MAPS_KEY";
string DataSourceID = "20181f26d9e94c81acdf9496133d4f23";
string dataSourceName = "petrolbunk";
string dataEntityName = "petrolbunk";
string accessId = DataSourceID;
string bingMapsKey = BingMapsKey;
double SearchLatitude = 47.63674;
double SearchLongitude = -122.30413;
double Radius = 3;
string requestUrl1 = string.Format("http://spatial.virtualearth.net/REST/v1/data/{0}/{1}/{2}" + "?spatialFilter=nearby({3},{4},{5})&key={6}", accessId, dataSourceName,
dataEntityName, SearchLatitude, SearchLongitude, Radius, bingMapsKey);
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync(requestUrl1);
if (response.IsSuccessStatusCode)
{
var data = response.Content.ReadAsStringAsync();
Is the above url layout is correct. How to display them in our map control.
The following code listing uses NAVTEQEUDataSource for searching nearby. You can take it for example
internal class NAVTEQEUDataSource : INAVTEQEUDataSource
{
public async Task<IList<Geopoint>> SearchNearBy(double latitude, double longitude, double radius, int entityTypeId, int maxResult, string bingMapKey)
{
const string spatialBaseUrl = "http://spatial.virtualearth.net/REST/v1/data/";
string url =
"c2ae584bbccc4916a0acf75d1e6947b4/NavteqEU/NavteqPOIs?spatialFilter=nearby({0},{1},{2})&$filter=EntityTypeID%20eq%20'{3}'&$select=EntityID,DisplayName,Latitude,Longitude,__Distance&$top={4}&key={5}";
HttpClient httpClient = new HttpClient { BaseAddress = new Uri(spatialBaseUrl) };
url = string.Format(url, latitude, longitude, radius, entityTypeId, maxResult, bingMapKey);
string response = await httpClient.GetStringAsync(url);
XmlUtil xmlUtil = new XmlUtil(response);
IList<XElement> properties = xmlUtil.GetElements("entry").ToList();
IList<Geopoint> result = new List<Geopoint>();
foreach (var property in properties)
{
BasicGeoposition basicGeoposition = new BasicGeoposition();
double temp;
if (double.TryParse(xmlUtil.GetRelativeElement(property, "content.properties.Latitude").Value, out temp))
basicGeoposition.Latitude = temp;
if (double.TryParse(xmlUtil.GetRelativeElement(property, "content.properties.Longitude").Value, out temp))
basicGeoposition.Longitude = temp;
result.Add(new Geopoint(basicGeoposition));
}
return result;
}
}
How it works you can read more at this post. The code listing uses some other util classes to handle response so I think you should read that post directly.
Taking a look into your account it doesn't look like there is any data source that can be accessed at
http://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/petrolbunk/petrolbunk
Have you created a data source? If you have, in the Bing Maps portal, go to Data Sources -> View Data source information. Find the data source you want to access and copy the complete URL (you don't need to break it up into pieces i.e. accessId, data source name, entity name).
If you want to access one of the point of interest data sources in Bing Maps, then take a look at the NAVTEQNA data source: https://msdn.microsoft.com/en-us/library/hh478192.aspx
I am still learning to work with XML and C#.
I have looked many places on how to get this to work properly but I am unable to solve this as of yet and was wondering if anyone can see where I am going wrong?
I am trying to get a list containing the node values for distance and duration for two seperate occasions. First should be just one pair which is the total dist/duration pair: /DirectionsResponse/route/leg/distance/value, then I'm trying to get a second list which will contain the steps version: /DirectionsResponse/route/leg/steps/distance/value. If I can get the second one working I can figure out the first.
Many Thanks
Jaie
public class MyNode
{
public string Distance { get; set; }
public string Duration { get; set; }
}
public class Program
{
static void Main(string[] args)
{
//The full URI
//http://maps.googleapis.com/maps/api/directions/xml?`enter code here`origin=Sydney+australia&destination=Melbourne+Australia&sensor=false
//refer: https://developers.google.com/maps/documentation/webservices/
string originAddress = "Canberra+Australia";
string destinationAddress = "sydney+Australia";
StringBuilder url = new StringBuilder();
//http://maps.googleapis.com/maps/api/directions/xml?
//different request format to distance API
url.Append("http://maps.googleapis.com/maps/api/directions/xml?");
url.Append(string.Format("origin={0}&", originAddress));
url.Append(string.Format("destination={0}", destinationAddress));
url.Append("&sensor=false&departure_time=1343605500&mode=driving");
WebRequest request = HttpWebRequest.Create(url.ToString());
var response = request.GetResponse();
var stream = response.GetResponseStream();
XDocument xdoc = XDocument.Load(stream);
List<MyNode> routes =
(from route in xdoc.Descendants("steps")
select new MyNode
{
Duration = route.Element("duration").Value,
Distance = route.Element("distance").Value,
}).ToList<MyNode>();
foreach (MyNode route in routes)
{
Console.WriteLine("Duration = {0}", route.Duration);
Console.WriteLine("Distance = {0}", route.Distance);
}
stream.Dispose();
}
}
I reckon you are pretty close to where you want to be, just a little debugging would get you over the line.
Here is a small snippet of what I threw together in LinqPad which I use to scratch together things before I commit them to code.
var origin = "Canberra+Australia";
var dest = "sydney+Australia";
var baseUrl = "http://maps.googleapis.com/maps/api/directions/xml?origin={0}&destination={1}&sensor=false&departure_time=1343605500&mode=driving";
var req = string.Format(baseUrl, origin, dest);
var resp = new System.Net.WebClient().DownloadString(req);
var doc = XDocument.Parse(resp);
var total = doc.Root.Element("route").Element("leg").Element("distance").Element("value").Value;
total.Dump();
var steps = (from row in doc.Root.Element("route").Element("leg").Elements("step")
select new
{
Duration = row.Element("duration").Element("value").Value,
Distance = row.Element("distance").Element("value").Value
}).ToList();
steps.Dump();
The Dump method spits the result out to the LinqPad results. I had a list of 16 items in my steps results, and the total distance was a value of 286372.
Hope this helps.
I derived/adapted the following code from Adam Freeman's book "Metro Revealed: Building Windows 8 apps with XAML and C#" to get the Address when the Coordinates are known:
public static async Task<string> GetAddressForCoordinates(double latitude, double longitude)
{
HttpClient httpClient = new HttpClient {BaseAddress = new Uri("http://nominatim.openstreetmap.org")};
HttpResponseMessage httpResult = await httpClient.GetAsync(
String.Format("reverse?format=json&lat={0}&lon={1}", latitude, longitude));
JsonObject jsonObject = JsonObject.Parse(await httpResult.Content.ReadAsStringAsync());
return jsonObject.GetNamedObject("address").GetNamedString("road");
}
How can I get the opposite (the Coordinates if the Address is known)?
UPDATE
I'm adding a bounty to this; what I've got already (shown above) is the reverse geocoding (getting the address for the coordinates); what I need is geocoding (getting the coordinates for the address).
Based on my reverse geocoding code above, I'm guessing it might be something like this:
public static async Task<string> GetCoordinatesForAddress(string address)
{
HttpClient httpClient = new HttpClient {BaseAddress = new Uri("http://nominatim.openstreetmap.org")};
HttpResponseMessage httpResult = await httpClient.GetAsync(
String.Format("format=json&address={0}", address));
JsonObject jsonObject = JsonObject.Parse(await httpResult.Content.ReadAsStringAsync());
return jsonObject.GetNamedObject("address").GetNamedString("lat"); // <-- what about "lon"?
}
...but I don't know how to combine the two coordinate (longitude and latitude) values (assuming this is correct, or close to being correct). Can anybody verify this, clean it up, or provide a better example (either using nominatim or otherwise)?
UPDATE 2
To answer Peter Ritchie's question/comment below:
In the original (reverse geocoding code), I've got:
return jsonObject.GetNamedObject("address").GetNamedString("road");
It simply returns the road; so something like "157 Riverside Avenue" I assume.
But for geocoding (needing two values, a longitude and a latitude), I've got this pseudocode:
return jsonObject.GetNamedObject("address").GetNamedString("lat"); // <-- what about "lon"?
So I don't know if I need to change the return value from Task<string> to Task<List and call (verbose pseudocode) [Note: I'm having a hard time escaping the angle brackets for Task with a List of string]:
var latitude jsonObject.GetNamedObject("address").GetNamedString("lat");
var longitude jsonObject.GetNamedObject("address").GetNamedString("lat");
List<string> listCoordinates = new List<string>();
listCoordinates.Add(latitude);
listCoordinates.Add(longitude);
return listCoordinates;
...or like so:
string latitude jsonObject.GetNamedObject("address").GetNamedString("lat");
string longtude jsonObject.GetNamedObject("address").GetNamedString("long");
return string.Format("{0};{1}", latitude, longitude);
...or ???
UPDATE 3
In response to the proffered Json code for geocoding:
Based on the original reverse geocode code, shouldn't the call be more like this:
HttpClient httpClient = new HttpClient { BaseAddress = new Uri("http://nominatim.openstreetmap.org/") };
var httpResult = await httpClient.GetAsync(
String.Format("search?format=json&addressdetails={0}", address);
...but at any rate:
The JArray type is not recognized, though JsonArray is.
The JValue type is not recognized, though JsonValue is.
The JsonConverter type is not recognized; perhaps part of Json.Net?
The closest I can come to getting the proferred code to compile is:
var result = await httpResult.Content.ReadAsStringAsync();
var r = (JsonArray)JsonConverter.DeserializeObject(result);//<-- JsonConvert[er] not recognized; part of Json.NET?
var latString = ((JsonValue)r[0]["lat"]).ValueType as string;
var longString = ((JsonValue)r[0]["lon"]).ValueType as string;
...but even with this (close but no Bob Seger), JsonConvert as well as JsonConverter are not recognized.
UPDATE 4
After slogging more concertedly through the documentation at http://wiki.openstreetmap.org/wiki/Nominatim#Search, I think my original (reverse geocode) method might be better as:
public static async Task`<string`> GetAddressForCoordinates(double latitude, double longitude)
{
HttpClient httpClient = new HttpClient {BaseAddress = new Uri("http://nominatim.openstreetmap.org/")};
HttpResponseMessage httpResult = await httpClient.GetAsync(
String.Format("reverse?format=json&lat={0}&lon={1}", latitude, longitude));
JsonObject jsonObject = JsonObject.Parse(await httpResult.Content.ReadAsStringAsync());
string house = jsonObject.GetNamedObject("addressparts").GetNamedString("house");
string road = jsonObject.GetNamedObject("addressparts").GetNamedString("road");
string city = jsonObject.GetNamedObject("addressparts").GetNamedString("city");
string state = jsonObject.GetNamedObject("addressparts").GetNamedString("state");
string postcode = jsonObject.GetNamedObject("addressparts").GetNamedString("postcode");
string country = jsonObject.GetNamedObject("addressparts").GetNamedString("country");
return string.Format("{0} {1}, {2}, {3} {4} ({5})", house, road, city, state, postcode, country);
}
This would return, for the corresponding coordinate args passed in, something like: "157 Riverside Avenue, Champaign, IL 55555 (USA)"
What I find odd about the documentation is there is no "state" element among the address parts; if that is really true, and not just a documentation oversight, my code above would fail on the call to GetNamedString("state").
I'm still not sure what the right syntax, etc., should be for the opposite (geocode) method, getting coordinates back after passing in an address.
UPDATE 5
Okay, I downloaded Json.NET and got it compiling. I haven't tested yet, but I've marked Peter Ritchie's as THE (50-point) answer.
This is the code I'm using:
public static async Task<string> GetCoordinatesForAddress(string address)
{
HttpClient httpClient = new HttpClient { BaseAddress = new Uri("http://nominatim.openstreetmap.org/") };
HttpResponseMessage httpResult = await httpClient.GetAsync(
String.Format("search?q={0}&format=json&addressdetails=1", Pluggify(address))); // In my Pluggify() method, I replace spaces with + and then lowercase it all
var result = await httpResult.Content.ReadAsStringAsync();
var r = (JArray)JsonConvert.DeserializeObject(result);
var latString = ((JValue)r[0]["lat"]).Value as string;
var longString = ((JValue)r[0]["lon"]).Value as string;
return string.Format("{0};{1}", latString, longString);
}
Also:
A funny thing happened on the way back to this forum: while installing Json.NET via NuGet, I also saw ".NET's fastest JSON Serializer by ServiceStack" which claims to be 3X faster than Json.NET. FIWW, it has been updated more recently than Json.NET. Thoughts/reaction?
UPDATE 6
I have this code to implement this (app id and code have been changed to protect the semi-innocent
(me)):
// If address has not been explicitly entered, try to suss it out:
address = textBoxAddress1.Text.Trim();
lat = textBoxLatitude1.Text.Trim();
lng = textBoxLongitude1.Text.Trim();
if (string.IsNullOrWhiteSpace(address))
{
address = await SOs_Classes.SOs_Utils.GetAddressForCoordinates(lat, lng);
}
. . .
public async static Task<string> GetAddressForCoordinates(string latitude, string longitude)
{
string currentgeoLoc = string.Format("{0},{1}", latitude, longitude);
string queryString = string.Empty;
string nokiaAppID = "j;dsfj;fasdkdf";
object nokiaAppCode = "-14-14-1-7-47-178-78-4";
var hereNetUrl = string.Format(
"http://demo.places.nlp.nokia.com/places/v1/discover/search?at={0}&q={1}&app_id={2}
&app_code={3}&accept=application/json",
currentgeoLoc, queryString, nokiaAppID, nokiaAppCode);
// get data from HERE.net REST API
var httpClient = new HttpClient();
var hereNetResponse = await httpClient.GetStringAsync(hereNetUrl);
// deseralize JSON from Here.net
using (var tr = new StringReader(hereNetResponse))
using (var jr = new JsonTextReader(tr))
{
var rootObjectResponse = new JsonSerializer
().Deserialize<JsonDOTNetHelperClasses.RootObject>(jr);
var firstplace = rootObjectResponse.results.items.First();
return HtmlUtilities.ConvertToText(firstplace.vicinity);
// NOTE: There is also a title (such as "Donut Shop", "Fire stations", etc.?) and type (such as "residence" or "business", etc.?)
}
}
...but on this line in GetAddressForCoordinates():
var firstplace = rootObjectResponse.results.items.First();
...I get this err msg: "*System.InvalidOperationException was unhandled by user code
HResult=-2146233079
Message=Sequence contains no elements
Source=System.Core
StackTrace:
at System.Linq.Enumerable.First[TSource](IEnumerable`1 source)
at SpaceOverlays.SOs_Classes.SOs_Utils.d__12.MoveNext() in c:...*"
The value of hereNetResponse is:
{"results":{"items":[]},"search":{"context":{"location":{"position":[38.804967,-90.113183],"address":
{"postalCode":"62048","city":"Hartford","stateCode":"IL","county":"Madison","countryCode":"USA","country":"
USA","text":"Hartford IL 62048
USA"}},"type":"urn:nlp-types:place","href":"http://demo.places.nlp.nokia.com/places/v1/places/loc-
dmVyc2lvbj0xO3RpdGxlPUhhcnRmb3JkO2xhdD0zOC44MDQ5Njc7bG9uPS05MC4xMTMxODM7Y2l0eT1IY
XJ0Zm9yZDtwb3N0YWxDb2RlPTYyMDQ4O2NvdW50cnk9VVNBO3N0YXRlQ29kZT1JTDtjb3VudHk9TWFka
XNvbjtjYXRlZ29yeUlkPWNpdHktdG93bi12aWxsYWdl;context=Zmxvdy1pZD02YmUzZDM4Yi0wNGVhLTUyM
jgtOWZmNy1kNWNkZGM0ODI5OThfMTM1NzQyMDI1NTg1M18wXzE2MA?
app_id=F6zpNc3TjnkiCLwl_Xmh&app_code=QoAM_5BaVDZvkE2jRvc0mw"}}}
...so it would appear that there is valid info inside there, such as should return "Hartford, IL"
And at any rate, a blank return value shouldn't throw an exception, I would think...
What you're asking about is simply "geocoding". If you want to use Nominatim specifically, they call this "Search". This is, to a certain extent, address validation; but part of the "validation" is including coordinates (bounding box, lat/long, etc.; depending on what is searched for and what the type of result). There's lots of details about the results, too much to simply post here; but this detail can be found here: http://wiki.openstreetmap.org/wiki/Nominatim#Search (including examles).
You'll have to parse the results (XML, JSON, or HTML) to get the fields you're interested it.
Update 1:
As to what to do with the actual values: it depends. If you want to view the coordinates in a form, you can simply put the lat and long strings into individual controls. If you want to put it in a single control, could use string.Format("{0}, {1}", latString, longString). If you want to use the coords with various methods/types for a Windows Store app, you might need to use the Microsoft.Maps.MapControl.Location class. For example:
Double latNumber;
Double longNumber;
if(false == Double.TryParse(latString, out latNumber)) throw new InvalidOperationException();
if(false == Double.TryParse(longString, out longNumber)) throw new InvalidOperationException();
var location = new Location(latNumber, longNumber);
The above assumes you've extracted the lat and long from the response and put them in latString, longString respectively.
Some interfaces may require lat/long as separate double values, in which case just use latNumber and longNumber above.
Over and above that, it really depends specifically on the interfaces you want to use. But, the above should give you enough to use most interfaces.
Update 2:
If the question isn't "how to get coordinates" but "how to parse json objects" then I'd recommend using JSon.Net to get at the lat/long strings in the json result. For example:
var httpClient = new HttpClient();
var httpResult = await httpClient.GetAsync(
"http://nominatim.openstreetmap.org/search?q=135+pilkington+avenue,+birmingham&format=json&polygon=1&addressdetails=1");
var result = await httpResult.Content.ReadAsStringAsync();
var r = (JArray) JsonConvert.DeserializeObject(result);
var latString = ((JValue) r[0]["lat"]).Value as string;
var longString = ((JValue)r[0]["lon"]).Value as string;
...see above w.r.t. what to do with latString and longString
If your looking for google maps geocoding, you can find it here:
https://developers.google.com/maps/documentation/geocoding/
and an example use is:
http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false
convert to Json, and take the Geometry object.
in regards to how to, basically, return two values from a function, in C# you have 4 options:
convert both objects into a single object of the same type (in case of strings, you just separate them by a delimiter, like you did) and then parse both out afterwards.
return a list - in this case a Task (or array).
create a new class/object that contains both (in this case you can call it Geometry for instance).
return one or both of the objects by requiring them to be passed as a reference to the function. In an async function, this is bound to be very tricky, but depending on who calls the function and who processes the result, it might be possible.
Microsoft Mappoint also contaisn an API you could make use of. It is able to return geocoordinates.
I’m using Amazon Product Advertising API to get data about books based on given ISBN number. It works fine I’m getting most of the information but for some of the books I have a problem with Editorial Reviews. It looks like the information is available on the Amazon web site but I’m not getting it back with my query. Does anyone know why? Below is sample of my code. The sample ISBN may be 9780752809069.
Thanks for any sugestions.
AWSECommerceServicePortTypeClient amazonClient;
amazonClient = new AWSECommerceServicePortTypeClient(
new BasicHttpBinding(BasicHttpSecurityMode.Transport), new EndpointAddress("https://ecs.amazonaws.co.uk/onca/soap?Service=AWSECommerceService")); //Amazon UK working
amazonClient.ChannelFactory.Endpoint.Behaviors.Add(new AmazonSigningEndpointBehavior("AAAAAAAAAAAAAAAAA", "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
ItemLookup itemLookup = new ItemLookup();
ItemLookupRequest request_isbn = new ItemLookupRequest();
request_isbn.ResponseGroup = new string[] {"EditorialReview", "Large" };
request_isbn.SearchIndex = "Books";
request_isbn.ItemId = new string[] { "9780752809069" };
request_isbn.IncludeReviewsSummary = "True";
request_isbn.IdType = ItemLookupRequestIdType.ISBN;
request_isbn.IdTypeSpecified = true;
itemLookup.Request = new ItemLookupRequest[] { request_isbn };
itemLookup.AssociateTag = "my astag";
ItemLookupResponse response_isbn = new ItemLookupResponse();
response_isbn = amazonClient.ItemLookup(itemLookup);
string _Description = "";
foreach (var revitem in response_isbn.Items[0].Item)
{
if (revitem.EditorialReviews != null) _Description = revitem.EditorialReviews.Last().Content.ToString(); //Sometimes is null even if there is Product Description avaliable on the Amazon Web
}
ItemLookup does not return some editorial reviews. ItemLookup only returns the editorial reviews written by Amazon.com Editorial reviews recorded by another website cannot be included in the reviews returned by ItemLookup.
https://aws.amazon.com/releasenotes/Product-Advertising-API/2666