public override void FillField(BaseDataMap map, object importRow, ref Item newItem, string importValue, out bool updatedField, ref LevelLogger logger)
 {
     var fillFieldLogger = logger.CreateLevelLogger();
     updatedField = false;
     if (IsRequired)
     {
         if (String.IsNullOrEmpty(importValue))
         {
             fillFieldLogger.AddError(CategoryConstants.ImportedValueToFieldWasEmpty, String.Format("The Item '{0}' of template type: '{1}' has a field '{2}', but the imported value '{3}' was empty. This field must be provided when the field is required. The field was not updated.", map.GetItemDebugInfo(newItem), newItem.TemplateName, NewItemField, importValue));
             return;
         }
     }
     //get the field as a link field and store the url
     LinkField lf = newItem.Fields[NewItemField];
     if (lf != null)
     {
         if (lf.Url != importValue)
         {
             lf.Url = importValue;
             updatedField = true;
         }
     }
     if(IsRequired && lf==null)
     {
         fillFieldLogger.AddError(CategoryConstants.RequiredFieldNotFoundOnItem, String.Format("The Item '{0}' of template type: '{1}' didn't contain a field with name '{2}'. This field must be present because the 'Is Required Field' is checked.", newItem.ID.ToString(), newItem.TemplateName, NewItemField));
         return;
     }
 }
 /// <summary>
 /// gets custom data from a DataRow
 /// </summary>
 /// <param name="importRow"></param>
 /// <param name="fieldName"></param>
 /// <returns></returns>
 public override string GetFieldValue(object importRow, string fieldName, ref LevelLogger logger)
 {
     var getFieldLogger = logger.CreateLevelLogger();
     try
     {
         DataRow dataRow = importRow as DataRow;
         if (dataRow != null)
         {
             if (!String.IsNullOrEmpty(fieldName))
             {
                 object fieldValue = dataRow[fieldName];
                 return (fieldValue != null) ? fieldValue.ToString() : String.Empty;
             }
             else
             {
                 getFieldLogger.AddError(CategoryConstants.TheFieldnameArgumentWasNullOrEmpty, String.Format("The GetFieldValue method failed because the the 'fieldName' was null or empty. ImportRow: {0}.", GetImportRowDebugInfo(importRow)));
             }
         }
         else
         {
             getFieldLogger.AddError(CategoryConstants.TheImportRowWasNull, String.Format("The GetFieldValue method failed because the Import Row was null. FieldName: {0}.", fieldName));
         }
     }
     catch (Exception ex)
     {
         getFieldLogger.AddError(CategoryConstants.GetFieldValueFailed, String.Format("The GetFieldValue method failed with an exception. ImportRow: {0}. FieldName: {1}. Exception: {2}.", GetImportRowDebugInfo(importRow), fieldName, ex));
     }
     return String.Empty;
 }
Exemplo n.º 3
0
        public virtual LevelLogger CreateLevelLogger()
        {
            var levelLogger = new LevelLogger(Logger);

            AddChild(levelLogger);
            return(levelLogger);
        }
        public static OutputHandlerBase CreateOutputHandler(Item dataSyncItem, LevelLogger logger)
        {
            string outHandlerAssembly = dataSyncItem[FieldNameOutputHandlerAssembly];
            string outputHandlerClass = dataSyncItem[FieldNameOutputHandlerClass];

            if (!String.IsNullOrEmpty(outHandlerAssembly))
            {
                if (!String.IsNullOrEmpty(outputHandlerClass))
                {
                    OutputHandlerBase outputHandler = null;
                    try
                    {
                        outputHandler = (OutputHandlerBase)Reflection.ReflectionUtil.CreateObject(outHandlerAssembly, outputHandlerClass, new object[] { logger });
                    }
                    catch (FileNotFoundException fnfe)
                    {
                        throw new Exception("The binary specified could not be found" + fnfe.Message, fnfe);
                    }
                    if (outputHandler != null)
                    {
                        return outputHandler;
                    }
                    throw new Exception(String.Format("The OutputHandler provided could not be instantiated. Assembly:'{0}' Class:'{1}'", outHandlerAssembly, outputHandlerClass));
                }
                else
                {
                    throw new Exception(String.Format("OutputHandler class is not defined"));
                }
            }
            else
            {
                throw new Exception("OutputHandler assembly is not defined");
            }
            return null;
        }
Exemplo n.º 5
0
        public override LevelLogger CreateLevelLogger()
        {
            var levelLogger = new LevelLogger(this);

            AddChild(levelLogger);
            return(levelLogger);
        }
