Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
StorelocatorGeocodeTask
using Geocoding.Google;
using Nop.Core.Data;
using Nop.Services.Configuration;
using Nop.Services.Logging;
using Nop.Services.Tasks;
using SevenSpikes.Nop.Plugins.StoreLocator.Domain.Shops;
using System;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
namespace Nop.Plugin.Misc.MyPlugin.Tasks
{
public class StorelocatorGeocodeTask : ITask
{
private readonly IRepository<Shop> _shopRepository;
private readonly ILogger _logger;
private readonly ISettingService _settingService;
private const string SETTING_QUERYLIMIT = "StorelocatorGeocodeSettings.QueryLimit";
private const string SETTING_GOOGLEKEY = "StorelocatorGeocodeSettings.GoogleApiKey";
public StorelocatorGeocodeTask(
IRepository<Shop> shopRepository,
ILogger logger,
ISettingService settingService
)
{
this._shopRepository = shopRepository;
this._logger = logger;
this._settingService = settingService;
}
public void Execute()
{
var queryLimit = _settingService.GetSettingByKey<DateTime?>(SETTING_QUERYLIMIT);
if (queryLimit.HasValue && queryLimit.Value > DateTime.Now)
return;
var shops = (from s in _shopRepository.Table
where s.Latitude == null
select s).Take(10).ToList();
var key = _settingService.GetSettingByKey<string>(SETTING_GOOGLEKEY);
foreach (var shop in shops)
{
try
{
var geocoder = new GoogleGeocoder(key);
var address = Regex.Replace(shop.ShortDescription, @"<[^>]+>|&nbsp;", "").Trim();
if (address != null)
{
var addresses = geocoder.Geocode(address);
if (addresses.Count() > 0)
{
shop.Latitude = addresses.First().Coordinates.Latitude.ToString(CultureInfo.InvariantCulture);
shop.Longitude = addresses.First().Coordinates.Longitude.ToString(CultureInfo.InvariantCulture);
shop.IsVisible = true;
_shopRepository.Update(shop);
_logger.Information(string.Format("Storelocator Geocode Update: {0} -> {1} {2}", shop.Name, shop.Latitude, shop.Longitude));
}
else
{
_logger.Warning(string.Format("Storelocator Geocode: Could not found address for {0}: {1}", shop.Name, address));
shop.IsVisible = false;
shop.Latitude = "0";
_shopRepository.Update(shop);
}
}
}
catch (GoogleGeocodingException ge)
{
switch (ge.Status)
{
case GoogleStatus.OverQueryLimit:
var date = DateTime.Now.AddDays(1);
_logger.Warning(string.Format("Storelocator Geocode Error: OverQueryLimit until {0}", date));
_settingService.SetSetting(SETTING_QUERYLIMIT, date);
return;
case GoogleStatus.RequestDenied:
_logger.Warning(string.Format("Storelocator Geocode Error: RequestDenied API Key={0}", key));
return;
default:
_logger.Error(string.Format("Storelocator Geocode Error: Status={1}, {0}", ge.Message, ge.Status), ge);
break;
}
}
catch (Exception e)
{
_logger.Error(string.Format("Storelocator Geocode Error: {0}", e.Message), e);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.