Get location name by giving ZIP codes - c#

I need to display the location and city name when a user enters a ZIP Code. How do I get the corresponding location names?

I would use a website like
http://www.zipinfo.com/search/zipcode.htm
and just send the zipcode to that, retrieve the input, parse for the city name, easy as that.

Try the USPS zipcode API - http://www.usps.com/webtools/welcome.htm

You can use the PlaceFinder geocoding web service to make REST based requests using the postal code you want to resolve to a name. The service supports both XML and JSON response formats. Here is a listing of the response elements returned by the service.
Using .NET, you would leverage the client or request/response classes in the System.Net namespace to make a request to the service and process the reponse.

The simplest way would be to use strings. You could alternatively create a ZIP class, if you wanted to get fancy.
using System;
using System.Collections.Generic;
class Program
{
// declare your variable
private static Dictionary<string, string> zipLookup;
public static void CreateZips()
{
zipLookup = new Dictionary<string, string>();
zipLookup.Add("90210", "Beverly Hills");
// fill all other values, probably from a db
}
static void Main(string[] args)
{
CreateZips();
var test = "90210";
if (zipLookup.ContainsKey(test))
{
Console.WriteLine(test.ToString() + "=" + zipLookup[test]);
}
else
{
Console.WriteLine(test.ToString() + " location unknown");
}
}
}
For more details on ZIPs, check out Wikipedia

I work in the address verification industry for a company called SmartyStreets. The solutions presented here are all functional in a variety of ways, but beware of their limitations and specialties. For example, Yahoo's service is more like address suggestion, not validation. The USPS web service is quite limited in the results it returns, for example: you won't get the County and Component data of an address, actual deliverability, etc.
For a more flexible, free solution -- may I suggest our LiveAddress API? It's a REST-ful endpoint which, given a street address (for example) and ZIP code, will fully and accurately complete the entire address.

Alternatively, you can use https://thezipcodes.com/
This has almost all the data that I used for the search.
Use http://thezipcodes.com/docs to use the API.

Related

Server-Side Request Forgery Fortify Fix

I'm trying to call a webservice. This webservice call depends on the user input as the URL.
The URL looks like follows:
https://someurl.com/somefunction/{userinput}
And my function looks like this
public async Task<Data> GetData(string input)
{
try
{
Address = BaseAddress; // https://someurl.com/somefunction/{userinput}
Address = Address.Replace("{userinput}", input);
....
WebService ws = await base.GetData(httpClient, serverIPaddress);
....
}
}
And I get the security error from Fortify
Server-Side Request Forgery (Input Validation and Representation, Data
Flow)
The function GetAsync() on line 122 initiates a network connection to
a third-party system using user-controlled data for resource URI. An
attacker may leverage this vulnerability to send a request on behalf
of the application server since the request will originate from the
application server's internal IP address.
Here are the recommendations:
Recommendations:
Do not establish network connections based on user-controlled data and
ensure that the request is being sent to the expected destination. If
user data is necessary to build the destination URI, use a level of
indirection: create a list of legitimate resource names that a user is
allowed to specify, and only allow the user to select from the list.
With this approach the input provided by the user is never used
directly to specify the resource name.
In some situations this approach is impractical because the set of
legitimate resource names is too large or too hard to keep track of.
Programmers often resort to blacklisting in these situations.
Blacklisting selectively rejects or escapes potentially dangerous
characters before using the input. However, any such list of unsafe
characters is likely to be incomplete and will almost certainly become
out of date. A better approach is to create a whitelist of characters
that are allowed to appear in the resource name and accept input
composed exclusively of characters in the approved set.
Also, if required, make sure that the user input is only used to
specify a resource on the target system but that the URI scheme, host,
and port is controlled by the application. This way the damage that an
attacker is able to do will be significantly reduced.
But the thing is that I really need to change {userinput} based on the supplied data from user. {userinput} will be a string with a certain maximum length.
How to resolve this issue?
After so much research and hit and try attempts, I finally got this working by appending the input in the BaseAddress
The sample code looks like
public async Task<Data> GetData(string input)
{
try
{
var httpClient = new HttpClient();
httpClient.BaseAddress = new Uri($"https://someurl.com/somefunction/{input}");
var content = await httpClient.GetStringAsync("");
return JsonConvert.DeserializeObject<Data>(content);
}
}