Exemplo n.º 6
0
 public override void FillField(BaseDataMap map, object importRow, ref Item newItem, string importValue, out bool updatedField, ref LevelLogger logger)
 {
     var fillFieldLogger = logger.CreateLevelLogger();
     updatedField = false;
     if (IsRequired)
     {
         if (String.IsNullOrEmpty(importValue))
         {
             fillFieldLogger.AddError(CategoryConstants.ImportedValueToFieldWasEmpty, String.Format("The Item '{0}' of template type: '{1}', field '{2}', but the imported value '{3}' was empty. This field must be provided when the field is required. The field was not updated.", map.GetItemDebugInfo(newItem), newItem.TemplateName, NewItemField, importValue));
             return;
         }
     }
     Field field = newItem.Fields[NewItemField];
     if (field != null)
     {
         //try to parse date value
         DateTime date;
         if (!DateTime.TryParse(importValue, out date))
         {
             fillFieldLogger.AddError(TheDatetimeParsingFailed, String.Format("The DateTime parsing failed. Therefor the field was not updated on item '{0}' of template type: '{1}' in field the date value could not be parsed '{2}'. The date parse string was: {3}.", map.GetItemDebugInfo(newItem), newItem.TemplateName, NewItemField, importValue));
             return;
         }
         string value = date.ToDateFieldValue();
         if (value != field.Value)
         {
             field.Value = value;
             updatedField = true;
         }
     }
     if (IsRequired && field == null)
     {
         fillFieldLogger.AddError(CategoryConstants.RequiredFieldNotFoundOnItem, String.Format("The Item '{0}' of template type: '{1}' didn't contain a field with name '{2}'. This field must be present because the 'Is Required Field' is checked.", map.GetItemDebugInfo(newItem), newItem.TemplateName, NewItemField));
         return;
     }
 }
