I'm trying to use the Bing Geocoding web service in order to convert adresses to Location in order to add on the Bing WPF Control in my WinForm Application.
My problem is that somes adresses are correctly found by geocoding and some other adresses no !
If i search this adress directly on tha bing maps website it's found.
Here is my sample :
public static GeocodeResponse GetGeocodeResponse(string appId, string address)
{
GeocodeRequest geocodeRequest = new GeocodeRequest
{
Credentials = new Credentials {ApplicationId = appId},
Query = address
};
ConfidenceFilter[] filters = new ConfidenceFilter[1];
filters[0] = new ConfidenceFilter { MinimumConfidence = Confidence.High };
GeocodeOptions geocodeOptions = new GeocodeOptions { Filters = filters };
geocodeRequest.Options = geocodeOptions;
GeocodeServiceClient geocodeServiceClient = new GeocodeServiceClient("BasicHttpBinding_IGeocodeService");
return geocodeServiceClient.Geocode(geocodeRequest);
}
Anyone have same tips in order to solve this ?
Thanks a lot :)
There are several possible things that can be causing this. The first is that you are using a basic or trial account and your requests are being rate limited. This occurs when the servers are under a lot of load or when you make a lot of requests at a frequency that would exceed the free terms of use. This is done to ensure that Enterprise accounts are not affected by the usage of basic or trial users. When rate limiting occurs a flag is added to the header of the response to indicate this:
You are using the old legacy Bing Maps SOAP service which has not been updated in over 4 years. It is generally not recommended to do any new development against those services as they are much slower, have less features and generally return less accurate results than the Bing Maps REST services. I would recommend moving over to the Bing Maps REST services. You can find documentation on how to use them in .NET here:
http://msdn.microsoft.com/en-us/library/ff701713.aspx
http://msdn.microsoft.com/en-us/library/jj819168.aspx
Also, take a look at this blog post:
http://rbrundritt.wordpress.com/2013/02/14/bing-maps-rest-service-tips-amp-tricks-2/
I also cover how to use the REST services in depth in my free eBook in Chapter 5:
http://rbrundritt.wordpress.com/my-book/
Related
I am trying to figure out the right parameters for ItemSearch such that the API call will return the same result as on the website. Currently I am using these params it is not consistent with the website.
url_params = dict(
Service='AWSECommerceService',
Operation='ItemSearch',
AssociateTag=AMAZON_ASSOCIATETAG,
SearchIndex='All',
AWSAccessKeyId=AWS_ACCESS_KEY_ID,
Keywords=keywords,
ResponseGroup='Small,OfferSummary,Images'
)
For example if 'iphone%205s' is put in keywords, the API returns a list of iPhone protectors, while searching on the website gives iPhones as top results.
I am also trying to figure out why this is for book searches. One possible answer I found online was that the websites search feature might use more elaborate queries than just one simple API call. For example, it may take into account other factors into the search (not sure what that might be but it may).
I am looking for a REST service that I could use in demo code. I'd like the service:
To take at least one parameter (as a request parameter, or XML POSTed as the body of the HTTP request).
To return the result as XML (not JSON).
To be accessible anonymously (I'll call the service in sample code, so I don't want to put my key in the code, or request users to get a key).
When the Twitter API supported XML (not just JSON), I was typically using their search API. But really anything mainstream enough, easy enough to understand will do (information about zip code, weather for a city…).
If you are using .Net, why don't you just create a tiny MVC application that has a controller that exposes a method that returns some sort of formatted XML? That way you can run the whole thing locally.
EDIT:
You know, I think you can use Google Maps API without a key. I created a test project a couple of days ago. Here is a .Net code snippet (only included so that you can see how I am calling the service):
private static string GetString(Uri requestUri)
{
var output = string.Empty;
var response = WebRequest.Create(requestUri).GetResponse();
var stream = response.GetResponseStream();
if (stream != null)
{
using (var reader = new StreamReader(stream))
{
output = reader.ReadToEnd();
reader.Close();
}
}
response.Close();
return output;
}
I pass in a uri with a url:
https://maps.googleapis.com/maps/api/directions/xml?mode=walking&origin={0},{1}&destination={2},{3}&sensor=false
Where {0},{1} are the first lat/long, and {2},{3} are the second. I am not attaching a key to this and it worked for testing. My method returns a string that later I handle like so:
var response = XDocument.Parse(GetString(request));
which gives me back xml. Again, I still recommend just creating your own web app and then deploying it somewhere publicly accessible (either in a LAN or on the web), but if you just need a web service to return XML you can use that.
The Yahoo! Weather API can be used for this. It takes a location as a request parameter and returns the weather forecast for that location as XML. It also returns weather information as HTML, which you could display as-is to the user. You can see an example of this below. Also make sure that you respect the term of use described at the bottom of the Weather API documentation page.
I am trying to locate a user through his/her IP address and then show them in a google map. what would be the best approach for this purpose. Or is there any other way to get the user lat/long and show em in a google map instead of IP address.
Your question is actually 2 questions. The first part is getting lat, lng from an ip address. AFAIK, google maps api doesnt provide for IP based geolocation. Therefore to show the IP address on a google map, you must first get the geographic location (either as an address, or as lat, lng). There are various paid and unpaid APIs on the web that allow you to do this, and django itself comes with a utility for this.
The docs are here. Your use case would be implemented as:
from django.contrib.gis.utils import GeoIP
g = GeoIP()
lat,lng = g.lat_lon(user_ip)
or
address = g.city(user_ip)
NOTE: This utility, or one of the many free IP based geolocation APIs might not be VERY accurate.
As for the second part, to show this location on a google map, you could check out this application:
http://code.google.com/p/django-googlemap/
You can use following, but I am not sure if this would work in all browsers.
if (navigator) {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
do_something(position.coords.latitude, position.coords.longitude);
});
}
}
Locating a user would depend on the device you are targeting and granularity/accuracy with which you want to display his location on the map.
The ip address is more suited for laptops and other non-GPS devices. Secondly as you'd know, ip address will only pin point the user's gateway. In my case the gateway is about 8 miles from where I reside so you can imagine the accuracy is only suited for a certain class of apps such analysis tools like omniture or mixpanel.
On the other hand if you are developing your app for a mobile device you can start off reading about it in the question posed here. Using gps/agps will give you accuracy of within a few meters. This is more suited for LBS applications like gowalla or foursquare. HTML5 makes it easy for you to implement the latter especially if you are targeting iOS and Android devices.
Some off the cuff code in python is given below. Details of gmaps api v3 can be found here.
Server implementation in Python to record location and generate markers
class RecordLocation(webapp.RequestHandler):
def post(self):
session=SessionManager(self)
if session.is_set(): marker=Markers(lat=self.request.get('lat'),lon=self.request.get('lon'),user_id=self.request.get('user'))
marker.put()
self.response.out.write('<html><body>')
self.response.out.write(" Location Updated<br/>")
self.response.out.write('</body></html>')
class GenerateMarkers(webapp.RequestHandler):
def get(self):
session=SessionManager(self)
if session.is_set():
markers=db.GqlQuery("SELECT * FROM Markers")
doc='<?xml version="1.0"?>'
doc+='<markers>'
for marker in markers:
doc+='<marker '
doc+='lat="'+marker.lat+'" '
doc+='lon="'+marker.lon+'" '
doc+='type="restaurant" '
doc+='/>'
doc+='</markers>'
self.response.out.write(doc)
We currently have an application that retrieves data from the server through a web service and populates a DataSet. Then the users of the API manipulate it through the objects which in turn change the dataset. The changes are then serialized, compressed and sent back to the server to get updated.
However, I have begin using NHibernate within projects and I really like the disconnected nature of the POCO objects. The problem we have now is that our objects are so tied to the internal DataSet that they cannot be used in many situations and we end up making duplicate POCO objects to pass back and forth.
Batch.GetBatch() -> calls to web server and populates an internal dataset
Batch.SaveBatch() -> send changes to web server from dataset
Is there a way to achieve a similar model that we are using which all database access occurs through a web service but use NHibernate?
Edit 1
I have a partial solution that is working and persisting through a web service but it has two problems.
I have to serialize and send my whole collection and not just changed items
If I try to repopulate the collection upon return my objects then any references I had are lost.
Here is my example solution.
Client Side
public IList<Job> GetAll()
{
return coreWebService
.GetJobs()
.BinaryDeserialize<IList<Job>>();
}
public IList<Job> Save(IList<Job> Jobs)
{
return coreWebService
.Save(Jobs.BinarySerialize())
.BinaryDeserialize<IList<Job>>();
}
Server Side
[WebMethod]
public byte[] GetJobs()
{
using (ISession session = NHibernateHelper.OpenSession())
{
return (from j in session.Linq<Job>()
select j).ToList().BinarySerialize();
}
}
[WebMethod]
public byte[] Save(byte[] JobBytes)
{
var Jobs = JobBytes.BinaryDeserialize<IList<Job>>();
using (ISession session = NHibernateHelper.OpenSession())
using (ITransaction transaction = session.BeginTransaction())
{
foreach (var job in Jobs)
{
session.SaveOrUpdate(job);
}
transaction.Commit();
}
return Jobs.BinarySerialize();
}
As you can see I am sending the whole collection to the server each time and then returning the whole collection. But I'm getting a replaced collection instead of a merged/updated collection. Not to mention the fact that it seems highly inefficient to send all the data back and forth when only part of it could be changed.
Edit 2
I have seen several references on the web for almost a transparent persistent mechanism. I'm not exactly sure if these will work and most of them look highly experimental.
ADO.NET Data Services w/NHibernate (Ayende)
ADO.NET Data Services w/NHibernate (Wildermuth)
Custom Lazy-loadable Business Collections with NHibernate
NHibernate and WCF is Not a Perfect Match
Spring.NET, NHibernate, WCF Services and Lazy Initialization
How to use NHibernate Lazy Initializing Proxies with Web Services or WCF
I'm having a hard time finding a replacement for the DataSet model we are using today. The reason I want to get away from that model is because it takes a lot of work to tie every property of every class to a row/cell of a dataset. Then it also tightly couples all of my classes together.
I've only taken a cursory look at your question, so forgive me if my response is shortsighted but here goes:
I don't think you can logically get away from doing a mapping from domain object to DTO.
By using the domain objects over the wire you are tightly coupling your client and service, part of the reason to have a service in the first place is to promote loose coupling. So that's an immediate issue.
On top of that you're going to end up with a brittle domain logic interface where you can't make changes on the service side without breaking your client.
I suspect your best bet would be to implement a loosely coupled service which implements a REST / or some other loosely coupled interface. You could use a product such as automapper to make the conversions simpler and easier and also flatten data structures as necessary.
At this point I don't know of any way to really cut down the verbosity involved in doing the interface layers but having worked on large projects that didn't make the effort I can honestly tell you the savings wasn't worth it.
I think your issue revolves around this issue:
http://thatextramile.be/blog/2010/05/why-you-shouldnt-expose-your-entities-through-your-services/
Are you or are you not going to send ORM-Entities over the wire?
Since you have a Services-Oriented architecture.. I (like the author) do not recommend this practice.
I use NHibernate. I call those ORM-Entities. They are THE POCO model. But they have "virtual" properties that allow for lazy-loading.
However, I also have some DTO-Objects. These are also POCO's. These do not have lazy'loading friendly properties.
So I do alot of "converting". I hydrate ORM-Entities (with NHibernate)...and then I end up converting them to Domain-DTO-Objects. Yes, it stinks in the beginning.
The server sends out the Domain-DTO-Objects's. There is NO lazy loading. I have to populate them with the "Goldie Locks" "just right" model. Aka, if I need Parent(s) with one level of children, I have to know that up front and send the Domain-DTO-Objects over that way, with just the right amount of hydration.
WHen I send back Domain-DTO-Objects's (from client to the server), I have to reverse the process. I convert the Domain-DTO-Objects into ORM-Entities. And allow NHibernate to work with the ORM-Entities.
Because the architecture is "disconnected", I do alot of (NHiberntae) ".Merge()" calls.
// ormItem is any NHibernate poco
using (ISession session = ISessionCreator.OpenSession())
{
using (ITransaction transaction = session.BeginTransaction())
{
session.BeginTransaction();
ParkingAreaNHEntity mergedItem = session.Merge(ormItem);
transaction.Commit();
}
}
.Merge is a wonderful thing. Entity Framework does not have it. Boo.
Is this alot of setup? Yes.
Do I think it is perfect? No.
However. Because I send very basic DTO's(Poco's) that are not "flavored" to the ORM, I have the ability to switch ORM's without killing my contracts to the outside world.
My datalayer can be ADO.NET, EF, NHibernate, or anything. I have to write the "Converters" if I switch, and the ORM code, but everything else is isolated.
Many people argue with me. They said I'm doing too much, and the ORM-Entities are fine.
Again, I like to "now allow any lazy loading" appearances. And I prefer to have my data-layer isolated. My clients should not know or care about my data-layer/orm of choice.
There are just enough subtle differences (or some not so subtle ones) between EF and NHibernate to screwball the game plan.
Do my Domain-DTO-Objects's look 95% like my ORM-Entities? Yep. But its the 5% that can screwball you.
Moving from DataSets, especially if they are populated from stored-procedures with alot of biz-logic in the TSQL, isn't trivial. But now that I do object model, and I NEVER write a stored procedure that isn't simple CRUD functions, I'd never go back.
And I hate maintenance projects with voodoo TSQL in the stored procedures. It ain't 1999 anymore. Well, most places.
Good luck.
PS Without .Merge(in EF), here is what you have to do in a disconnected world: (boo microsoft)
http://www.entityframeworktutorial.net/EntityFramework4.3/update-many-to-many-entity-using-dbcontext.aspx
I have an ASP.net web service that I'm using for a web application which returns a either XML or JSON data to me, depending on the function I call. This has been working well thus far, but I've run into a problem. I want to create an "export" link on my page that will download a JSON file. The link is formatted very simply:
Export This Item
As you might imagine, this should export item 2. So far so good, yes?
Problem is that since I'm not specifically requesting that the accepted content type is JSON, ASP.net absolutely refuses to send back anything but XML, which just isn't appropriate for this situation. The code is essentially as follows:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public Item ExportItem(int itemId)
{
Context.Response.AddHeader("content-disposition", "attachment; filename=export.json"); //Makes it a download
return GetExportItem(itemId);
}
Despite my specifying the ResponseFormat as JSON, I always get back XML unless I request this method via AJAX (using Google Web Toolkit, BTW):
RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, "mywebserviceaddress/ExportFunc");
builder.setHeader("Content-type","application/json; charset=utf-8");
builder.setHeader("Accepts","application/json");
builder.sendRequest("{\"itemId\":2}", new RequestCallback(){...});
That's great, but AJAX won't give me a download dialog. Is there any way to force ASP.net to give me back JSON, regardless of how the data is requested? It would seem to me that not having a manual override for this behavior is a gross design oversight.
QUICK ANSWER:
First off, let me say that I think that womp's answer is probably the better way to go long term (Convert to WCF), but deostroll led me to the answer that I'll be using for the immediate future. Also, it should be noted that this seems to work primarily because I wanted just a download, may not work as well in all situations. In any case, here's the code that I ended up using to get the result I wanted:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void ExportItem(int itemId)
{
Item item = GetExportItem(itemId);
JavaScriptSerializer js = new JavaScriptSerializer();
string str = js.Serialize(item);
Context.Response.Clear();
Context.Response.ContentType = "application/json";
Context.Response.AddHeader("content-disposition", "attachment; filename=export.json");
Context.Response.AddHeader("content-length", str.Length.ToString());
Context.Response.Flush();
Context.Response.Write(str);
}
Please note the return type of void (which means that your WDSL will be next to useless for this function). Returning anything will screw up the response that is being hand-built.
Asp.net web services are SOAP-based web services. They'll always return XML. The Ajax libraries came along and the ScriptMethod stuff was introduced, but it doesn't change the underlying concept of it.
There's a couple things you can do.
WebMethods are borderline obsolete with the introduction of WCF. You might consider migrating your web services to WCF, in which you'll have much greater control over the output format.
If you don't want to do that, you can manually serialize the result of your webservice calls into JSON, and the service will wrap that in a SOAP header. You would then need to strip out the SOAP stuff.
Here are two forums threads for your reference:
http://forums.asp.net/t/1118828.aspx
http://forums.asp.net/p/1054378/2338982.aspx#2338982
I have no clear idea. They say on concentrating on setting the content type to application/json. I haven't worked with wcf before, but I think you can make use of the Response object.
Set the content type on the response object. Do a response.write passing your json data as string and then do a response.end.
Just thought I'd throw this out there since it wasn't mentioned previously... if you use WebServices with ASP.NET 3.5, JSON is the default return format. It also comes along with JSON serializer so you can stop using the JavascriptSerializer.
This article on Rick Strahl's blog talks about the strongly-typed conversion you can do between server side classes and JSON objects from the client.
I've recently completed a project using this new JSON stuff in .NET 3.5, and I'm extremely impressed with the performance. Maybe it's worth a look...