Skip to content

Instantly share code, notes, and snippets.

@jonathanread
Last active August 29, 2015 13:57
Show Gist options
  • Save jonathanread/9840603 to your computer and use it in GitHub Desktop.
Save jonathanread/9840603 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Sitefinity;
using Telerik.Sitefinity.Model;
using Telerik.Sitefinity.DynamicModules;
using Telerik.Sitefinity.Data.Linq.Dynamic;
using Telerik.Sitefinity.DynamicModules.Model;
using Telerik.Sitefinity.GenericContent.Model;
using Telerik.Sitefinity.Utilities.TypeConverters;
using Telerik.Sitefinity.Security;
using Telerik.Sitefinity.Lifecycle;
using Telerik.Sitefinity.Taxonomies;
using Telerik.Sitefinity.Taxonomies.Model;
using Telerik.Sitefinity.Modules.Libraries;
using Telerik.OpenAccess;
using System.IO;
using FileHelpers;
using System.Text.RegularExpressions;
namespace SitefinityWebApp.Custom
{
public partial class ImportSchools : System.Web.UI.Page
{
public List<string> imported = new List<string>();
public List<string> skipped = new List<string>();
public DynamicModuleManager dynamicModuleManager = DynamicModuleManager.GetManager();
public Type certificationSchoolType = TypeResolutionService.ResolveType("Telerik.Sitefinity.DynamicTypes.Model.Certificationschools.CertificationSchool");
public LibrariesManager libraryManager = LibrariesManager.GetManager();
public Type locationType = TypeResolutionService.ResolveType("Telerik.Sitefinity.DynamicTypes.Model.Certificationschools.Location");
public TaxonomyManager taxonomyManager = TaxonomyManager.GetManager();
public string schoolsFile = "School List.csv";
public string locationsFile = "locations.csv";
protected void Page_Load(object sender, EventArgs e)
{
try
{
DeleteAllLocations(true);
DeleteAllCertSchools();
FileHelperEngine engine = new FileHelperEngine(typeof(SchoolImportClass));
SchoolImportClass[] Rows = engine.ReadFile(Server.MapPath("~\\Custom\\")+schoolsFile) as SchoolImportClass[];
foreach (SchoolImportClass line in Rows)
{
CreateCertificationSchool(line);
}
dynamicModuleManager.SaveChanges();
}
catch (Exception ex)
{
if (skipped.Count() > 0)
{
Response.Write("Skipped<br/>");
foreach (string i in skipped)
{
Response.Write(i + "<br />");
}
Response.Write(ex.Message);
}
}
if (skipped.Count() > 0)
{
Response.Write("Skipped<br/>");
foreach (string i in skipped)
{
Response.Write(i + "<br />");
}
}
if (imported.Count() > 0)
{
Response.Write("Imported<br/>");
foreach (string i in imported)
{
Response.Write(i + "<br />");
}
}
//DeleteAllLocations(false);
}
public void CreateCertificationSchool(SchoolImportClass School)
{
try
{
var tempItem = dynamicModuleManager.GetDataItems(certificationSchoolType).Where(i => i.GetValue<string>("Title") == School.School).FirstOrDefault();
if (tempItem == null && School.Description != "")
{
DynamicContent certificationSchoolItem = dynamicModuleManager.CreateDataItem(certificationSchoolType);
// This is how values for the properties are set
certificationSchoolItem.SetValue("Title", School.School);
certificationSchoolItem.SetValue("Description", School.Description);
certificationSchoolItem.SetValue("Summary", School.Summary);
certificationSchoolItem.SetValue("Programs", School.Programs);
certificationSchoolItem.SetValue("AdditionalInformation", School.AdditionalInfo);
certificationSchoolItem.SetValue("ProgramDeliveryType", new string[] { School.ProgramDeliveryType });
certificationSchoolItem.SetValue("CertificationTypes", School.Cerdentials.Split(','));
certificationSchoolItem.SetValue("SchoolType", new string[] { School.SchoolType });
certificationSchoolItem.SetValue("PublicationDate", DateTime.Now);
certificationSchoolItem.SetValue("Owner", SecurityManager.GetCurrentUserId());
//Set Logo
var image = libraryManager.GetImages().FirstOrDefault(i => i.Status == ContentLifecycleStatus.Live && i.Title == School.LogoTitle.Trim());
if (image != null)
{
certificationSchoolItem.AddImage("Logo", image.Id);
}
certificationSchoolItem.UrlName = Regex.Replace(School.School.ToLower(), @"[^\w\-\!\$\'\(\)\=\@\d_]+", "-");
FileHelperEngine engine1 = new FileHelperEngine(typeof(LocationSchoolImportClass));
LocationSchoolImportClass[] Rows1 = engine1.ReadFile(Server.MapPath("~\\Custom\\")+locationsFile) as LocationSchoolImportClass[];
foreach (LocationSchoolImportClass line in Rows1.Where(i=>i.School == School.School))
{
CreateLocations(certificationSchoolItem, line.School + " - " + line.City, line.Email, line.Country, line.State, line.City);
}
// You need to call SaveChanges() in order for the items to be actually persisted to data store
ILifecycleDataItem publishedItem = dynamicModuleManager.Lifecycle.Publish(certificationSchoolItem);
certificationSchoolItem.SetWorkflowStatus(dynamicModuleManager.Provider.ApplicationName, "Published");
imported.Add(School.School);
}
else
{
skipped.Add("already added " + School.School);
}
}
catch (Exception ex)
{
skipped.Add(School.School + "{"+ex.Message+"}");
ex.ToString();
}
}
public void CreateLocations(DynamicContent school, string title, string emails, string country, string state, string city)
{
try
{
var geoRegions = taxonomyManager.GetTaxonomies<HierarchicalTaxonomy>().Where(t => t.Name == "Geographicregions").SingleOrDefault();
var regionTaxa = taxonomyManager.GetTaxa<HierarchicalTaxon>().Where(t => t.Title == country && t.Parent == null).Single();
var stateTaxa = taxonomyManager.GetTaxa<HierarchicalTaxon>().Where(t => t.Title == state && t.Parent.Id == regionTaxa.Id).Single();
if (school != null)
{
CreateLocation(school, title, emails, city, regionTaxa, stateTaxa);
}
else{
skipped.Add("School Empty " + title);
}
}
catch (Exception ex)
{
ex.ToString();
skipped.Add(title + "{" + ex.Message + "}");
}
}
public void CreateLocation(DynamicContent school, string title, string emails, string city, HierarchicalTaxon regionTaxa, HierarchicalTaxon stateTaxa)
{
DynamicContent locationItem = dynamicModuleManager.CreateDataItem(locationType);
try
{
locationItem.SetValue("Title", title);
locationItem.SetValue("City", city);
locationItem.SetValue("Owner", SecurityManager.GetCurrentUserId());
locationItem.SetValue("PublicationDate", DateTime.Now);
if (regionTaxa != null)
{
locationItem.Organizer.AddTaxa("Geographicregions", regionTaxa.Id);
locationItem.Organizer.AddTaxa("Geographicregions", stateTaxa.Id);
}
var emailTaxonomy = taxonomyManager.GetTaxonomies<FlatTaxonomy>().Where(t => t.Name == "E-mailAddresses").FirstOrDefault();
List<Guid> emailGuids = new List<Guid>();
if (emails != "")
{
foreach (string email in emails.Split(','))
{
var EmailAddress = taxonomyManager.GetTaxa<FlatTaxon>().Where(t => t.Title == email.Trim()).FirstOrDefault();
if (EmailAddress != null)
{
emailGuids.Add(EmailAddress.Id);
}
else
{
var taxon = taxonomyManager.CreateTaxon<FlatTaxon>(emailTaxonomy.Id);
string eAddress = email.Trim();
taxon.Name = eAddress;
taxon.Title = eAddress;
emailTaxonomy.Taxa.Add(taxon);
}
}
}
else
{
var EmailAddress = taxonomyManager.GetTaxa<FlatTaxon>().Where(t => t.Title == "[email protected]").FirstOrDefault();
if (EmailAddress != null)
{
emailGuids.Add(EmailAddress.Id);
}
}
if (emailGuids != null && emailGuids.Count() > 0)
{
locationItem.Organizer.AddTaxa("EmailAddresses", emailGuids.ToArray());
}
}
catch (Exception ex)
{
ex.ToString();
skipped.Add(title + "{" + ex.Message + "}");
}
finally
{
// Set item parent
if (school.Id != null)
{
locationItem.SetParent(school.Id, certificationSchoolType.FullName);
locationItem.UrlName = Regex.Replace(title.ToLower(), @"[^\w\-\!\$\'\(\)\=\@\d_]+", "-");
locationItem.SetWorkflowStatus(dynamicModuleManager.Provider.ApplicationName, "Published");
// You need to call SaveChanges() in order for the items to be actually persisted to data store
ILifecycleDataItem publishedItem = dynamicModuleManager.Lifecycle.Publish(locationItem);
imported.Add(title);
}
else
{
skipped.Add(title + " Parent Null");
}
}
}
private static void DeleteAllLocations(bool deleteAll)
{
var locationProviderName = String.Empty;
DynamicModuleManager locationsDynamicModuleManager = DynamicModuleManager.GetManager(locationProviderName);
Type locationType = TypeResolutionService.ResolveType("Telerik.Sitefinity.DynamicTypes.Model.Certificationschools.Location");
var locationsItems = locationsDynamicModuleManager.GetDataItems(locationType).ToList();
foreach (DynamicContent item in locationsItems)
{
if (deleteAll)
{
locationsDynamicModuleManager.DeleteDataItem(item);
}
else
{
if (item.SystemParentId == null || item.SystemParentId == Guid.Empty)
{
locationsDynamicModuleManager.DeleteDataItem(item);
}
}
}
locationsDynamicModuleManager.SaveChanges();
}
private static void DeleteAllCertSchools()
{
var certsProviderName = String.Empty;
DynamicModuleManager certsDynamicModuleManager = DynamicModuleManager.GetManager(certsProviderName);
Type certificationSchoolType = TypeResolutionService.ResolveType("Telerik.Sitefinity.DynamicTypes.Model.Certificationschools.CertificationSchool");
var certificationSchoolItems = certsDynamicModuleManager.GetDataItems(certificationSchoolType).ToList();
foreach (DynamicContent item in certificationSchoolItems)
{
certsDynamicModuleManager.DeleteDataItem(item);
}
certsDynamicModuleManager.SaveChanges();
}
}
[DelimitedRecord(",")]
public class SchoolImportClass
{
[FieldQuoted('"', QuoteMode.OptionalForBoth)]
public string School;
[FieldQuoted('"', QuoteMode.OptionalForBoth)]
public string SchoolType;
[FieldQuoted('"', QuoteMode.OptionalForBoth)]
public string ProgramDeliveryType;
[FieldQuoted('"', QuoteMode.OptionalForBoth)]
public string Cerdentials;
[FieldQuoted('"', QuoteMode.OptionalForBoth)]
public string Description;
[FieldQuoted('"', QuoteMode.OptionalForBoth)]
public string Summary;
[FieldQuoted('"', QuoteMode.OptionalForBoth)]
public string Programs;
[FieldQuoted('"', QuoteMode.OptionalForBoth)]
public string AdditionalInfo;
[FieldQuoted('"', QuoteMode.OptionalForBoth)]
public string LogoTitle;
}
[DelimitedRecord(",")]
public class LocationSchoolImportClass
{
[FieldQuoted('"', QuoteMode.OptionalForBoth)]
public string School;
[FieldQuoted('"', QuoteMode.OptionalForBoth)]
public string City;
[FieldQuoted('"', QuoteMode.OptionalForBoth)]
public string State;
[FieldQuoted('"', QuoteMode.OptionalForBoth)]
public string Country;
[FieldQuoted('"', QuoteMode.OptionalForBoth)]
public string Email;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment