internal MemberMapping FindDeclaringMapping(MemberMapping member, out StructMapping declaringMapping, string parent) { declaringMapping = null; if (BaseMapping != null) { MemberMapping baseMember = BaseMapping.FindDeclaringMapping(member, out declaringMapping, parent); if (baseMember != null) { return(baseMember); } } if (_members == null) { return(null); } for (int i = 0; i < _members.Length; i++) { if (_members[i].Name == member.Name) { if (_members[i].TypeDesc != member.TypeDesc) { throw new InvalidOperationException(SR.Format(SR.XmlHiddenMember, parent, member.Name, member.TypeDesc.FullName, this.TypeName, _members[i].Name, _members[i].TypeDesc.FullName)); } else if (!_members[i].Match(member)) { throw new InvalidOperationException(SR.Format(SR.XmlInvalidXmlOverride, parent, member.Name, this.TypeName, _members[i].Name)); } declaringMapping = this; return(_members[i]); } } return(null); }
/// <summary> /// Searches the node hierarchy for a specified search term and places the result in the nodes parameter. /// </summary> /// <param name="searchTerm">The mapping to search for.</param> /// <param name="nodes">This collection is returned with the matching nodes.</param> /// <returns>List of nodes matching the search criteria.</returns> public override List <Component> FindMany(BaseMapping searchTerm, List <Component> nodes) { // check if search contains regex if (!string.IsNullOrEmpty(searchTerm.RegexPattern)) { var regexMatch = Regex.Match(Name, searchTerm.RegexPattern); if (regexMatch.Success) { nodes.Add(this); } } else { if (searchTerm.OpenEhrFieldPath == Name || Name.Split(':')[0] == searchTerm.OpenEhrFieldPath) { nodes.Add(this); } } foreach (var component in Children) { nodes = component.FindMany(searchTerm, nodes); } return(nodes); }
public void Run(Item processor, Item itemToProcess, Item fieldMapping) { BaseMapping baseMap = new BaseMapping(fieldMapping); string findPattern = processor.Fields["Find"].Value; string replacePattern = processor.Fields["Replace"].Value; string replaceReportingText = string.IsNullOrEmpty(replacePattern) ? "*remove*" : replacePattern; try { HtmlDocument document = new HtmlDocument(); string content = itemToProcess.Fields[baseMap.NewItemField].Value; document.LoadHtml(content); HtmlNode node = Helper.HandleNodesLookup(findPattern, document); using (new SecurityModel.SecurityDisabler()) { itemToProcess.Editing.BeginEdit(); if (node != null) { if (findPattern.Contains("/*") && node.ChildNodes != null) { foreach (var child in node.ChildNodes) { content = content.Replace(child.OuterHtml, replacePattern); itemToProcess.Fields[baseMap.NewItemField].Value = content; } } else { itemToProcess.Fields[baseMap.NewItemField].Value = content.Replace(node.OuterHtml, replacePattern); } ImportReporter.Write(itemToProcess, Level.Info, string.Format("Replaced '{0}' with '{1}'", findPattern, replaceReportingText), baseMap.NewItemField, "Cleanup"); } else { bool occuruncesFound = itemToProcess.Fields[baseMap.NewItemField].Value.Contains(findPattern); itemToProcess.Fields[baseMap.NewItemField].Value = content.Replace(findPattern, replacePattern); if (occuruncesFound) { ImportReporter.Write(itemToProcess, Level.Info, string.Format("Replaced '{0}' with '{1}'", findPattern, replaceReportingText), baseMap.NewItemField, "Cleanup"); } } itemToProcess.Editing.EndEdit(); } } catch (Exception ex) { ImportReporter.Write(itemToProcess, Level.Info, string.Format("Replace failed on '{0}' with '{1}'", findPattern, replaceReportingText), baseMap.NewItemField, "Cleanup"); } }
public static void Run(Item itemToProcess, Item fieldMapping) { MultilistField WarningTags = fieldMapping.Fields["Warning Trigger Tags"]; ItemReport itemReport; if (!ImportReporter.ItemReports.ContainsKey(itemToProcess.Paths.Path)) { ImportReporter.ItemReports.Add(itemToProcess.Paths.Path, new ItemReport()); } ImportReporter.ItemReports.TryGetValue(itemToProcess.Paths.Path, out itemReport); if (string.IsNullOrEmpty(itemReport.ItemName)) { itemReport.ItemName = itemToProcess.Name; } if (string.IsNullOrEmpty(itemReport.NewItemPath)) { itemReport.NewItemPath = itemToProcess.Paths.Path; } BaseMapping baseMap = new BaseMapping(fieldMapping); List <string> tagsToCheck = new List <string>(); HtmlDocument document = new HtmlDocument(); string content = itemToProcess.Fields[baseMap.NewItemField].Value; document.LoadHtml(content); string findPattern; HtmlNode node; foreach (var id in WarningTags.TargetIDs) { findPattern = itemToProcess.Database.GetItem(id).Fields["Identifier"].Value; node = Helper.HandleNodesLookup(findPattern, document); if (node == null || node.ChildNodes == null || !node.ChildNodes.Any()) { continue; } tagsToCheck.Add(findPattern); } if (!tagsToCheck.Any()) { return; } string fieldName = fieldMapping.Fields["To What Field"].Value; string messageText = string.Join("/", tagsToCheck.ToArray()) + " warning tags were found and requires additional review"; ImportReporter.Write(itemToProcess, Level.Warning, messageText, fieldName, "Warning Trigger Tags"); }
public SitecoreDataMap(Database db, Item importItem, LevelLogger logger) : base(db, importItem, logger) { //deal with sitecore properties if any Item Props = GetItemByTemplate(importItem, Utility.Constants.PropertiesFolderID); if (Props.IsNotNull()) { ChildList c = Props.GetChildren(); if (c.Any()) { foreach (Item child in c) { //create an item to get the class / assembly name from BaseMapping bm = new BaseMapping(child); if (!string.IsNullOrEmpty(bm.HandlerAssembly)) { if (!string.IsNullOrEmpty(bm.HandlerClass)) { //create the object from the class and cast as base field to add it to field definitions IBaseProperty bp = null; try { bp = (IBaseProperty)Sitecore.Reflection.ReflectionUtil.CreateObject(bm.HandlerAssembly, bm.HandlerClass, new object[] { child }); } catch (FileNotFoundException fnfe) { Logger.AddError("Error", string.Format("the property:{0} binary {1} specified could not be found", child.Name, bm.HandlerAssembly)); } if (bp != null) { PropertyDefinitions.Add(bp); } else { Logger.AddError("Error", string.Format("the property: '{0}' class type {1} could not be instantiated", child.Name, bm.HandlerClass)); } } else { Logger.AddError("Error", string.Format("the property: '{0}' Handler Class {1} is not defined", child.Name, bm.HandlerClass)); } } else { Logger.AddError("Error", string.Format("the property: '{0}' Handler Assembly {1} is not defined", child.Name, bm.HandlerAssembly)); } } } else { Logger.AddError("Warn", "there are no properties to import"); } } }
protected virtual List <IBaseField> GetFieldDefinitions(Item i) { List <IBaseField> l = new List <IBaseField>(); //check for fields folder Item Fields = i.GetChildByTemplate(FieldsFolderTemplateID); if (Fields.IsNull()) { Logger.Log(i.Paths.FullPath, "there is no 'Fields' folder on the import item", ProcessStatus.ImportDefinitionError); return(l); } //check for any children if (!Fields.HasChildren) { Logger.Log(i.Paths.FullPath, "there are no fields to import on on the import item", ProcessStatus.ImportDefinitionError); return(l); } ChildList c = Fields.GetChildren(); foreach (Item child in c) { if (child.TemplateID == new ID("{F9FDB469-FC36-4A48-AB45-1B4832AA350E}")) { var fieldFolder = ((LookupField)child.Fields["Fields"]).TargetItem; foreach (Item sharedChild in fieldFolder.GetChildren()) { //create an item to get the class / assembly name from BaseMapping bm = new BaseMapping(child); var field = GenerateType <IBaseField>(sharedChild, bm.HandlerClass, bm.HandlerAssembly, new object[] { child, Logger }); if (field != null) { l.Add(field); } } } else { BaseMapping bm = new BaseMapping(child); var field = GenerateType <IBaseField>(child, bm.HandlerClass, bm.HandlerAssembly, new object[] { child, Logger }); if (field != null) { l.Add(field); } } } return(l.Where(x => x != null).ToList()); }
private NameValueCollection GetMappings() { NameValueCollection mappings = new NameValueCollection(); foreach (IBaseField field in FieldDefinitions) { BaseMapping baseMap = new BaseMapping(field.InnerItem); string fromFieldName = baseMap.InnerItem.Fields[DataImporter.HtmlScraper.Constants.FieldNames.FromWhatField].Value; string toFieldName = baseMap.NewItemField + "_" + Guid.NewGuid().ToString().Replace("-", ""); mappings.Add(fromFieldName, toFieldName); } return(mappings); }
public void ComputeX_ShouldReturnCorrectXValues() { var s = new bool[] { true, true, false }; var r = new bool[] { true, true, true }; var t = new bool[] { false, true, true }; var xs = BaseMapping.ComputeX(s[0], s[1], s[2]); var xr = BaseMapping.ComputeX(r[0], r[1], r[2]); var xt = BaseMapping.ComputeX(t[0], t[1], t[2]); Assert.AreEqual(X.S, xs); Assert.AreEqual(X.R, xr); Assert.AreEqual(X.T, xt); }
// 为Mongo 提供 MongoConfiguration public MongoConfiguration InitMongoBuilder(string ConnString) { var config = new MongoConfigurationBuilder(); //加入连接字符串 config.ConnectionString(ConnString); //映射公共类 BaseMapping mapping = new BaseMapping(); //向映射公共类注册自己定义映射 mapping.AddMapping(new MyMapping().Mapping); //传入公共类的执行方法 config.Mapping(mapping.ForeachMapping); return(config.BuildConfiguration()); }
public void ComputeY_ShouldReturnCorrectYValues() { var input = new int[] { 2, 3, 4 }; var actualYs = BaseMapping.ComputeY(X.S, input[0], input[1], input[2]); var actualYr = BaseMapping.ComputeY(X.R, input[0], input[1], input[2]); var actualYt = BaseMapping.ComputeY(X.T, input[0], input[1], input[2]); var expectedYs = 2 + ((double)2 * 3 / 100); var expectedYr = 2 + ((double)2 * (3 - 4) / 100); var expectedYt = 2 - ((double)2 * 4 / 100); Assert.AreEqual(expectedYs, actualYs); Assert.AreEqual(expectedYr, actualYr); Assert.AreEqual(expectedYt, actualYt); }
public void ComputeY_ShouldReturnCorrectYValues() { // X = S => Y = F + D + (D * E / 100) var actualYs = Specialized2.ComputeY(X.S, 2, 3, 4); // (X = R || X = T) => BaseMapping.ComputeY(); var actualYr = Specialized2.ComputeY(X.R, 2, 3, 4); var actualYt = Specialized2.ComputeY(X.T, 2, 3, 4); // expectedYs = 4 + 2 + (2*3/100) = 6 + (.06) = 6.06 var expectedYs = 6.06; var expectedYr = BaseMapping.ComputeY(X.R, 2, 3, 4); var expectedYt = BaseMapping.ComputeY(X.T, 2, 3, 4); Assert.AreEqual(expectedYr, actualYr); Assert.AreEqual(expectedYs, actualYs); Assert.AreEqual(expectedYt, actualYt); }
/// <summary> /// Searches the node hierarchy for a specified search term and places the result in the nodes parameter. /// </summary> /// <param name="searchTerm">The mapping to search for.</param> /// <param name="nodes">This collection is returned with the matching nodes.</param> /// <returns>List of nodes matching the search criteria.</returns> public override List <Component> FindMany(BaseMapping searchTerm, List <Component> nodes) { if (!string.IsNullOrEmpty(searchTerm.RegexPattern)) { if (Regex.Match(Name, searchTerm.RegexPattern).Success) { nodes.Add(this); } } else { if (searchTerm.OpenEhrFieldPath == Name) { nodes.Add(this); } } return(nodes); }
public void Run(Item processor, Item itemToProcess, Item fieldMapping) { BaseMapping baseMap = new BaseMapping(fieldMapping); try { using (new SecurityModel.SecurityDisabler()) { itemToProcess.Editing.BeginEdit(); itemToProcess.Fields[baseMap.NewItemField].Value = itemToProcess.Fields[baseMap.NewItemField].Value.Trim(); itemToProcess.Editing.EndEdit(); } ImportReporter.Write(itemToProcess, Level.Info, "", baseMap.NewItemField, "Trim Value"); } catch (Exception ex) { ImportReporter.Write(itemToProcess, Level.Error, ex.ToString(), baseMap.NewItemField, "Trim Value Field"); } }
private IBaseField GenerateFieldMapping(Item child) { //create an item to get the class / assembly name from BaseMapping bm = new BaseMapping(child); //check for assembly if (string.IsNullOrEmpty(bm.HandlerAssembly)) { Logger.Log("BaseDataMap.GenerateFieldMapping", string.Format("the field's Handler Assembly is not defined on item {0}: {1}", child.Paths.FullPath, bm.HandlerAssembly)); return(null); } //check for class if (string.IsNullOrEmpty(bm.HandlerClass)) { Logger.Log("BaseDataMap.GenerateFieldMapping", string.Format("the field's Handler Class is not defined on item {0}: {1}", child.Paths.FullPath, bm.HandlerClass)); return(null); } //create the object from the class and cast as base field to add it to field definitions IBaseField bf = null; try { bf = (IBaseField)Sitecore.Reflection.ReflectionUtil.CreateObject(bm.HandlerAssembly, bm.HandlerClass, new object[] { child, Logger }); } catch (FileNotFoundException) { Logger.Log("BaseDataMap.GenerateFieldMapping", string.Format("the field's binary specified could not be found on item {0} : {1}", child.Paths.FullPath, bm.HandlerAssembly)); } if (bf != null) { return(bf); } else { Logger.Log("BaseDataMap.GenerateFieldMapping", string.Format("the field's class type could not be instantiated {0} :{1}", child.Paths.FullPath, bm.HandlerClass)); } return(null); }
protected virtual List <IBaseFieldWithReference> GetReferenceFieldDefinitions(Item i) { List <IBaseFieldWithReference> l = new List <IBaseFieldWithReference>(); //check for fields folder Item Fields = i.GetChildByTemplate(ReferenceFieldsFolderTemplateID); if (Fields.IsNull()) { Logger.Log("BaseDataMap.GetReferenceFieldDefinitions", string.Format("there is no 'Reference Fields' folder on the import item {0}", i.Paths.FullPath)); return(l); } //check for any children if (!Fields.HasChildren) { Logger.Log("BaseDataMap.GetReferenceFieldDefinitions", string.Format("there are no reference fields to import on on the import item {0}", ImportItem.Paths.FullPath)); return(l); } ChildList c = Fields.GetChildren(); foreach (Item child in c) { //create an item to get the class / assembly name from BaseMapping bm = new BaseMapping(child); var fieldRef = GenerateType <IBaseFieldWithReference>(child, bm.HandlerClass, bm.HandlerAssembly, new object[] { child }); if (fieldRef != null) { l.Add(fieldRef); } } return(l); }
public abstract List <Component> FindMany(BaseMapping searchTerm, List <Component> nodes);
public MappingRegistry Register(BaseMapping baseMapping) { mappings.Add(baseMapping); return(this); }
protected List <IBaseProperty> GetPropDefinitions(Item i) { List <IBaseProperty> l = new List <IBaseProperty>(); //check for properties folder Item Props = i.GetChildByTemplate(PropertiesFolderTemplateID); if (Props.IsNull()) { Logger.Log("Warn", string.Format("there is no 'Properties' folder on '{0}'", i.DisplayName)); return(l); } //check for any children if (!Props.HasChildren) { Logger.Log("Warn", string.Format("there are no properties to import on '{0}'", i.DisplayName)); return(l); } ChildList c = Props.GetChildren(); foreach (Item child in c) { //create an item to get the class / assembly name from BaseMapping bm = new BaseMapping(child); //check for assembly if (string.IsNullOrEmpty(bm.HandlerAssembly)) { Logger.Log(child.Paths.FullPath, "the 'Handler Assembly' is not defined", ProcessStatus.ImportDefinitionError, "Handler Assembly", bm.HandlerAssembly); continue; } //check for class if (string.IsNullOrEmpty(bm.HandlerClass)) { Logger.Log(child.Paths.FullPath, "the Handler Class is not defined", ProcessStatus.ImportDefinitionError, "Handler Class", bm.HandlerClass); continue; } //create the object from the class and cast as base field to add it to field definitions IBaseProperty bp = null; try { bp = (IBaseProperty)Sitecore.Reflection.ReflectionUtil.CreateObject(bm.HandlerAssembly, bm.HandlerClass, new object[] { child }); } catch (FileNotFoundException fnfe) { Logger.Log(child.Paths.FullPath, "the binary could not be found", ProcessStatus.ImportDefinitionError, "Handler Assembly", bm.HandlerAssembly); } if (bp != null) { l.Add(bp); } else { Logger.Log(child.Paths.FullPath, "the class type could not be instantiated", ProcessStatus.ImportDefinitionError, "Handler Class", bm.HandlerClass); } } return(l); }
public BaseDataMap(Database db, string connectionString, Item importItem, string lastUpdated = "") { Overwrite = importItem.Fields["Overwrite Item"] != null && ((CheckboxField)importItem.Fields["Overwrite Item"]).Checked; SkipExistingItems = importItem.Fields["Skip Existing Items"] != null && ((CheckboxField)importItem.Fields["Skip Existing Items"]).Checked; SearchIndex = importItem.Fields["Search Index"] != null ? importItem.Fields["Search Index"].Value : ""; DeltasOnly = importItem.Fields["Deltas Only"] != null && ((CheckboxField)importItem.Fields["Deltas Only"]).Checked; LastUpdatedFieldName = importItem.Fields["Last Updated Field Name"] != null ? importItem.Fields["Last Updated Field Name"].Value : ""; LastUpdated = string.IsNullOrEmpty(lastUpdated) ? DateTime.Now.AddDays(-30) : DateTime.Parse(lastUpdated); MissingItemsQuery = importItem.Fields["Missing Items Query"] != null ? importItem.Fields["Missing Items Query"].Value : ""; HistorySnapshotQuery = importItem.Fields["History Snapshot Query"] != null ? importItem.Fields["History Snapshot Query"].Value : ""; //instantiate log log = new StringBuilder(); //setup import details SitecoreDB = db; DatabaseConnectionString = connectionString; //get query Query = importItem.Fields["Query"].Value; if (string.IsNullOrEmpty(Query)) { Log("Error", "the 'Query' field was not set"); } //get parent and store it var parentID = importItem.Fields["Import To Where"].Value; if (!string.IsNullOrEmpty(parentID)) { var parent = SitecoreDB.Items[parentID]; if (parent.IsNotNull()) { Parent = parent; } else { Log("Error", "the 'To Where' item is null"); } } else { Log("Error", "the 'To Where' field is not set"); } //get new item template var templateID = importItem.Fields["Import To What Template"].Value; if (!string.IsNullOrEmpty(templateID)) { var templateItem = SitecoreDB.Items[templateID]; if (templateItem.IsNotNull()) { if ((BranchItem)templateItem != null) { NewItemTemplate = (BranchItem)templateItem; } else { NewItemTemplate = (TemplateItem)templateItem; } } else { Log("Error", "the 'To What Template' item is null"); } } else { Log("Error", "the 'To What Template' field is not set"); } //more properties ItemNameDataField = importItem.Fields["Pull Item Name from What Fields"].Value; ItemNameMaxLength = int.Parse(importItem.Fields["Item Name Max Length"].Value); var iLang = SitecoreDB.GetItem(importItem.Fields["Import To Language"].Value); ImportToLanguage = LanguageManager.GetLanguage(iLang.Name); if (ImportToLanguage == null) { Log("Error", "The 'Import Language' field is not set"); } //foldering information FolderByDate = ((CheckboxField)importItem.Fields["Folder By Date"]).Checked; FolderByName = ((CheckboxField)importItem.Fields["Folder By Name"]).Checked; DateField = importItem.Fields["Date Field"].Value; if (FolderByName || FolderByDate) { //setup a default type to an ordinary folder var FolderItem = SitecoreDB.Templates["{A87A00B1-E6DB-45AB-8B54-636FEC3B5523}"]; //if they specify a type then use that var folderID = importItem.Fields["Folder Template"].Value; if (!string.IsNullOrEmpty(folderID)) { FolderItem = SitecoreDB.Templates[folderID]; } FolderTemplate = FolderItem; } //start handling fields var Fields = GetItemByTemplate(importItem, FieldsFolderID); if (Fields.IsNotNull()) { var c = Fields.GetChildren(); if (c.Any()) { foreach (Item child in c) { //create an item to get the class / assembly name from var bm = new BaseMapping(child); if (!string.IsNullOrEmpty(bm.HandlerAssembly)) { if (!string.IsNullOrEmpty(bm.HandlerClass)) { //create the object from the class and cast as base field to add it to field definitions IBaseField bf = null; try { bf = (IBaseField) ReflectionUtil.CreateObject(bm.HandlerAssembly, bm.HandlerClass, new object[] { child }); } catch (FileNotFoundException fnfe) { Log("Error", string.Format("the field:{0} binary {1} specified could not be found", child.Name, bm.HandlerAssembly)); } if (bf != null) { FieldDefinitions.Add(bf); } else { Log("Error", string.Format("the field: '{0}' class type {1} could not be instantiated", child.Name, bm.HandlerClass)); } } else { Log("Error", string.Format("the field: '{0}' Handler Class {1} is not defined", child.Name, bm.HandlerClass)); } } else { Log("Error", string.Format("the field: '{0}' Handler Assembly {1} is not defined", child.Name, bm.HandlerAssembly)); } } } else { Log("Warn", "there are no fields to import"); } } else { Log("Warn", "there is no 'Fields' folder"); } }
public SingleMapping(BaseMapping mapping, BaseTransformation[] transformations, MergeType mergeType = MergeType.FAVOUR_INPUT) { this.mapping = mapping; this.mergeType = mergeType; this.transformations = transformations; }
public SitecoreDataMap(Database db, string connectionString, Item importItem) : base(db, connectionString, importItem) { Item fLang = SitecoreDB.GetItem(importItem.Fields["Import From Language"].Value); ImportFromLanguage = LanguageManager.GetLanguage(fLang.Name); CheckboxField cf = importItem.Fields["Recursively Fetch Children"]; RecursivelyFetchChildren = cf.Checked; //deal with sitecore properties if any Item Props = GetItemByTemplate(importItem, PropertiesFolderID); if (Props.IsNotNull()) { ChildList c = Props.GetChildren(); if (c.Any()) { foreach (Item child in c) { //create an item to get the class / assembly name from BaseMapping bm = new BaseMapping(child); if (!string.IsNullOrEmpty(bm.HandlerAssembly)) { if (!string.IsNullOrEmpty(bm.HandlerClass)) { //create the object from the class and cast as base field to add it to field definitions IBaseProperty bp = null; try { bp = (IBaseProperty)Sitecore.Reflection.ReflectionUtil.CreateObject(bm.HandlerAssembly, bm.HandlerClass, new object[] { child }); } catch (FileNotFoundException fnfe) { Log("Error", string.Format("the property:{0} binary {1} specified could not be found", child.Name, bm.HandlerAssembly)); } if (bp != null) { PropertyDefinitions.Add(bp); } else { Log("Error", string.Format("the property: '{0}' class type {1} could not be instantiated", child.Name, bm.HandlerClass)); } } else { Log("Error", string.Format("the property: '{0}' Handler Class {1} is not defined", child.Name, bm.HandlerClass)); } } else { Log("Error", string.Format("the property: '{0}' Handler Assembly {1} is not defined", child.Name, bm.HandlerAssembly)); } } } else { Log("Warn", "there are no properties to import"); } } Item Temps = GetItemByTemplate(importItem, TemplatesFolderID); if (Temps.IsNotNull()) { ChildList c = Temps.GetChildren(); if (c.Any()) { foreach (Item child in c) { //create an item to get the class / assembly name from TemplateMapping tm = new TemplateMapping(child); if (string.IsNullOrEmpty(tm.FromWhatTemplate)) { Log("Error", string.Format("the template mapping field 'FromWhatTemplate' on '{0}' is not defined", child.Name)); break; } if (string.IsNullOrEmpty(tm.ToWhatTemplate)) { Log("Error", string.Format("the template mapping field 'ToWhatTemplate' on '{0}' is not defined", child.Name)); break; } TemplateMappingDefinitions.Add(tm.FromWhatTemplate, tm); } } } }
public BaseDataMap(Database db, string connectionString, Item importItem) { //instantiate log log = new StringBuilder(); //setup import details SitecoreDB = db; DatabaseConnectionString = connectionString; //get query Query = importItem.Fields["Query"].Value; if (string.IsNullOrEmpty(Query)) { Log("Error", "the 'Query' field was not set"); } //get parent and store it string parentID = importItem.Fields["Import To Where"].Value; if (!string.IsNullOrEmpty(parentID)) { Item parent = SitecoreDB.Items[parentID]; if (parent.IsNotNull()) { Parent = parent; } else { Log("Error", "the 'To Where' item is null"); } } else { Log("Error", "the 'To Where' field is not set"); } //get new item template string templateID = importItem.Fields["Import To What Template"].Value; if (!string.IsNullOrEmpty(templateID)) { Item templateItem = SitecoreDB.Items[templateID]; if (templateItem.IsNotNull()) { NewItemTemplate = templateItem; } else { Log("Error", "the 'To What Template' item is null"); } } else { Log("Error", "the 'To What Template' field is not set"); } //more properties ItemNameDataField = importItem.Fields["Pull Item Name from What Fields"].Value; ItemNameMaxLength = int.Parse(importItem.Fields["Item Name Max Length"].Value); //foldering information FolderByDate = ((CheckboxField)importItem.Fields["Folder By Date"]).Checked; FolderByName = ((CheckboxField)importItem.Fields["Folder By Name"]).Checked; DateField = importItem.Fields["Date Field"].Value; if (FolderByName || FolderByDate) { //setup a default type to an ordinary folder Sitecore.Data.Items.TemplateItem FolderItem = SitecoreDB.Templates["{A87A00B1-E6DB-45AB-8B54-636FEC3B5523}"]; //if they specify a type then use that string folderID = importItem.Fields["Folder Template"].Value; if (!string.IsNullOrEmpty(folderID)) { FolderItem = SitecoreDB.Templates[folderID]; } FolderTemplate = FolderItem; } //start handling fields Item Fields = GetItemByTemplate(importItem, FieldsFolderID); if (Fields.IsNotNull()) { ChildList c = Fields.GetChildren(); if (c.Any()) { foreach (Item child in c) { //create an item to get the class / assembly name from BaseMapping bm = new BaseMapping(child); if (!string.IsNullOrEmpty(bm.HandlerAssembly)) { if (!string.IsNullOrEmpty(bm.HandlerClass)) { //create the object from the class and cast as base field to add it to field definitions IBaseField bf = null; try { bf = (IBaseField)Sitecore.Reflection.ReflectionUtil.CreateObject(bm.HandlerAssembly, bm.HandlerClass, new object[] { child }); } catch (FileNotFoundException fnfe) { Log("Error", string.Format("the field:{0} binary {1} specified could not be found", child.Name, bm.HandlerAssembly)); } if (bf != null) { FieldDefinitions.Add(bf); } else { Log("Error", string.Format("the field: '{0}' class type {1} could not be instantiated", child.Name, bm.HandlerClass)); } } else { Log("Error", string.Format("the field: '{0}' Handler Class {1} is not defined", child.Name, bm.HandlerClass)); } } else { Log("Error", string.Format("the field: '{0}' Handler Assembly {1} is not defined", child.Name, bm.HandlerAssembly)); } } } else { Log("Warn", "there are no fields to import"); } } else { Log("Warn", "there is no 'Fields' folder"); } }
public void Run(Item processor, Item itemToProcess, Item fieldMapping) { ImportConfig config = new ImportConfig(fieldMapping.Parent.Parent, fieldMapping.Database, ""); Uri baseUri = new Uri(config.BaseUrl); BaseMapping baseMap = new BaseMapping(fieldMapping); MediaProcessor mediaProcessor = new MediaProcessor(processor); HtmlDocument document = new HtmlDocument(); string content = itemToProcess.Fields[baseMap.NewItemField].Value; document.LoadHtml(content); using (new SecurityModel.SecurityDisabler()) { foreach (var mediaType in mediaProcessor.MediaTypes) { var nodes = document.DocumentNode.SelectNodes(string.Format("//{0}/@{1}", mediaType.Identifier, mediaType.Attribute)); if (nodes == null) { continue; } //select nodes in html where path ends with extension listed in config List <HtmlNode> targetedNodes = nodes.Where(n => n.Attributes[mediaType.Attribute].Value.Trim().ToLower() .EndsWith(mediaType.Extension.Trim().ToLower())).ToList(); if (targetedNodes == null) { targetedNodes = nodes.Where(n => n.Attributes[mediaType.Attribute].Value.Trim().ToLower() .Contains(mediaType.Extension.Trim().ToLower())).ToList(); } else { targetedNodes.AddRange(nodes.Where(n => n.Attributes[mediaType.Attribute].Value.Trim().ToLower() .Contains(mediaType.Extension.Trim().ToLower())).ToList()); } foreach (var child in targetedNodes) { try { //Make sure the selected tags have media items to import, with existing parameters to follow string source = child.Attributes[mediaType.Attribute].Value; string mediaExtension = Path.GetExtension(source); if (string.IsNullOrEmpty(source)) { continue; } Uri mediaSource = new Uri(source, UriKind.RelativeOrAbsolute); if (mediaSource.IsAbsoluteUri) { if ((mediaSource.Host != baseUri.Host)) { continue; } } else { //This is for internal/relative path images mediaSource = new Uri(baseUri, source); } string destination = mediaProcessor.RetrieveDestination(processor, mediaProcessor.RootDestination, source, mediaSource, baseUri); Item importedMediaItem = MediaUpload.UploadMedia(mediaSource.ToString(), destination, itemToProcess); if (importedMediaItem != null) { var mediaUrl = "-/media/" + importedMediaItem.ID.ToShortID().ToString() + ".ashx"; //Swap the old link with the new link to our media library HtmlNode newChild = child.Clone(); newChild.Attributes[mediaType.Attribute].Value = mediaUrl; content = content.Replace(child.OuterHtml, newChild.OuterHtml); itemToProcess.Editing.BeginEdit(); itemToProcess.Fields[baseMap.NewItemField].Value = content; itemToProcess.Editing.EndEdit(); ImportReporter.Write(itemToProcess, Level.Info, string.Format("Link updated for: {0}", importedMediaItem.Name), baseMap.NewItemField, "Media Importer"); } } catch (Exception ex) { ImportReporter.Write(itemToProcess, Level.Error, string.Format("There was an error importing media from {0}. Error: {1}.", string.Concat(baseUri, child.Attributes[mediaType.Attribute].Value), ex.Message), baseMap.NewItemField, "Media Import"); //Error importing media and/or updating links to media } } } } }
protected virtual List <IBaseFieldWithReference> GetReferenceFieldDefinitions(Item i) { List <IBaseFieldWithReference> l = new List <IBaseFieldWithReference>(); //check for fields folder Item Fields = i.GetChildByTemplate(ReferenceFieldsFolderTemplateID); if (Fields.IsNull()) { Logger.Log("BaseDataMap.GetReferenceFieldDefinitions", string.Format("there is no 'Reference Fields' folder on the import item {0}", i.Paths.FullPath)); return(l); } //check for any children if (!Fields.HasChildren) { Logger.Log("BaseDataMap.GetReferenceFieldDefinitions", string.Format("there are no reference fields to import on on the import item {0}", ImportItem.Paths.FullPath)); return(l); } ChildList c = Fields.GetChildren(); foreach (Item child in c) { //create an item to get the class / assembly name from BaseMapping bm = new BaseMapping(child); //check for assembly if (string.IsNullOrEmpty(bm.HandlerAssembly)) { Logger.Log(child.Paths.FullPath, "the field's Handler Assembly is not defined", ProcessStatus.ImportDefinitionError, child.Name, bm.HandlerAssembly); continue; } //check for class if (string.IsNullOrEmpty(bm.HandlerClass)) { Logger.Log(child.Paths.FullPath, "the field's Handler Class is not defined", ProcessStatus.ImportDefinitionError, child.Name, bm.HandlerClass); continue; } //create the object from the class and cast as base field to add it to field definitions IBaseFieldWithReference bf = null; try { bf = (IBaseFieldWithReference)Sitecore.Reflection.ReflectionUtil.CreateObject(bm.HandlerAssembly, bm.HandlerClass, new object[] { child }); } catch (FileNotFoundException fnfe) { Logger.Log(child.Paths.FullPath, "the field's binary specified could not be found", ProcessStatus.ImportDefinitionError, child.Name, bm.HandlerAssembly); } if (bf != null) { l.Add(bf); } else { Logger.Log(child.Paths.FullPath, "the field's class type could not be instantiated", ProcessStatus.ImportDefinitionError, child.Name, bm.HandlerClass); } } return(l); }