Created
June 9, 2014 15:01
-
-
Save jonathanread/0af32a7d17198e8c849e to your computer and use it in GitHub Desktop.
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
using System; | |
using System.Linq; | |
using Telerik.Sitefinity.Scheduling; | |
using System.Web.Configuration; | |
using System.Net.Http; | |
using System.Net.Http.Headers; | |
using System.Web.Script.Serialization; | |
using Aptera.Sitefinity.Data.DynamicModules; | |
using System.Collections.Generic; | |
using Telerik.Sitefinity.Abstractions; | |
using Aptera.Sitefinity.Data.ECommerce; | |
using Telerik.Sitefinity.GeoLocations.Model; | |
using Telerik.Sitefinity.Locations; | |
using Telerik.Sitefinity.Configuration; | |
using Telerik.Sitefinity.Locations.Configuration; | |
using Aptera.Sitefinity.Model; | |
using GoogleMaps.LocationServices; | |
using Telerik.Sitefinity.Modules.Ecommerce.Catalog; | |
using Telerik.Sitefinity.Modules.Ecommerce.Common; | |
using Telerik.Sitefinity.Ecommerce.Catalog.Model; | |
using Telerik.Sitefinity.Model; | |
using Telerik.Sitefinity.DynamicModules; | |
using Telerik.Sitefinity.DynamicModules.Model; | |
using Telerik.Sitefinity.GenericContent.Model; | |
using Telerik.Sitefinity.Utilities.TypeConverters; | |
namespace Aptera.Sitefinity.Scheduling | |
{ | |
public class RecurringScheduledTask : ScheduledTask | |
{ | |
public override string TaskName | |
{ | |
get | |
{ | |
return "Aptera.Sitefinity.Scheduling.RecurringScheduledTask, Aptera.Sitefinity"; | |
} | |
} | |
public RecurringScheduledTask() | |
{ | |
this.Key = "868C0440-705E-6A7D-A775-FF0A00BA8CFC"; | |
} | |
public override void ExecuteTask() | |
{ | |
//Get data from BRDB Service | |
CreateSchools(); | |
CreateProgramTypes(); | |
CreateProducts(); | |
CleanUp(); | |
ReScheduleTask(); | |
} | |
/// <summary> | |
/// Rescheduled Task based on interval set in AppSettings BRDBRecurringScheduledTaskInterval | |
/// </summary> | |
private static void ReScheduleTask() | |
{ | |
SchedulingManager schedulingManager = SchedulingManager.GetManager(); | |
double interval = (string.IsNullOrEmpty(WebConfigurationManager.AppSettings["BRDBRecurringScheduledTaskInterval"])) ? 720 : double.Parse(WebConfigurationManager.AppSettings["BRDBRecurringScheduledTaskInterval"]); | |
RecurringScheduledTask newTask = new RecurringScheduledTask() { ExecuteTime = DateTime.UtcNow.AddMinutes(interval) }; | |
schedulingManager.AddTask(newTask); | |
schedulingManager.SaveChanges(); | |
} | |
#region Creation Methods | |
/// <summary> | |
/// Clean up unused items | |
/// </summary> | |
private void CleanUp() | |
{ | |
CatalogManager manager = CatalogManager.GetManager(); | |
EcommerceManager ecommerceManager = EcommerceManager.GetManager(); | |
ProductType productType = ecommerceManager.GetProductTypes().Where(t => t.Title == "Program").FirstOrDefault(); | |
IQueryable<Product> products = manager.GetProducts(productType.ClrType).Where(p => p.Visible && p.Status == ContentLifecycleStatus.Live); | |
DynamicModuleManager dynamicModuleManager = DynamicModuleManager.GetManager(); | |
Type programTypeType = TypeResolutionService.ResolveType("Telerik.Sitefinity.DynamicTypes.Model.ProgramTypes.ProgramType"); | |
IQueryable<DynamicContent> programTypes = dynamicModuleManager.GetDataItems(programTypeType).Where(i => i.Status == ContentLifecycleStatus.Master); | |
Type schoolType = TypeResolutionService.ResolveType("Telerik.Sitefinity.DynamicTypes.Model.Schools.School"); | |
IQueryable<DynamicContent> schools = dynamicModuleManager.GetDataItems(schoolType).Where(i =>i.Status == ContentLifecycleStatus.Master); | |
List<DynamicContent> removeSchools = new List<DynamicContent>(); | |
List<DynamicContent> removeProgramTypes = new List<DynamicContent>(); | |
foreach (DynamicContent s in schools) | |
{ | |
var live = (DynamicContent)dynamicModuleManager.Lifecycle.GetLive(s); | |
var i = products.Where(p => p.GetValue<string>("School") == live.Id.ToString()).FirstOrDefault(); | |
if (i == null) | |
{ | |
dynamicModuleManager.DeleteDataItem(s); | |
removeSchools.Add(s); | |
} | |
} | |
foreach (DynamicContent pt in programTypes) | |
{ | |
var live = (DynamicContent)dynamicModuleManager.Lifecycle.GetLive(pt); | |
var i = products.Where(p => p.GetValue<string>("ProgramType") == live.Id.ToString()).FirstOrDefault(); | |
if (i == null) | |
{ | |
dynamicModuleManager.DeleteDataItem(pt); | |
removeProgramTypes.Add(pt); | |
} | |
} | |
removeProgramTypes.ToString(); | |
removeSchools.ToString(); | |
dynamicModuleManager.SaveChanges(); | |
} | |
/// <summary> | |
/// Create Schools into Sitefinity DynamicModule "School" | |
/// </summary> | |
private void CreateSchools() | |
{ | |
HttpResponseMessage response = GetApiResponse("/api/school"); | |
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer(); | |
if (response.IsSuccessStatusCode) | |
{ | |
try | |
{ | |
IEnumerable<School> schools = jsonSerializer.Deserialize<IEnumerable<School>>(response.Content.ReadAsStringAsync().Result); | |
foreach (School s in schools) | |
{ | |
DynamicContent tempSchool = School.GetSchoolByTitle(s.Name); | |
if (tempSchool == null) | |
{ | |
s.CreateSchool(); | |
} | |
else if (tempSchool.GetValue<string>("Title") == s.Name && DateTime.Compare(tempSchool.DateCreated, s.UpdatedDate) < 0) | |
{ | |
tempSchool = School.CheckOutSchool(tempSchool); | |
tempSchool.SetValue("Description", s.Description); | |
tempSchool.SetValue("SchoolID", s.Id); | |
tempSchool.SetValue("ParentSchoolID", s.ParentSchoolId); | |
Address address = new Address(); | |
CountryElement addressCountry = Config.Get<LocationsConfig>().Countries.Values.First(x => x.Name == "United States"); | |
address.CountryCode = addressCountry.IsoCode; | |
address.StateCode = s.State; | |
address.City = s.City; | |
address.Street = s.Address1; | |
address.Zip = s.Zip; | |
Coordinates coordinates = GetLatLong(address); | |
address.Latitude = coordinates.Latitude; | |
address.Longitude = coordinates.Longitude; | |
address.MapZoomLevel = 8; | |
tempSchool.SetValue("Address", address); | |
School.CheckInPublishSchool(tempSchool); | |
} | |
} | |
} | |
catch (Exception ex) | |
{ | |
Log.Write(ex); | |
} | |
} | |
else | |
{ | |
Log.Write(response.ReasonPhrase); | |
} | |
} | |
/// <summary> | |
/// Create Ecommerce Products | |
/// </summary> | |
private void CreateProducts() | |
{ | |
HttpResponseMessage response = GetApiResponse("/api/program"); | |
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer(); | |
try | |
{ | |
if (response.IsSuccessStatusCode) | |
{ | |
IEnumerable<CustomProduct> products = jsonSerializer.Deserialize<IEnumerable<CustomProduct>>(response.Content.ReadAsStringAsync().Result); | |
foreach (CustomProduct cp in products) | |
{ | |
DynamicContent school = School.GetSchoolById(cp.SchoolId); | |
DynamicContent programType = ProgramType.GetProgramTypeById(cp.Type); | |
if (school != null && programType != null) | |
{ | |
cp.Title = school.GetValue("Title").ToString() + " - " + programType.GetValue("Title").ToString(); | |
if (CustomProduct.GetProductByTitle(cp.Title) == null) | |
{ | |
cp.School = school.Id; | |
cp.ProgramType = programType.Id; | |
cp.IsShippable = true; | |
cp.Weight = 1; | |
cp.Sku = cp.Id; | |
cp.CreateProduct(); | |
} | |
} | |
} | |
} | |
} | |
catch (Exception ex) | |
{ | |
Log.Write(ex); | |
} | |
} | |
/// <summary> | |
/// Create ProgramTypes into Sitefinity DynamicModule "ProgramTypes" | |
/// </summary> | |
private void CreateProgramTypes() | |
{ | |
HttpResponseMessage response = GetApiResponse("/api/programtype"); | |
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer(); | |
try | |
{ | |
if (response.IsSuccessStatusCode) | |
{ | |
IEnumerable<ProgramType> programtypes = jsonSerializer.Deserialize<IEnumerable<ProgramType>>(response.Content.ReadAsStringAsync().Result); | |
foreach (ProgramType pt in programtypes) | |
{ | |
if (ProgramType.GetProgramTypeByTitle(pt.CourseType) == null) | |
{ | |
if (!string.IsNullOrEmpty(pt.CourseType)) | |
{ | |
pt.CreateProgramType(); | |
} | |
} | |
} | |
} | |
else | |
{ | |
Log.Write(response.ReasonPhrase); | |
} | |
} | |
catch (Exception ex) | |
{ | |
Log.Write(ex); | |
} | |
} | |
#endregion | |
#region Helpers | |
/// <summary> | |
/// Get Response from API | |
/// </summary> | |
/// <param name="api">Relative path from AppSetting BRDBServiceUrl</param> | |
/// <returns></returns> | |
private static HttpResponseMessage GetApiResponse(string api) | |
{ | |
try | |
{ | |
HttpClient client = new HttpClient(); | |
string baseApiAddress = WebConfigurationManager.AppSettings["BRDBServiceUrl"]; | |
client.BaseAddress = new Uri(baseApiAddress); | |
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); | |
HttpResponseMessage response = client.GetAsync(api).Result; | |
return response; | |
} | |
catch (Exception ex) | |
{ | |
Log.Write(ex); | |
return null; | |
} | |
} | |
private Coordinates GetLatLong(Address addressObj) | |
{ | |
string address = string.Format("{0} {1},{2} {3} ", addressObj.Street, addressObj.City, addressObj.StateCode, addressObj.Zip); | |
var locationService = new GoogleLocationService(); | |
var point = locationService.GetLatLongFromAddress(address); | |
return new Coordinates { Latitude = point.Latitude, Longitude = point.Longitude }; | |
} | |
#endregion | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment