I'm using ReverseGeocodeQuery class to get location names from coordinates:
ReverseGeocodeQuery query = new ReverseGeocodeQuery();
query.GeoCoordinate = new GeoCoordinate(latitude, longitude);
query.QueryCompleted += (sender, args) =>
{
var result = args.Result[0].Information.Address;
Location location = new Location(result.Street, result.City, result.State, result.Country);
};
query.QueryAsync();
The problem is that results are returned in the system language of the phone. Since I am using place names for tagging purposes, I need all of them in same language, preferably in english.
I have tried by setting the CurrentCulture to en-US:
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
But I'm still getting the results in the language configured as system language.
Is ther any way to get the results from ReverseGeocodeQuery in desired language?
The results are always using the system language. Maybe you can save the name of the place and also the lat long, or use a translation service to translate to englis
Just to complete Josue's answer. An alternative to get reverse geocode results in desided language is to use one of the public REST APIs that allow to specify it (e.g. Google or Nokia Here). While the use of them is simple and are very customizable, the downside is that it is necessary to register to the services in order to get the keys.
I have decided for using HERE's API. So, below you will find the code I have used to achieve the same result as using the code present in the question, but forcing the result to be in English:
using (HttpClient client = new HttpClient())
{
string url = String.Format("http://reverse.geocoder.cit.api.here.com/6.2/reversegeocode.json"
+ "?app_id={0}"
+ "&app_code={1}"
+ "&gen=1&prox={2},{3},100"
+ "&mode=retrieveAddresses"
+ "&language=en-US",
App.NOKIA_HERE_APP_ID, App.NOKIA_HERE_APP_CODE, latitude.ToString(CultureInfo.InvariantCulture), longitude.ToString(CultureInfo.InvariantCulture));
var response = await client.GetAsync(url);
var json = await response.Content.ReadAsStringAsync();
dynamic loc = JObject.Parse(json);
dynamic address = JObject.Parse(loc.Response.View[0].Result[0].Location.Address.ToString());
string street = address.Street;
string city = address.City;
string state = address.State;
string country = address.Country;
Location location = new Location(street, city, state, country);
}
Related
I'm making a decentralized wallet built on the Ethereum network, and I'm currently trying to convert 1 Ethereum to get the equivalent of the StableCoin for a smart contract [in this case, DAI]
I was able to find out how to know my balance of this currency, and I think that I can also transfer money from one account to another in its Coin smart contract
The problem is that when I transfer the value of [assuming 100 DAI], it tells me that I do not have any balance value from this token (this is very logical) because I did not transfer Ethereum against this currency!!
Error Message : [Smart contract error: Dai/insufficient-balance]
Here is the question:
What is the name of the Function which I can convert my Ethereum to the currency that I deal with its smart contract??
Or is it not going this way??
//Dai Stablecoin Address on Ropsten Network =>
string SmartContractAddress = "0x31F42841c2db5173425b5223809CF3A38FEde360";
var account = new Account(PrivateKey);
web3 = new Web3(account, ropsten);
web3.TransactionManager.UseLegacyAsDefault = true;
// Get Balance Of an address
var balanceOfFunctionMessage = new BalanceOfFunction()
{
Owner = account.Address,
};
var balanceHandler = web3.Eth.GetContractQueryHandler<BalanceOfFunction>();
var balance = await balanceHandler.QueryAsync<BigInteger>(SmartContractAddress, balanceOfFunctionMessage);
// Try To transfer some DAI to receiver Address
var receiverAddress = "0xC10cAA4668427F05d0D95B9409f87D0662A25f97";
var transferHandler = web3.Eth.GetContractTransactionHandler<TransferFunction>();
var transfer = new TransferFunction()
{
To = receiverAddress,
TokenAmount = 100
};
var transactionReceipt = await transferHandler.SendRequestAndWaitForReceiptAsync(SmartContractAddress, transfer);
According to my simple understanding: I think I need to know the name of the function by which I can exchange assets from Ethereum to the currency of this contract
I am developing a UWP app using the Maps control that allows a user to plan a route by adding waypoints on the map using various methods such as clicking on the UWP Map control. One of the ways I want to allow a user to add a waypoint or location is to search by actual address. I use the BING Maps REST services code below but if I don't supply the language and culture of where the app is currently being used it always returns American addresses first which are clearly no use to users not in the USA (Yes Microsoft, some of us actually live outside the USA - shock, horror!). I discovered if I supplied the language-culture string such as "en-AU" for Australia then it will search Australian addresses first, and this works really well.
public async Task<List<WayPoint>> FindAddress(string address)
{
List<WayPoint> matchingWaypoints = new List<WayPoint>();
//Create a Geocode request to submit to the BING Maps REST service.
var request = new GeocodeRequest()
{
Query = address.Trim(),
Culture = "en-AU", //HOW CAN I GET THIS FROM THE DEVICE'S CURRENT LOCATION???
IncludeIso2 = true,
IncludeNeighborhood = true,
MaxResults = 10,
BingMapsKey = MapServiceToken
};
//Process the request by using the BING Maps REST services.
var response = await ServiceManager.GetResponseAsync(request);
if (response != null &&
response.ResourceSets != null &&
response.ResourceSets.Length > 0 &&
response.ResourceSets[0].Resources != null &&
response.ResourceSets[0].Resources.Length > 0)
{
int wpNumber = 0;
foreach (BingMapsRESTToolkit.Location loc in response.ResourceSets[0].Resources)
matchingWaypoints.Add(new WayPoint(wpNumber++, loc.Address.FormattedAddress, loc.Point.Coordinates[0], loc.Point.Coordinates[1]));
}
return matchingWaypoints;
}
So what I obviously want to do is derive this string based on the device's current location (i.e: country) NOT from the device's region settings. So for example if someone is using the app the USA I want to specify en-US, if they're in New Zealand it would be en-NZ, if in France it would be "fr-FR" etc. Does anyone know how I could do this? All the stuff I've read about localisation uses the device settings NOT the current physical location so I'm still trying to work out how to do it.
If anyone can help out I'd really appreciate it :-)
There is an official sample of how to get location at https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/Geolocation
This will return the latitude and longitude. You can then use a different Bing API to get the country based on that lat/long.
This will give you a country name. With this you can lookup against a pre-generated list of codes to country names (created with CultureInfo.GetCultures() on your machine) or you could look at this for a way of doing this at runtime as GetCultures() isn't supported in UWP.
Using the Regional settings is simpler but if you want to use the actual location then this is the way to go. For devices where access to location isn't available then regional settings could be a good back up.
Another approach would be one of various public APIs which will give you information such as location based on IP address. This also isn't perfect though due to the use of proxies in different countries, etc.
Thanks for the reply Matt but I worked out how to do it with the help of the Bing Maps forum. Instead of using the REST API am using the FindLocationsAsync call as part of the UWP Map API passing in the address, the local geopoint to use a starting reference (aka a 'hint' location) and the max number of matches to return... here's the code I used which works perfectly. (Note that WayPoint is an object from my model to store various info about a waypoint on the route.)
public async Task<List<WayPoint>> FindAddress(string address)
{
List<WayPoint> matchingWaypoints = new List<WayPoint>();
// Use current location as a query hint so nearest addresses are returned.
BasicGeoposition queryHint = new BasicGeoposition();
queryHint.Latitude = this.CurrentLocation.Position.Latitude;
queryHint.Longitude = this.CurrentLocation.Position.Longitude;
Geopoint hintPoint = new Geopoint(queryHint);
MapLocationFinderResult result =
await MapLocationFinder.FindLocationsAsync(address.Trim(), hintPoint, 5);
// If the query returns results, store in collection of WayPoint objects.
string addresses = "";
if (result.Status == MapLocationFinderStatus.Success)
{
int i = 0;
foreach (MapLocation res in result.Locations)
{
matchingWaypoints.Add(new WayPoint(i++, res.Address.FormattedAddress, res.Point.Position.Latitude, res.Point.Position.Longitude));
}
}
return matchingWaypoints;
}
Using NotificationHubClient I can get all registered devices using GetAllRegistrationsAsync(). But if I do not use the registration model but the installation model instead, how can I get all installations? There are methods to retrieve a specific installation but none to get everything.
You're correct, as of July 2016 there's no way to get all installations for a hub. In the future, the product team is planning to add this feature to the installations model, but it will work in a different way. Instead of making it a runtime operation, you'll provide your storage connection string and you'll get a blob with everything associated with the hub.
Sorry for visiting an old thread... but in theory you could use the GetAllRegistrationsAsyc to get all the installations. I guess this will return everything without an installation id as well, but you could just ignore those if you choose.
Could look something like this
var allRegistrations = await _hub.GetAllRegistrationsAsync(0);
var continuationToken = allRegistrations.ContinuationToken;
var registrationDescriptionsList = new List<RegistrationDescription>(allRegistrations);
while (!string.IsNullOrWhiteSpace(continuationToken))
{
var otherRegistrations = await _hub.GetAllRegistrationsAsync(continuationToken, 0);
registrationDescriptionsList.AddRange(otherRegistrations);
continuationToken = otherRegistrations.ContinuationToken;
}
// Put into DeviceInstallation object
var deviceInstallationList = new List<DeviceInstallation>();
foreach (var registration in registrationDescriptionsList)
{
var deviceInstallation = new DeviceInstallation();
var tags = registration.Tags;
foreach(var tag in tags)
{
if (tag.Contains("InstallationId:"))
{
deviceInstallation.InstallationId = new Guid(tag.Substring(tag.IndexOf(":")+1));
}
}
deviceInstallation.PushHandle = registration.PnsHandle;
deviceInstallation.Tags = new List<string>(registration.Tags);
deviceInstallationList.Add(deviceInstallation);
}
I am not suggesting this to be the cleanest chunk of code written, but it does the trick for us. We only use this for debugging type purposes anyways
I have some problems with my bing maps.
The first one happens when I click on My Location - from almost all locations I were it worked fine, but there are some locations that returns null, why? (It happened me in a new building that hasn't address yet and also happened in a building with no internet connections).
The method:
private async void MyLocation_Click(object sender, RoutedEventArgs e)
{
Bing.Maps.Location location = await GeoLocation.GetCurrentLocationAsync();
MapLayer.SetPosition(_flagPin, location);
map.SetView(location, 15);
}
The first line calls to my static function:
public static async Task<Bing.Maps.Location> GetCurrentLocationAsync()
{
Geolocator geo = new Geolocator();
geo.DesiredAccuracy = PositionAccuracy.Default;
Geoposition currentPosition = null;
currentPosition = await geo.GetGeopositionAsync();
return new Bing.Maps.Location()
{
Latitude = currentPosition.Coordinate.Latitude,
Longitude = currentPosition.Coordinate.Longitude
};
}
What is the problem? How to fix it?
And the second question is about addresses.
When I get an Address object, there are many formats I can select such as FormattedAddress, CountryRegion, PostalTown, I selected The FormattedAddress and there is a problem with it.
My code:
GeocodeResponse GP = await GeoLocation.ReverseGeocodeAsync(location.Latitude, location.Longitude);
EventContext.Address = GP.Results[0].Address.FormattedAddress;
The problem is when I want to send an Address and get the Location.
Sometimes this code returns null, why?
GeocodeResponse GP = await GeoLocation.GeocodeAsync(EventContext.Address);
I thought that maybe the problem is that sometimes the Address (Formatted) is not good, sometimes it gives weird addresses, such as, "Street, st. Canada", which is not found and therefore, it returns null. But what can I do to send a correctly Address? Does FomattedAddress is good?
Here are the two GeoCodeAsync and ReverseGeocodeAsync functions:
public static async Task<GeocodeResponse> GeocodeAsync(string address)
{
GeocodeService.GeocodeRequest geocodeRequest = new GeocodeService.GeocodeRequest();
// Set credentials using a Bing Maps key
geocodeRequest.Credentials = new GeocodeService.Credentials();
geocodeRequest.Credentials.ApplicationId = Application.Current.Resources["BingCredentials"] as string;
// Set the address
geocodeRequest.Query = address;
// Make the geocode request
GeocodeService.GeocodeServiceClient geocodeService = new GeocodeServiceClient(GeocodeServiceClient.EndpointConfiguration.BasicHttpBinding_IGeocodeService);
GeocodeResponse geocodeResponse = await geocodeService.GeocodeAsync(geocodeRequest);
return geocodeResponse;
}
public static async Task<GeocodeResponse> ReverseGeocodeAsync(double latitude, double longitude)
{
ReverseGeocodeRequest reverseGeocodeRequest = new ReverseGeocodeRequest();
// Set credentials using a Bing Maps key
reverseGeocodeRequest.Credentials = new GeocodeService.Credentials();
reverseGeocodeRequest.Credentials.ApplicationId = Application.Current.Resources["BingCredentials"] as string;
// Set the coordinates
reverseGeocodeRequest.Location = new GeocodeService.GeocodeLocation() { Latitude = latitude, Longitude = longitude };
// Make the reverse geocode request
GeocodeServiceClient geocodeService = new GeocodeServiceClient(GeocodeServiceClient.EndpointConfiguration.BasicHttpBinding_IGeocodeService);
GeocodeResponse geocodeResponse = await geocodeService.ReverseGeocodeAsync(reverseGeocodeRequest);
return geocodeResponse;
}
To clarify your first issue, are you getting null from the GPS or is it the address information in the result that is null the issue? If the GPS is returning null then it's possible that your GPS isn't able to get the current position where you are. This has nothing to do with Bing Maps and more so just an issue which your mobile device getting a clear view to the GPS satellites. If the issue is that the address information in the result is null then this is to be expected with new buildings that might not yet be known in the Bing Maps data set. It usually takes several months for new buildings to be found and added to the map data set. If you have no internet connection then the mobile device won't be able to connect to Bing Maps to get the address information. Note that Bing Maps is over 9 Petabytes in size so there is no local copy of the data on your mobile device.
If you already have the coordinates and the address information you shouldn't be geocoding it again. This is a waste of time and will cause issues. The geocoder will sometimes return "street" or "ramp" if the coordinate in which you pass to the reverse geocoder is on an unnamed street. Note geocoders are not designed to clean/validate addresses. They are designed to take an address and return a coordinate. Reverse geocoders are designed to take a coordinate and find the nearest address. Mixing the results from one with the other can result in odd results as the coordinates for each could be significantly different. It rare cases it's possible to loop between both services and get different results each time as the results will slightly be different and end up "walking" along a street.
I'm using the Business Objects Web Services SDK to access our Business Objects data. I've successfully got a list of reports, and from that found the LastSuccessfulInstance of a report that has been previously run. However, I can't seem to get the LastRunTime to be populated. When I do a query with no attributes specified it comes back as not set, and I get the same result when I ask for that attribute in particular. I've looked at the report itself and the instance and they both don't have this information. Does anyone know where I can get it from?
Here's my code (hacked from one of SAP's demos):
var sessConnUrl = serviceUrl + "/session";
var boConnection = new BusinessObjects.DSWS.Connection(sessConnUrl);
var boSession = new Session(boConnection);
// Setup the Enterprise Credentials used to login to the Enterprise System
var boEnterpriseCredential = new EnterpriseCredential
{
Domain = cmsname,
Login = username,
Password = password,
AuthType = authType
};
// Login to the Enterprise System and retrieve the SessionInfo
boSession.Login(boEnterpriseCredential);
/************************** DISPLAY INBOX OBJECTS *************************/
// Retrieve the BIPlatform Service so it can be used to add the USER
var biPlatformUrl = boSession.GetAssociatedServicesURL("BIPlatform");
var boBiPlatform = BIPlatform.GetInstance(boSession, biPlatformUrl[0]);
// Specify the query used to retrieve the inbox objects
// NOTE: Adding a "/" at the end of the query indicates that we want to
// retrieve the all the objects located directly under the inbox.
// Without the "/" Path operator, the inbox itself would be returned.
const string query = "path://InfoObjects/Root Folder/Reports/";
// Execute the query and retrieve the reports objects
var boResponseHolder = boBiPlatform.Get(query, null);
var boInfoObjects = boResponseHolder.InfoObjects.InfoObject;
// If the reports contains a list of objects, loop through and display them
if (boInfoObjects != null)
{
// Go through and display the list of documents
foreach (var boInfoObject in boInfoObjects)
{
var report = boInfoObject as Webi;
if (report == null)
continue;
if (!string.IsNullOrEmpty(report.LastSuccessfulInstanceCUID))
{
var instanceQuery = "cuid://<" + report.LastSuccessfulInstanceCUID + ">";
var instanceResponseHolder = boBiPlatform.Get(instanceQuery, null);
var instance = instanceResponseHolder.InfoObjects.InfoObject[0];
}
}
}
Both report.LastRunTimeSpecified and instance.LastRunTimeSpecified are false and both LastRunTime are 01\01\0001, but I can see a last run time in the Web Intelligence UI.
With a little help from Ted Ueda at SAP support I figured it out. Not all the properties are populated by default you need to append #* to the query string to get everything, i.e. change the line:
const string query = "path://InfoObjects/Root Folder/Reports/";
to:
const string query = "path://InfoObjects/Root Folder/Reports/#*";