Exemplo n.º 7
0
 protected void AddChild(LevelLogger child)
 {
     if (Children != null && child != null)
     {
         Children.Add(child);
         child.AddedLogLine += ChildAddedLogLine;
     }
 }
 public SqlDataMap(Database db, Item importItem, LevelLogger logger)
     : base(db, importItem, logger)
 {
     if (string.IsNullOrEmpty(Query))
     {
         Logger.AddError("Error", "the 'Query' field was not set");
     }
 }
 public CSVDataMap(Database db, Item importItem, LevelLogger logger, string data)
     : base(db, importItem, logger)
 {
     Data = data;
     HeaderColumns = new Dictionary<string, int>();
     ImportData = new List<object>();
     InitializeColumnDelimiterCharacter(importItem);
 }
 public override void FillField(Providers.BaseDataMap map, object importRow, ref Item newItem, string importValue, out bool updatedField, ref LevelLogger logger)
 {
     var xml = string.Empty;
     if (!String.IsNullOrEmpty(importValue))
     {
         xml = String.Format(SitecoreExternalLinkXml, importValue);
     }
     base.FillField(map, importRow, ref newItem, xml, out updatedField, ref logger);
 }
        public static void SendLogReport(ref LevelLogger logger, OutputHandlerBase exporter)
        {
            var dataSyncItem = logger.GetData(Utility.Constants.DataSyncItem) as Item;
            if (dataSyncItem == null)
            {
                logger.AddError("Error", "The DataSyncItem was null. Therefor we couldn't retrieve any mail recipients.");
                return;
            }
            if (exporter == null)
            {
                logger.AddError("Error", "The ExporterBase was null. This class is used to output the logger.");
                return;
            }
            var recipient = dataSyncItem[FieldNameMailRecipients];
            if (String.IsNullOrEmpty(recipient))
            {
                logger.AddInfo("Add Mail Recipients to receive email reports", "If you want to receive email, then fill out the field 'Mail Recipients'.");
            }
            else
            {
                var replyTo = dataSyncItem[FieldNameMailReplyTo];
                if (String.IsNullOrEmpty(replyTo))
                {
                    replyTo = DefaultReplyTo;
                    logger.AddError("Error", "The 'Mail Reply To' field must be defined. Please provide a replyTo address for the mail.");
                }
                var subject = dataSyncItem[FieldNameMailSubject];
                if (String.IsNullOrEmpty(subject))
                {
                    subject = DefaultSubject;
                }

                var result = !logger.HasFatalsOrErrors() ? Success : Failure;
                try
                {
                    subject = String.Format(subject, exporter.GetIdentifier(), result);
                }
                catch (Exception exception)
                {
                    logger.AddError("Error", "SendLogReport had an exception trying to format the subject of the mail." + exception.Message);
                }
                var doNotSendMailOnSuccess = dataSyncItem[FieldNameDoNotSendMailOnSuccess] == SitecoreBooleanTrue;
                if((doNotSendMailOnSuccess && result == Failure) || !doNotSendMailOnSuccess)
                {
                    try{
                        if (SendMail.SendMailWithoutAttachment(recipient, replyTo, subject, exporter.Export()) == Failure)
                        {
                            logger.AddError("Error", "The SendMailWithoutAttachment failed.");
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.AddError("Error", "The SendMailWithoutAttachment failed with an exception: " + ex.Message);
                    }
                }
            }
        }
 public virtual void AddItemToCache(Item parent, string fieldName, Item item, string key, ref LevelLogger logger)
 {
     var startKey = GetBaseCacheKey(parent, ref logger);
     if (startKey == null)
     {
         return;
     }
     AddToCache(startKey, item, fieldName, key, ref logger);
 }
Exemplo n.º 13
0
        public virtual LevelLogger CreateLevelLogger(string name)
        {
            var levelLogger = new LevelLogger(Logger)
            {
                Name = name
            };

            AddChild(levelLogger);
            return(levelLogger);
        }
Exemplo n.º 14
0
        public override LevelLogger CreateLevelLogger(string name)
        {
            var levelLogger = new LevelLogger(this)
            {
                Name = name
            };

            AddChild(levelLogger);
            return(levelLogger);
        }
 public List<Item> GetItemsFromCache(Item parent, string fieldName, string key, ref LevelLogger logger)
 {
     var startKey = GetBaseCacheKey(parent, ref logger);
     if (startKey == null)
     {
         return null;
     }
     var completeKey = startKey + "|" + fieldName + "|" + key;
     completeKey = completeKey.ToLower();
     return Caching.Get(completeKey);
 }
 public virtual void InitializeItemsCache(Item parent, string fieldNameForKeys, ref LevelLogger logger)
 {
     if (parent == null)
     {
         logger.AddError("Parent was null in InitializeItemsCache", "The parent was null.");
         return;
     }
     if (String.IsNullOrEmpty(fieldNameForKeys))
     {
         logger.AddError("The fieldNameForKeys was null or empty.", String.Format("The fieldNameForKeys was null or empty. fieldNameForKeys: {0}", fieldNameForKeys));
         return;
     }
     var startKey = GetBaseCacheKey(parent, ref logger);
     var fieldNameKeys = fieldNameForKeys.Split('|');
     using (new LanguageSwitcher(BaseDataMap.ImportToLanguageVersion))
     {
         var getItemsByKeyLogger = logger.CreateLevelLogger();
         string pattern = "{0}//*";
         var query = String.Format(pattern, parent.Paths.FullPath);
         try
         {
             var items = BaseDataMap.SitecoreDB.SelectItems(query);
             if (items != null)
             {
                 if (items.Any())
                 {
                     foreach (var item in items)
                     {
                         if (item != null)
                         {
                             foreach (var fieldNameKey in fieldNameKeys)
                             {
                                 if (!String.IsNullOrEmpty(fieldNameKey))
                                 {
                                     var keyValue = item[fieldNameKey];
                                     if (!String.IsNullOrEmpty(keyValue))
                                     {
                                         AddToCache(startKey, item, fieldNameKey, keyValue, ref getItemsByKeyLogger);
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
         catch (Exception ex)
         {
             getItemsByKeyLogger.AddError("Exception in InitializeItemsCache", ex.Message);
         }
     }
 }
 public override string GetAbsoluteImageUrl(BaseDataMap map, object importRow, ref Item newItem, string importValue, ref LevelLogger logger)
 {
     var getAbsoluteImageUrlLogger = logger.CreateLevelLogger();
     var src = StringUtil.ReadBetweenTags(importValue, SrcTagHtml, EndTagHtml);
     if (!IsRequired && String.IsNullOrEmpty(src))
     {
         return String.Empty;
     }
     if (IsRequired && String.IsNullOrEmpty(src))
     {
         getAbsoluteImageUrlLogger.AddError(CategoryConstants.TheSrcForTheImageWasNullOrEmpty, String.Format("The src for the image was null or empty. This must be provided since the isRequired value is set for this field. ImportRow: {0}.",
                              map.GetImportRowDebugInfo(importRow)));
     }
     return base.GetAbsoluteImageUrl(map, importRow, ref newItem, src, ref getAbsoluteImageUrlLogger);
 }
 public override byte[] GetImageAsBytes(BaseDataMap map, object importRow, ref Item newItem, string importValue, ref LevelLogger logger)
 {
     var getImageLogger = logger.CreateLevelLogger();
     var src = GetAbsoluteImageUrl(map, importRow, ref newItem, importValue, ref getImageLogger);
     if (String.IsNullOrEmpty(src) && !IsRequired)
     {
         return null;
     }
     if (String.IsNullOrEmpty(src) && IsRequired)
     {
         getImageLogger.AddError(CategoryConstants.TheSrcForTheImageWasNullOrEmptyAfterReturnOfTheGetAbsoluteImageUrl, String.Format("The src for the image was null or empty after return of the GetAbsoluteImageUrl method in the ToImageFromImageHtmlTag field class. An src must be provided. ImportRow: {0}.",
                              map.GetImportRowDebugInfo(importRow)));
         return null;
     }
     return base.GetImageAsBytes(map, importRow, ref newItem, src, ref getImageLogger);
 }
        public LevelLogger RunDataSyncJob(Item dataSyncItem, ref LevelLogger logger)
        {
            string errorMessage = String.Empty;

            var map = InstantiateDataMap(dataSyncItem, ref logger);
            if (!String.IsNullOrEmpty(errorMessage))
            {
                logger.AddError("Error", errorMessage);
                return logger;
            }
            if (map != null)
            {
                logger = map.Process();
            }
            return logger;
        }
 public virtual void Initialize(ref LevelLogger logger)
 {
     if (BaseDataMap.IsDisableItemsNotPresentInImport && BaseDataMap.DisableItemsFolderItem != null)
     {
         var disabledLogger = logger.CreateLevelLogger();
         InitializeItemsCache(BaseDataMap.DisableItemsFolderItem, BaseDataMap.IdentifyTheSameItemsByFieldDefinition.GetNewItemField(), ref disabledLogger);
     }
     var itemsAndParentLogger = logger.CreateLevelLogger();
     if (BaseDataMap.FolderByParentHierarchy)
     {
         InitializeItemsCache(BaseDataMap.Parent, BaseDataMap.IdentifyTheSameItemsByFieldDefinition.GetNewItemField() + "|" + BaseDataMap.IdentifyParentByWhatFieldOnParent, ref itemsAndParentLogger);
     }
     else
     {
         InitializeItemsCache(BaseDataMap.Parent, BaseDataMap.IdentifyTheSameItemsByFieldDefinition.GetNewItemField(), ref itemsAndParentLogger);
     }
 }
 public static void PublishItemSmart(Data.Items.Item rootItem, Database source, Database target, Language lang, BaseDataMap map, ref LevelLogger logger)
 {
     var publishFullLogger = logger.CreateLevelLogger();
     if (rootItem == null)
     {
         publishFullLogger.AddError("RootItem cannot be [null]", "RootItem cannot be [null]");
         return;
     }
     try
     {
         ItemPublisher(Options(rootItem, source, target, lang, PublishMode.Smart)).Publish();
     }
     catch (Exception ex)
     {
         publishFullLogger.AddError("PublishItemSmart of item failed with exception.", String.Format("PublishItemSmart of item {0} failed. Exception: {1}", rootItem.ID, map.GetExceptionDebugInfo(ex)));
     }
 }
        public static bool AttachImageToItem(BaseDataMap map, object importRow, Item newItem, string newItemField, MediaItem imageItem, ref LevelLogger logger, string height = null, string width = null)
        {
            var attachImageLogger = logger.CreateLevelLogger();
            if (imageItem != null)
            {
                if (string.IsNullOrEmpty(newItemField))
                {
                    {
                        attachImageLogger.AddError(NewItemFieldIsNotDefinedForMediaitem, String.Format("NewItemField is not defined for mediaitem: {0}.",
                                               map.GetImportRowDebugInfo(importRow)));
                        return false;
                    }
                }
                if (!newItem.Editing.IsEditing)
                {
                    newItem.Editing.BeginEdit();
                }
                ImageField imageField = newItem.Fields[newItemField];
                if (imageField.MediaID != imageItem.ID)
                {
                    imageField.Clear();
                    imageField.MediaID = imageItem.ID;
                    if (!String.IsNullOrEmpty(height))
                    {
                        imageField.Height = height;
                    }
                    if (!String.IsNullOrEmpty(width))
                    {
                        imageField.Width = width;
                    }

                    if (!String.IsNullOrEmpty(imageItem.Alt))
                    {
                        imageField.Alt = imageItem.Alt;
                    }
                    else
                    {
                        imageField.Alt = imageItem.DisplayName;
                    }
                    return true;
                }
            }
            return false;
        }
        public void FillField(BaseDataMap map, object importRow, ref Item newItem, string importValue, out bool updatedField, ref LevelLogger logger)
        {
            var fillFieldLogger = logger.CreateLevelLogger();

            updatedField = false;
            //ignore import value and store value provided
            Field f = newItem.Fields[NewItemField];
            if (f != null)
            {
                if (f.Value != Value)
                {
                    f.Value = Value;
                    updatedField = true;
                }
            }
            if (IsRequired && f == null)
            {
                fillFieldLogger.AddError(CategoryConstants.RequiredFieldNotFoundOnItem, String.Format("The Item '{0}' of template type: '{1}' didn't contain a field with name '{2}'. This field must be present because the 'Is Required Field' is checked.", map.GetItemDebugInfo(newItem), newItem.TemplateName, NewItemField));
            }
        }
Exemplo n.º 24
0
 public override void FillField(Providers.BaseDataMap map, object importRow, ref Item newItem, string importValue, out bool updatedField, ref LevelLogger logger)
 {
     var fillFieldLogger = logger.CreateLevelLogger();
     var xml = string.Empty;
     if (!String.IsNullOrEmpty(importValue))
     {
         const string pattern = @".+\@.+\..+";
         if (Regex.Match(importValue, pattern).Success)
         {
             xml = String.Format(SitecoreEmailLinkXml, importValue);
         }
         else
         {
             updatedField = false;
             fillFieldLogger.AddError(CategoryConstants.EmailWasInWrongFormatOnImportRow, String.Format("The import value '{0}' was not a correct email. The value was not stored on the field. Importrow: {1}. ", importValue, map.GetImportRowDebugInfo(importRow)));
             return;
         }
     }
     base.FillField(map, importRow, ref newItem, xml, out updatedField, ref fillFieldLogger);
 }
        public BaseDataMap InstantiateDataMap(Item dataSyncItem, ref LevelLogger logger)
        {
            var currentDB = Configuration.Factory.GetDatabase("master");

            string handlerAssembly = dataSyncItem[FieldNameHandlerAssembly];
            string handlerClass = dataSyncItem[FieldNameHandlerClass];

            if (!String.IsNullOrEmpty(handlerAssembly))
            {
                if (!String.IsNullOrEmpty(handlerClass))
                {
                    BaseDataMap map = null;
                    try
                    {
                        map = (BaseDataMap)Reflection.ReflectionUtil.CreateObject(handlerAssembly, handlerClass, new object[] { currentDB, dataSyncItem, logger });
                    }
                    catch (FileNotFoundException fnfe)
                    {
                        logger.AddError("Error", "The binary specified could not be found" + fnfe.Message);
                    }
                    if (map != null)
                    {
                        return map;
                    }
                    logger.AddError("Error", String.Format("The data map provided could not be instantiated. Assembly:'{0}' Class:'{1}'", handlerAssembly, handlerClass));
                }
                else
                {
                    logger.AddError("Error", "Import handler class is not defined");
                }
            }
            else
            {
                logger.AddError("Error", "import handler assembly is not defined");
            }
            return null;
        }
 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");
         }
     }
 }
 public override string GetFieldValue(object importRow, string fieldName, ref LevelLogger logger)
 {
     var levelLogger = logger.CreateLevelLogger();
     try
     {
         var row = importRow as Dictionary<string, string>;
         if (row != null)
         {
             if (row.ContainsKey(fieldName))
             {
                 return row[fieldName];
             }
             Logger.AddError("Error", string.Format("The fieldName {0} didn't exist in the import row.", fieldName));
         }
     }
     catch (Exception ex)
     {
         levelLogger.AddError("GetFieldValue failed",
             string.Format(
                 "The GetFieldValue method failed with an exception. ImportRow: {0}. FieldName: {1}. Exception: {2}.",
                 GetImportRowDebugInfo(importRow), fieldName, ex));
     }
     return string.Empty;
 }
        public override byte[] GetImageAsBytes(Providers.BaseDataMap map, object importRow, ref Item newItem, string importValue, ref LevelLogger logger)
        {
            var getImageAsBytesLogger = logger.CreateLevelLogger();
            try
            {
                if (IsRequired && String.IsNullOrEmpty(importValue))
                {
                    getImageAsBytesLogger.AddError("Required field was null or empty in GetImageAsBytes", String.Format(
                            "The 'GetImageAsBytes' could not retrieve an image since the importValue was null or empty. The field was marked as required. " +
                            "ImportRow: {0}.",
                            map.GetImportRowDebugInfo(importRow)));
                    return null;
                }
                if (!IsRequired && String.IsNullOrEmpty(importValue))
                {
                    return null;
                }
                if (String.IsNullOrEmpty(ImageFilesToImportAbsolutePath))
                {
                    getImageAsBytesLogger.AddError("The setting 'ImageFilesToImportAbsolutePath' was null or empty", String.Format(
                            "The setting 'ImageFilesToImportAbsolutePath' was null or empty. Therefor the image could not be found, since there is no place to search for it. Plase provide a value." +
                            "ImportValue: {0}. ImportRow: {1}.", importValue, map.GetImportRowDebugInfo(importRow)));
                    return null;
                }
                var searchPattern = importValue + "*.*";
                var directoryInfo = new DirectoryInfo(ImageFilesToImportAbsolutePath);
                var files = directoryInfo.GetFiles(searchPattern, SearchTopDirectoryOnly);

                if (files.Length == 0)
                {
                    getImageAsBytesLogger.AddError("Attempt to find a file failed in GetImageAsBytes", String.Format(
                            "In the GetImageAsBytes method the attempt to find a file failed. No file was found in the search for file '{0}' in the folder '{1}'." +
                            " ImportValue: {2}. ImportRow: {3}. SearchTopDirectoryOnlye: {4}.", searchPattern,
                            ImageFilesToImportAbsolutePath, importValue, map.GetImportRowDebugInfo(importRow),
                            SearchTopDirectoryOnly));
                    return null;
                }
                if (files.Length > 1)
                {
                    getImageAsBytesLogger.AddError("More than one file found in GetImageAsBytes", String.Format(
                            "In the GetImageAsBytes method there where found more than one file in the search for file '{0}' in the folder '{1}'." +
                            " ImportValue: {2}. ImportRow: {3}. SearchTopDirectoryOnlye: {4}.", searchPattern,
                            ImageFilesToImportAbsolutePath, importValue, map.GetImportRowDebugInfo(importRow),
                            SearchTopDirectoryOnly));
                    return null;
                }
                var file = files.First();
                if (file != null)
                {
                    try
                    {
                        byte[] bytes = File.ReadAllBytes(file.FullName);
                        return bytes;
                    }
                    catch (Exception ex)
                    {
                        getImageAsBytesLogger.AddError("Exception occured trying to ReadAllBytes from GetImageAsBytes", String.Format(
                                "In the GetImageAsBytes method an exception occured in trying to ReadAllBytes from file '{0}'. SearchPattern: '{1}' in the folder '{2}'." +
                                " ImportValue: {3}. ImportRow: {4}. SearchTopDirectoryOnlye: {5}. Exception: {6}.",
                                file.FullName, searchPattern, ImageFilesToImportAbsolutePath, importValue,
                                map.GetImportRowDebugInfo(importRow), SearchTopDirectoryOnly,
                                map.GetExceptionDebugInfo(ex)));
                        return null;
                    }
                }
                getImageAsBytesLogger.AddError("One file found but it was null in GetImageAsBytes", String.Format(
                        "In the GetImageAsBytes method one file was found, but it was null. SearchPattern: '{0}' in the folder '{1}'." +
                        " ImportValue: {2}. ImportRow: {3}. SearchTopDirectoryOnlye: {4}.",
                        searchPattern, ImageFilesToImportAbsolutePath, importValue, map.GetImportRowDebugInfo(importRow),
                        SearchTopDirectoryOnly));
                return null;
            }
            catch (Exception ex)
            {
                getImageAsBytesLogger.AddError(CategoryConstants.GetImageAsBytesFailedWithException, String.Format("In the GetImageAsBytes method an exception occured. ImageFilesToImportAbsolutePath: '{0}'." +
                                              " ImportValue: {1}. ImportRow: {2}. SearchTopDirectoryOnlye: {3}. Exception: {4}",
                                              ImageFilesToImportAbsolutePath, importValue, map.GetImportRowDebugInfo(importRow), SearchTopDirectoryOnly, map.GetExceptionDebugInfo(ex)));
                return null;
            }
        }
 private bool TryParseAttribute(IEnumerable result, out string fieldValue, ref LevelLogger logger)
 {
     fieldValue = String.Empty;
     try
     {
         var xAttributes = result.Cast<XAttribute>();
         var attributes = xAttributes as IList<XAttribute> ?? xAttributes.ToList();
         if (attributes.Count() > 1)
         {
             string pipeseperatedValues = String.Empty;
             foreach (var attribute in attributes)
             {
                 if (attribute != null)
                 {
                     var value = attribute.Value;
                     if (!String.IsNullOrEmpty(value))
                     {
                         pipeseperatedValues += value + "|";
                     }
                 }
             }
             if (pipeseperatedValues.EndsWith("|"))
             {
                 pipeseperatedValues = pipeseperatedValues.TrimEnd('|');
             }
             fieldValue = pipeseperatedValues;
             return true;
         }
         if (attributes.Count() == 1)
         {
             var xAttribute = attributes.First();
             if (xAttribute != null)
             {
                 fieldValue = xAttribute.Value;
                 return true;
             }
         }
     }
     catch (Exception exception)
     {
         return false;
     }
     return false;
 }
 private bool TryParseElement(IEnumerable result, out string fieldValue, ref LevelLogger logger)
 {
     fieldValue = String.Empty;
     try
     {
         var xElements = result.Cast<XElement>();
         var elements = xElements as IList<XElement> ?? xElements.ToList();
         if (elements.Count() > 1)
         {
             string pipeseperatedValues = String.Empty;
             foreach (var element in elements)
             {
                 if (element != null)
                 {
                     var value = element.Value;
                     if (!String.IsNullOrEmpty(value))
                     {
                         pipeseperatedValues += value + "|";
                     }
                 }
             }
             if (pipeseperatedValues.EndsWith("|"))
             {
                 pipeseperatedValues = pipeseperatedValues.TrimEnd('|');
             }
             fieldValue = pipeseperatedValues;
             return true;
         }
         if (elements.Count() == 1)
         {
             var xElement = elements.First();
             if (xElement != null)
             {
                 fieldValue = xElement.Value;
                 return true;
             }
         }
     }
     catch (Exception exception)
     {
         return false;
     }
     return false;
 }
 protected IEnumerable ExecuteXPathQueryOnXElement(XElement xElement, string query, ref LevelLogger logger)
 {
     var executeXPathQueryLogger = logger.CreateLevelLogger();
     if (xElement != null)
     {
         try
         {
             if (query == Dot)
             {
                 return GetInnerXml(xElement);
             }
             return xElement.XPathEvaluate(query) as IEnumerable;
         }
         catch (Exception ex)
         {
             executeXPathQueryLogger.AddError("Exception occured ExecuteXPathQueryOnXElement executing the XPath", String.Format("An exception occured in the ExecuteXPathQueryOnXElement method executing the XPath query. Query: {0}. Exception: {1}.", query, GetExceptionDebugInfo(ex)));
         }
     }
     executeXPathQueryLogger.AddError("XDocument was null in ExecuteXPathQueryOnXElement", "In ExecuteXPathQueryOnXElement method the XDocument was null.");
     return null;
 }
        /// <summary>
        /// gets custom data from a DataRow
        /// </summary>
        /// <param name="importRow"></param>
        /// <param name="fieldName"></param>
        /// <param name="errorMessage"></param>
        /// <returns></returns>
        public override string GetFieldValue(object importRow, string fieldName, ref LevelLogger logger)
        {
            var getFieldValueLogger = logger.CreateLevelLogger();
            try
            {
                var xElement = importRow as XElement;
                if (xElement != null)
                {
                    if (!String.IsNullOrEmpty(fieldName))
                    {
                        try
                        {
                            // First retrieve the fieldName as an attribute
                            var attribute = xElement.Attribute(fieldName);
                            if (attribute != null)
                            {
                                string value = attribute.Value;
                                if (!String.IsNullOrEmpty(value))
                                {
                                    return value;
                                }
                            }
                            else
                            {
                                // Then retrieve the fieldname as an subelement
                                var subElements = xElement.Elements(fieldName);
                                var elementsList = subElements.ToList();
                                if (elementsList.Count() > 1)
                                {
                                    // Log eror since document format is wrong. Has two or more elements with same name.
                                    getFieldValueLogger.AddError("Found more than one subelement with FieldName", String.Format(
                                            "The GetFieldValue method failed because the fieldName '{0}' resulted in more than one subelement in the Import Row. FieldName: {0}. ImportRow: {1}.",
                                            fieldName, GetImportRowDebugInfo(importRow)));
                                }
                                else if (elementsList.Count() == 1)
                                {
                                    var subElement = elementsList.First();
                                    if (subElement != null)
                                    {
                                        var value = subElement.Value;
                                        if (!String.IsNullOrEmpty(value))
                                        {
                                            return value;
                                        }
                                    }
                                }
                            }
                        }
                        catch (XmlException)
                        {
                            // We do nothing since this is most likely because we have a xpath query as the fieldname.
                        }

                        // Now finally try to retrieve through a xPath query
                        var executeXPathLogger = getFieldValueLogger.CreateLevelLogger();
                        var result = ExecuteXPathQueryOnXElement(xElement, fieldName, ref executeXPathLogger);
                        if (executeXPathLogger.HasErrors())
                        {
                            executeXPathLogger.AddError("Failure in ExecuteXPathQueryOnXElement", String.Format("The GetFieldValue method failed in executing the ExecuteXPathQueryOnXElement method."));
                        }
                        string fieldValue;
                        if (result is string)
                        {
                            return result as string;
                        }
                        var enumerable = result as IList<object> ?? result.Cast<object>().ToList();
                        if (TryParseAttribute(enumerable, out fieldValue, ref getFieldValueLogger))
                        {
                            return fieldValue;
                        }
                        if (TryParseElement(enumerable, out fieldValue, ref getFieldValueLogger))
                        {
                            return fieldValue;
                        }
                    }
                    else
                    {
                        getFieldValueLogger.AddError(CategoryConstants.TheFieldnameArgumentWasNullOrEmpty, String.Format("The GetFieldValue method failed because the 'fieldName' was null or empty. FieldName: {0}. ImportRow: {1}.", fieldName, GetImportRowDebugInfo(importRow)));
                    }
                }
                else
                {
                    getFieldValueLogger.AddError(CategoryConstants.TheImportRowWasNull, String.Format("The GetFieldValue method failed because the Import Row was null. FieldName: {0}.", fieldName));
                }
            }
            catch (Exception ex)
            {
                getFieldValueLogger.AddError(CategoryConstants.GetFieldValueFailed, String.Format("The GetFieldValue method failed with an exception. ImportRow: {0}. FieldName: {1}. Exception: {2}.", GetImportRowDebugInfo(importRow), fieldName, ex));
            }
            return String.Empty;
        }
 private string GetLookupId(BaseDataMap map, object importRow, ref Item newItem, string importValue, Item sourceListRootItem, ref LevelLogger logger)
 {
     var getLookupIdLogger = logger.CreateLevelLogger();
     IEnumerable<Item> t = GetMatchingChildItem(map, sourceListRootItem, importValue);
     if (t.Count() > 1)
     {
         getLookupIdLogger.AddError(CategoryConstants.ImportedValueResultInMoreThanOneLookupItem, String.Format(
                 "The Item '{0}' of template type: '{1}' has a field '{2}', but the imported value '{3}' did result in more that one lookup item. The field was not updated.",
                 map.GetItemDebugInfo(newItem), newItem.TemplateName, NewItemField, importValue));
         return String.Empty;
     }
     if (t.Count() == 1)
     {
         var guid = t.First().ID.ToString();
         if (String.IsNullOrEmpty(guid))
         {
             getLookupIdLogger.AddError(CategoryConstants.ImportedValueDidntResultInAIdToStore, String.Format(
                         "The Item '{0}' of template type: '{1}' has a field '{2}', but the imported value '{3}' didn't result in a ID to store.",
                         map.GetItemDebugInfo(newItem), newItem.TemplateName, NewItemField, importValue));
             return String.Empty;
         }
         return guid;
     }
     else
     {
         if (!DoNotRequireValueMatch)
         {
             getLookupIdLogger.AddError(CategoryConstants.DidntLocateALookupItemWithTheValue, String.Format("The Item '{0}' of template type: '{1}' didn't locate a lookup Item with the value '{2}'.",
                 newItem.ID.ToString(), newItem.TemplateName, importValue));
             return String.Empty;
         }
     }
     return String.Empty;
 }
 /// <summary>
 /// uses the import value to search for a matching item in the SourceList and then stores the GUID
 /// </summary>
 /// <param name="map">provides settings for the import</param>
 /// <param name="importRow"></param>
 /// <param name="newItem">newly created item</param>
 /// <param name="importValue">imported value to match</param>
 public override void FillField(BaseDataMap map, object importRow, ref Item newItem, string importValue, out bool updatedField, ref LevelLogger logger)
 {
     var fillFieldLogger = logger.CreateLevelLogger();
     updatedField = false;
     if (IsRequired)
     {
         if (String.IsNullOrEmpty(importValue))
         {
             fillFieldLogger.AddError(CategoryConstants.ImportedValueToFieldWasEmpty, String.Format("The Item '{0}' of template type: '{1}', field '{2}', but the imported value '{3}' was empty. This field must be provided when the field is required. The field was not updated.", map.GetItemDebugInfo(newItem), newItem.TemplateName, NewItemField, importValue));
             return;
         }
     }
     if (!ID.IsID(SourceList))
     {
         fillFieldLogger.AddError(CategoryConstants.SourceListNotAnValidSitecoreId, String.Format(
                 "The 'Source List' provided was not an valid Sitecore ID. SourceList: {0}. The Fill Field method was aborted and the fieldvalue was not updated.", SourceList));
         return;
     }
     //get parent item of list to search
     Item i = newItem.Database.GetItem(SourceList);
     if (i != null)
     {
         if (!String.IsNullOrEmpty(importValue))
         {
             Field f = newItem.Fields[NewItemField];
             if (f != null)
             {
                 var guidValue = String.Empty;
                 if (!String.IsNullOrEmpty(MultiListDelimiter))
                 {
                     var keys = importValue.Split(new[] {MultiListDelimiter}, StringSplitOptions.RemoveEmptyEntries);
                     foreach (var keyValue in keys)
                     {
                         var trimmedKeyValue = keyValue.Trim();
                         string errorMessage = String.Empty;
                         var id = GetLookupId(map, importRow, ref newItem, trimmedKeyValue, i, ref fillFieldLogger);
                         if (!String.IsNullOrEmpty(errorMessage))
                         {
                             fillFieldLogger.AddError(CategoryConstants.ErrorToLocateTheLookupIdInMultiList, String.Format("An error occured in trying to locate the Lookup id in a MultiList attempt. The MultiListDelimiter: {0}. The importValue was '{1}'. Item: {2}. The errormessage was: {3}.",
                             MultiListDelimiter, importValue, map.GetItemDebugInfo(newItem), errorMessage));
                             return;
                         }
                         guidValue += id + "|";
                     }
                     if (guidValue.EndsWith("|"))
                     {
                         guidValue = guidValue.Substring(0, guidValue.Length - 1);
                     }
                 }
                 else
                 {
                     string errorMessage = String.Empty;
                     guidValue = GetLookupId(map, importRow, ref newItem, importValue, i, ref fillFieldLogger);
                     if (!String.IsNullOrEmpty(errorMessage))
                     {
                         fillFieldLogger.AddError(CategoryConstants.ErrorToLocateTheLookupId, String.Format("An error occured in trying to locate the Lookup id. The importValue was '{0}'. Item: {1}. The errormessage was: {2}.",
                             importValue, map.GetItemDebugInfo(newItem), errorMessage));
                         return;
                     }
                 }
                 if (String.IsNullOrEmpty(guidValue))
                 {
                     if (!DoNotRequireValueMatch)
                     {
                         fillFieldLogger.AddError(CategoryConstants.ImportedValueDidntResultInAIdToStore, String.Format(
                             "The Item '{0}' of template type: '{1}' has a field '{2}', but the imported value '{3}' didn't result in a ID to store.",
                             map.GetItemDebugInfo(newItem), newItem.TemplateName, NewItemField, importValue));
                         return;
                     }
                 }
                 if (f.Value != guidValue)
                 {
                     f.Value = guidValue;
                     updatedField = true;
                 }
             }
             if (IsRequired && f == null)
             {
                 fillFieldLogger.AddError(CategoryConstants.RequiredFieldNotFoundOnItem, String.Format(
                         "The Item '{0}' of template type: '{1}' didn't contain a field with name '{2}'. This field must be present because the 'Is Required Field' is checked.",
                         map.GetItemDebugInfo(newItem), newItem.TemplateName, NewItemField));
                 return;
             }
         }
         else
         {
             if (IsRequired)
             {
                 fillFieldLogger.AddError(CategoryConstants.TheGuidDidntResultInAHitForLookup, String.Format("The Item '{0}' of template type: '{1}' had a Guid field '{2}' where the imported value '{3}' didn't result any hit. Because the 'Is Required Field' is checked there must be found a value i Sitecore. The field was not updated.", map.GetItemDebugInfo(newItem), newItem.TemplateName, NewItemField, importValue));
                 return;
             }
             if (newItem[NewItemField] != importValue)
             {
                 newItem[NewItemField] = importValue;
                 updatedField = true;
             }
         }
     }
     if (IsRequired && i == null)
     {
         fillFieldLogger.AddError(CategoryConstants.TheGuidFieldHadASourcelistThatWasNull, String.Format("The Item '{0}' of template type: '{1}' had a Guid field '{2}' for which SourceList was null. This SourceList must be present because the 'Is Required Field' is checked.", map.GetItemDebugInfo(newItem), newItem.TemplateName, NewItemField));
         return;
     }
 }
 /// <summary>
 /// gets a field value from an item
 /// </summary>
 /// <param name="importRow"></param>
 /// <param name="fieldName"></param>
 /// <returns></returns>
 public override string GetFieldValue(object importRow, string fieldName, ref LevelLogger logger)
 {
     var getFieldValueLogger = logger.CreateLevelLogger();
     var importRowItem = importRow as Item;
     if (importRowItem != null)
     {
         if (!String.IsNullOrEmpty(fieldName))
         {
             switch (fieldName.ToLower())
             {
                 case ("@key"):
                     return importRowItem.Key;
                 case ("@name"):
                     return importRowItem.Name;
                 case ("@displayname"):
                     return importRowItem.DisplayName;
                 case ("@id"):
                     return importRowItem.ID.ToShortID().ToString();
                 case ("@parentid"):
                     return importRowItem.Parent != null
                                ? importRowItem.ParentID.ToShortID().ToString()
                                : string.Empty;
             }
             var field = importRowItem.Fields[fieldName];
             if (field != null)
             {
                 return importRowItem[fieldName];
             }
             getFieldValueLogger.AddError("The 'fieldName' didn't result in any field on the item", String.Format("The GetFieldValue method failed because the the 'fieldName' didn't result in any field on the item. ImportRow: {0}.", GetImportRowDebugInfo(importRow)));
         }
         else
         {
             getFieldValueLogger.AddError(CategoryConstants.TheFieldnameArgumentWasNullOrEmpty, String.Format("The GetFieldValue method failed because the the 'fieldName' was null or empty. ImportRow: {0}.", GetImportRowDebugInfo(importRow)));
         }
     }
     else
     {
         getFieldValueLogger.AddError(CategoryConstants.TheImportRowWasNull, String.Format(
                            "The GetFieldValue method failed because the Import Row was null. FieldName: {0}.",
                            fieldName));
     }
     return String.Empty;
 }