Created
March 4, 2011 21:10
-
-
Save davecowart/855709 to your computer and use it in GitHub Desktop.
Geolocation logic
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace App.Models { | |
public class IPLocation { | |
public string ZipPostalCode { get; set; } | |
public double Latitude { get; set; } | |
public double Longitude { get; set; } | |
public string City { get; set; } | |
public string RegionName { get; set; } | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace App.Controllers { | |
public class LocationControllerBase : Controller { | |
private const string zipCodeCache = "zipCodeCache"; | |
private const string ipLocationCache = "ipLocationCache"; | |
public string ZipCode { | |
get { | |
if (Session[zipCodeCache] == null) { | |
if (Request.IsAuthenticated) { | |
using (var container = new WindsorContainer()) { | |
IGenericRepository<UserProfile> _userProfileRepository = new GenericRepository<UserProfile>(ConfigurationManager.ConnectionStrings["BaseJunkieConnectionString"].ConnectionString); | |
Session[zipCodeCache] = _userProfileRepository.Get.Single(up => up.UserId == UserId()).PostalCode; | |
} | |
} else { | |
Session[zipCodeCache] = Location.ZipPostalCode.Trim(); | |
} | |
} | |
return Session[zipCodeCache].ToString(); | |
} | |
} | |
public virtual IPLocation Location { | |
get { | |
if (Session[ipLocationCache] == null) { | |
string ipURL = ConfigurationManager.AppSettings["IPLocationAPI"]; | |
string ipAddress = Request.ServerVariables["REMOTE_ADDR"]; | |
if (new string[] { "127.0.0.1", @"::1" }.Contains(ipAddress)) { | |
ipAddress = "71.12.191.59"; // Default for testing on localhost | |
} | |
XDocument xDoc = XDocument.Load(string.Concat(ipURL, ipAddress)); | |
IPLocation location = new IPLocation() { | |
ZipPostalCode = xDoc.Element("Response").Element("ZipPostalCode").Value, | |
Latitude = Double.Parse(xDoc.Element("Response").Element("Latitude").Value), | |
Longitude = Double.Parse(xDoc.Element("Response").Element("Longitude").Value), | |
City = xDoc.Element("Response").Element("City").Value, | |
RegionName = xDoc.Element("Response").Element("RegionName").Value | |
}; | |
Session[ipLocationCache] = location; | |
} | |
return Session[ipLocationCache] as IPLocation; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment