Use the geo location API for personalization
Sitefinity Personalization module retrieves geolocation data based on the IP of the visitor currently browsing the site. This enables you to specify different personalization criteria based on visitor location, for example, city, country, and so on.
Work with Sitefinity CMS IpCityLocationService
You can leverage the geolocation service functionality in your custom implementation as well. To do this, you first instantiate the Sitefinity IpCityLocationService. To work with the instance of IpCityLocationService you need to check whether it has successfully loaded the GeoLocation database by using its IsReady property.
The****IsReady property indicates the service is ready for operation. The property may return false in case you are using the IpCityLocationService too early in your code (for example, in the Global.asax). Thus, you make sure Sitefinity has bootstrapped and read its configurations properly. To use the service in Global.asax, make sure to implement the call to IpCityLocationService in the Bootstrapper_Bootstrapped event handler as demonstrated in the following example:
using System;
using Telerik.Sitefinity.Abstractions;
using Telerik.Sitefinity.Personalization.Impl.GeoData;
namespace SitefinityWebApp
{
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
Bootstrapper.Bootstrapped += Bootstrapper_Bootstrapped;
}
private void Bootstrapper_Bootstrapped(object sender, EventArgs e)
{
var lookupService = new IpCityLocationService();
if (lookupService.IsReady)
{
//it's safe to use the service
}
}
}
}
Get a CityLocation by IP
Once you verify the service is ready, you call its GetLocation method by passing an IPAddress parameter. If a match is found for the specified IP address, IpCityLocationService returns a CityLocation object that contains the City, Country, ISO Code, Region, PostalCode, geographic coordinates of the matched location. Refer to the sample below on how to use IpCityLocationService in your code:
using System.Net;
using Telerik.Sitefinity.Personalization.Impl.GeoData;
namespace Sitefinity.Documentation.GeoLocation.Samples
{
public class GeoLocationSamples
{
public CityLocation FindLocation(string ipAddressString)
{
IPAddress ip = null;
IPAddress.TryParse(ipAddressString, out ip);
var lookupService = new IpCityLocationService();
if (lookupService.IsReady)
return lookupService.GetLocation(ip);
else return null;
}
public static void GetCityLocationProperties(CityLocation location)
{
var city = location?.City;
var country = location?.Country;
var region = location?.Region;
}
}
}