How to get Sub Domain on Web API Action

I am developing a Classified Web Site. This web site has a lot of Sub Domains like dubai.sitedomain.com, london.sitedomain.com, newyork.sitedomain.com etc depending on cities. I am using Angularjs as my front end and Web Api as server side.
My requirement is I want to get the subdomain on my Web Api Action. Like:
[HttpGet]
[Route("GetAds")]
public IHttpActionResult GetAds()
{
// Here I want to know, from which subdomain the request has been sent
// so I can filter my ads according to the city
var city = "city from subdomain";
var list = _adService.GetAdsByCity(city);
return Ok(list);
}
Use Request.Headers.Referrer.Host.Replace(".sitedomain.com", string.Empty);
Of course this will only work on your live environment, so you may need to modify this to work differently on your local test domains, or provide some sort of default fallback. I would suggest extracting this to a method in a common library, as it's likely you will need it in many places.
Alternatively, if you know that it will always be the first part, you can use
Request.Headers.Referrer.Host.Substring(0, Request.Headers.Referrer.Host.IndexOf("."));
You can extract it from
var x = Request.Host.Value;
Which will give you "london.sitedomain.com:port"
You can then do a
x.Split('.')[0] //(for example)
To get the subdomain
This should get you what you need.
HttpContext.Current.Request.UserHostAddress;
HttpContext.Current.Request.UserAgent;
HttpContext.Current.Request.Url.OriginalString;
There is also:
Request.Url.Scheme
Request.Url.Authority
Request.ApplicationPath
You can get host from HttpRequestMessage.RequestUri.Host:
string host = Request.RequestUri.Host;
int index = host.IndexOf('.');
return host.Substring(0, index + 1)

how to get country name from latitude and longitude

How can i get the country name from latitude and longtitude using c#?
Im using the Bing.Map API
Location location12 = new Location(location.Latitude, location.Longitude);
MapLayer.SetPosition(pin, location12);
Map.Children.Add(pin);
string placeName = GetPlaceNameForCoordinates(location.Latitude, location.Longitude);
You'll want to use a reverse geocoding API of some kind. For example:
The Bing Maps API (the webservice)
The Google Geocoding API
The Geonames API
If you're already using the Bing.Maps SDK, you should use the Map.SearchManager property to get a SearchManager, and then use the ReverseGeocodeAsync method. In particular, as noted in comments, mixing and matching which API you use to show data via other SDKs may well violate the terms and conditions of both: be careful which technologies you use within a single application. (Even though this question gives sample code using the Bing Maps SDK, I've kept the list above in order to help others who may come with a slightly different context.)
For example:
var manager = map.SearchManager;
var request = new ReverseGeocodeRequestOptions(location) {
IncludeEntityTypeFlags = ReverseGeocodeEntityType.CountryRegion
};
var response = await manager.ReverseGeocodeAsync(
new ReverseGeocodeRequestOptions(location) { );
// Use the response
If you decide to use the Geonames API, the data can be downloaded for offline use too.
I've created a github project with sample code that does this without api calls
see here
Very simple country name and id returned

What to include when signing an API request

If I have a complex object that is been sent as an API request (for example Order below), should I include all the properties when generating the signature or should I use just a subset?
I am asking because I am unclear and from looking at other API's the requests parameters are flat and simple
public class Order
{
public string Id { get; set; }
public string ClientIdentifier { get; set; }
public IEnumerable<OrderItems> OrderItems { get; set; }
public long timestamp { get; set; }
public string signature { get; set; }
}
public class OrderItems
{
public string ItemId { get; set; }
public string Name { get; set; }
public IEnumerable<decimal> PriceBands { get; set; }pes
more types
}
and so on ....
You first need to understand what the signing of the message prevents to understand what data should be included in the request. Here's a list of the 2 main things that signing the requests block attackers from being able to do.
With a signed request the password is kept safe and an attacker cannot use the information in the query to sign another request. This is helpful if the attacker can see the request being sent to the server.
The attacker cannot modify any data in the request that has been used to generate the signature without invalidating the signature, causing the request to be refused by the server.
Number 2 has a catch to it. It only helps protect the data that is part of the signature. If you leave any data out an attacker could change that data and send a different message than the message you sent. This is why when signing a request all of the request data needs to be included: The full URI including the domain, headers, querystring parameters, and any posted data such as XML or JSON.
As hinted by naveen in the comment above, your question does not seem to be a an OAuth question directly:
Looking at the (quite good) explanation of the OAuth flow at http://hueniverse.com/oauth/guide/authentication/ leads to the conclusion that all parameters in an OAuth request need to be used in signing the request because the server will also take all parameters (by definition) to validate the signature, so my suggestion is to use all parameters for signing, too ;)
But (as a side note):
Your code shows a complex data strutcture which should be submitted, so this raises some more questions: how do you encode the data to be transferable via HTTP? How does the server implementation look like (is it your own implementation or a given service)?
Assuming that you serialize the data to XML or JSON to be used as a request parameter, you'll get "just a string" for the data. This data - used as a request parameter - will completely be used for signing as mentioned above.
I'd also suggest using an Open-Source OAuth client implementation. A good place to start looking for one is the Twitter Client Library page at https://dev.twitter.com/docs/twitter-libraries#dotnet because Twitter uses OAuth for 3rd-party access to its API and the libraries (OAuth components like Hammock) are stable.
As it was already pointed out you need to figure out what attacks you want to prevent.
Usual approach to case when data you are submitting is sensitive is to use HTTPS (SSL) to communicate with the server. In this case you don't need to encrypt/sign data itself, any plain protocol including sending JSON is OK.
If you want to prevent unknown clients to post the data use mutual SSL which will allow you to limit what client can talk to server.
If you want to verify data is not tampered with over HTTP - sign whole data block... But it is much harder to implement correctly that using existing SSL connection. Check out http://blogs.msdn.com/b/ericlippert/archive/2011/09/27/keep-it-secret-keep-it-safe.aspx

How can I use Google Search in my C# project?

i build mini Question Answering System in C#. I need retrieve document by google Search.
What is google tools name, i can use it in my project?
Thanks
One possibility is to set up a custom Google search engine. Then you also need to create a developer key, which I believe is done under the console.
After setting that up, you can make REST style call with code such as the following, which retrieves the results as JSON:
WebClient w = new WebClient();
string result;
string uri;
string googleAPIKey = "your developer key";
string googleEngineID = "your search engine id";
string template = "https://www.googleapis.com/customsearch/v1?key={0}&cx={1}&q={2}&start={3}&alt=json";
int startIndex = 1;
int gathered = 0;
uri = String.Format(template, googleAPIKey, googleEngineID, "yoursearchstring", startIndex);
result = w.DownloadString(uri);
For extracting the information from the JSON results, you can use something like Json.NET. It makes it extremely easy to read the information:
JObject o = JObject.Parse(result);
Then you can directly access the desired information with a single line of code.
One important piece of information is that the search API free usage is extremely limited (100 requests per day). So for a real-world application it would probably be necessary to pay for the search. But depending on how you use it, maybe 100 requests per day is sufficient. I wrote a little mashup using the Google search API to search for Stackoverflow site information of interest and then used the StackExchange API to retrieve the information. For that personal use, it works very well.
I've never used it before (and it's alpha), but take a look at Google APIs for .NET Framework library.

Categories

Resources