private IEnumerable<Item> GetLookupValues(BaseDataMap map, Item listParent, string importValue, string value)
 {
     if (!lookupValues.Any())
     {
         var listItems = listParent.GetChildren();
         foreach (Item item in listItems)
         {
             var lookupValue = item[MatchOnFieldName].ToLower();
             if (!lookupValues.ContainsKey(lookupValue))
             {
                 lookupValues.Add(lookupValue, new List<Item> {item});
             }
             else
             {
                 var itemList = lookupValues[lookupValue];
                 if (itemList != null)
                 {
                     if (!itemList.Contains(item))
                     {
                         itemList.Add(item);
                     }
                 }
             }
         }
     }
     if (lookupValues.ContainsKey(value))
     {
         return lookupValues[value];
     }
     return new List<Item>();
 }
 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;
     }
 }
 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;
     }
 }
 public override IEnumerable<Item> GetMatchingChildItem(BaseDataMap map, Item listParent, string importValue)
 {
     //IEnumerable<Item> t = (from Item c in listParent.GetChildren()
     //                       where c[MatchOnFieldName].ToLower().Equals(importValue.ToLower())
     //                       select c).ToList();
     return GetLookupValues(map, listParent, importValue, importValue.ToLower());
     //return t;
 }
 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 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));
            }
        }
 public virtual string GetImageWidth(BaseDataMap map, object importRow, ref Item newItem, string importValue, ref LevelLogger logger)
 {
     return String.Empty;
 }
 public virtual ID GetMediaFolderItem(BaseDataMap map, object importRow, ref Item newItem, ref LevelLogger logger)
 {
     return MediaItemId;
 }
        public virtual byte[] GetImageAsBytes(BaseDataMap map, object importRow, ref Item newItem, string importValue, ref LevelLogger logger)
        {
            var getImageAsBytesLogger = logger.CreateLevelLogger();
            try
            {
                var stopWatch = new Stopwatch();
                stopWatch.Start();
                var image = ImageHandler.GetImageFromUrl(importValue);
                if (image == null)
                {
                    getImageAsBytesLogger.AddError(CategoryConstants.TheImageRetrievedFromUrlWasNull, String.Format("The image retrieved from the url was null. Src: '{0}'", importValue));
                    return null;
                }

                var imageBytes = ImageHandler.ImageToByteArray(image);
                if (imageBytes == null)
                {
                    getImageAsBytesLogger.AddError(CategoryConstants.TheImageBytesRetrievedWasNull, String.Format("The 'imageBytes' retrieved was null. Src: '{0}'", importValue));
                    return null;
                }
                return imageBytes;
            }
            catch (Exception ex)
            {
                getImageAsBytesLogger.AddError(CategoryConstants.GetImageAsBytesFailedWithException, String.Format("The GetImageAsBytes failed with an exception. Src: '{0}'. Exception: {1}.", importValue, map.GetExceptionDebugInfo(ex)));
                return null;
            }
        }
        public virtual MemoryStream GetImageAsMemoryStream(BaseDataMap map, object importRow, ref Item newItem, string importValue, ref LevelLogger logger, out string imageType)
        {
            imageType = String.Empty;
            var getImageAsMemoryStreamLogger = logger.CreateLevelLogger();
            try
            {
                var image = ImageHandler.GetImageFromUrl(importValue);
                if (image == null)
                {
                    getImageAsMemoryStreamLogger.AddError(CategoryConstants.TheImageRetrievedFromUrlWasNull, String.Format("The image retrieved from the url was null. Src: '{0}'", importValue));
                    return null;
                }
                imageType = ImageHandler.GetImageType(image);

                var memoryStream = ImageHandler.ImageToMemoryStream(image);
                if (memoryStream == null)
                {
                    getImageAsMemoryStreamLogger.AddError(CategoryConstants.TheMemoryStreamRetrievedWasNull, String.Format("The 'memoryStream' retrieved was null. Src: '{0}'", importValue));
                    return null;
                }
                return memoryStream;
            }
            catch (Exception ex)
            {
                getImageAsMemoryStreamLogger.AddError(CategoryConstants.GetImageAsMemoryStreamFailed, String.Format("The GetImageAsMemoryStream failed with an exception. Src: '{0}'. Exception: {1}.", importValue, map.GetExceptionDebugInfo(ex)));
                return null;
            }
        }
 public virtual string GetFileName(BaseDataMap map, object importRow, ref Item newItem, string importValue, ref LevelLogger logger)
 {
     var getFileNameLogger = logger.CreateLevelLogger();
     var fileNameFieldName = GetFileNameFromWhatField;
     if (String.IsNullOrEmpty(fileNameFieldName))
     {
         getFileNameLogger.AddError(CategoryConstants.GetFilenameFromwWhatFieldWasNullOrEmpty, String.Format("The 'GetFileNameFromWhatField' was null or empty. Please indicate which field the filename should be retrieved from. ImportRow: {0}.",
                 map.GetImportRowDebugInfo(importRow)));
         return null;
     }
     var fileName = map.GetFieldValue(importRow, fileNameFieldName, ref getFileNameLogger);
     if (String.IsNullOrEmpty(fileName))
     {
         getFileNameLogger.AddError(CategoryConstants.TheFilenameFromFieldWasNullOrEmpty, String.Format("The filename was attempted retrieved from the field '{0}', but it was null or empty. The image field name must be provided. ImportRow: {1}.",
                 fileNameFieldName, map.GetImportRowDebugInfo(importRow)));
         return null;
     }
     return fileName;
 }
 public virtual string GetImageAltText(BaseDataMap map, object importRow, ref Item newItem, string importValue, ref LevelLogger logger)
 {
     var getImageAltText = logger.CreateLevelLogger();
     var getImageAltTextIfNotProvidedFromWhatField = GetImageAltTextIfNotProvidedFromWhatField;
     if (!String.IsNullOrEmpty(getImageAltTextIfNotProvidedFromWhatField))
     {
         var altText = map.GetFieldValue(importRow, getImageAltTextIfNotProvidedFromWhatField, ref getImageAltText);
         if (!String.IsNullOrEmpty(altText))
         {
             return Helper.TitleCaseString(altText);
         }
     }
     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;
 }
        public override void FillField(BaseDataMap map, object importRow, ref Item newItem, string importValue, out bool updatedField, ref LevelLogger logger)
        {
            var fillFieldLogger = logger.CreateLevelLogger();
            try
            {
                updatedField = false;
                string errorMessage = String.Empty;
                string newTimeStamp;
                var isUpdateMediaItemLogger = fillFieldLogger.CreateLevelLogger();
                var isUpdateMediaItem = IsUpdateMediaItem(map, importRow, ref newItem, importValue, ref isUpdateMediaItemLogger, out newTimeStamp);
                if (isUpdateMediaItemLogger.HasErrors())
                {
                    fillFieldLogger.AddError("IsUpdateMediaItem failed with error", String.Format("The method IsUpdateMediaItem failed with the following error: {0}. ImportRow: {1}.",
                            errorMessage, map.GetImportRowDebugInfo(importRow)));
                    DeleteMediaItemIfEmpty(map, ref newItem, ref fillFieldLogger);
                    return;
                }
                if (isUpdateMediaItem)
                {
                    var getImageAltLogger = fillFieldLogger.CreateLevelLogger();
                    var imageAltText = GetImageAltText(map, importRow, ref newItem, importValue, ref getImageAltLogger);
                    if (getImageAltLogger.HasErrors())
                    {
                        getImageAltLogger.AddError("GetImageAltText failed with error", String.Format(
                                "The method GetImageAltText failed with the following error: {0}. ImportRow: {1}.",
                                errorMessage, map.GetImportRowDebugInfo(importRow)));
                        DeleteMediaItemIfEmpty(map, ref newItem, ref getImageAltLogger);
                        return;
                    }
                    var getOriginalLogger = fillFieldLogger.CreateLevelLogger();
                    var originalFileNameWithExtension = GetOriginalFileNameWithExtension(map, importRow, ref newItem,
                                                                                         importValue, ref getOriginalLogger);
                    if (getOriginalLogger.HasErrors())
                    {
                        getOriginalLogger.AddError("GetOriginalFileNameWithExtensio failed", String.Format("The method GetOriginalFileNameWithExtension failed with the following error: {0}. ImportRow: {1}.",
                                errorMessage, map.GetImportRowDebugInfo(importRow)));
                        DeleteMediaItemIfEmpty(map, ref newItem, ref getOriginalLogger);
                        return;
                    }
                    if (!IsRequired && String.IsNullOrEmpty(importValue))
                    {
                        return;
                    }
                    var imageType = "";
                    var getImageAsMemoryLogger = fillFieldLogger.CreateLevelLogger();
                    var memoryStream = GetImageAsMemoryStream(map, importRow, ref newItem, importValue, ref getImageAsMemoryLogger, out imageType);
                    if (getImageAsMemoryLogger.HasErrors())
                    {
                        getImageAsMemoryLogger.AddError("GetImageAsStream failed", String.Format("The method GetImageAsStream failed with the following error: {0}. ImportRow: {1}.",
                                errorMessage, map.GetImportRowDebugInfo(importRow)));
                        DeleteMediaItemIfEmpty(map, ref newItem, ref getImageAsMemoryLogger);
                        return;
                    }
                    if (memoryStream == null && !IsRequired)
                    {
                        return;
                    }
                    if (String.IsNullOrEmpty(originalFileNameWithExtension))
                    {
                        if (!String.IsNullOrEmpty(imageType))
                        {
                            originalFileNameWithExtension = imageType;
                        }
                        else
                        {
                            originalFileNameWithExtension = DefaultMediaType;
                        }
                    }

                    var imageHelperLogger = fillFieldLogger.CreateLevelLogger();
                    var imageItem = ImageHandler.ImageHelper(newItem.Name, originalFileNameWithExtension, imageAltText,
                                                             newItem.Parent.ID, true, memoryStream, ref imageHelperLogger);
                    if (imageItem != null)
                    {
                        newItem = imageItem;
                        newItem.Editing.BeginEdit();
                        newItem[Utility.Constants.FieldNameDataSyncTimeStamp] = newTimeStamp;
                        updatedField = true;
                    }
                }
            }
            catch (Exception ex)
            {
                updatedField = false;
                fillFieldLogger.AddError("Exception occured in FillField processing image/images", String.Format(
                        "An exception occured in FillField in processing of the image/images. Exception: {0}. ImportRow: {1}.",
                        map.GetExceptionDebugInfo(ex), map.GetImportRowDebugInfo(importRow)));
            }
        }
 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 && 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.",
                 (object) map.GetItemDebugInfo(newItem), (object) newItem.TemplateName,
                 (object) NewItemField, (object) 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;
     }
     var listParent = newItem.Database.GetItem(SourceList);
     if (listParent != null)
     {
         if (!string.IsNullOrEmpty(importValue))
         {
             var matchingChildItem = GetMatchingChildItem(map, listParent, importValue);
             var childItems = matchingChildItem as Item[] ?? matchingChildItem.ToArray();
             if (childItems.Any())
             {
                 var str = string.Empty;
                 foreach (var childItem in childItems)
                 {
                     if (childItem != null)
                     {
                         str += (str.Length > 0)
                                    ? "|" + childItem.ID
                                    : childItem.ID.ToString();
                     }
                 }
                 var field = newItem.Fields[NewItemField];
                 if (field != null)
                 {
                     if (string.IsNullOrEmpty(str))
                     {
                         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.",
                                 (object) map.GetItemDebugInfo(newItem), (object) newItem.TemplateName,
                                 (object) NewItemField, (object) importValue));
                         return;
                     }
                     if (field.Value != str)
                     {
                         field.Value = str;
                         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;
                 }
             }
             else if (!this.DoNotRequireValueMatch)
             {
                 fillFieldLogger.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;
             }
         }
         else if (this.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.",
                 (object) map.GetItemDebugInfo(newItem), (object) newItem.TemplateName,
                 (object) NewItemField, (object) importValue));
             return;
         }
         else if (newItem[NewItemField] != importValue)
         {
             newItem[NewItemField] = importValue;
             updatedField = true;
         }
     }
     if (IsRequired && listParent == 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.",
             (object) map.GetItemDebugInfo(newItem), (object) newItem.TemplateName,
             (object) this.NewItemField));
     }
 }
 /// <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;
     }
 }
 public override IEnumerable<Item> GetMatchingChildItem(BaseDataMap map, Item listParent, string importValue)
 {
     var values = ParseImportValues(importValue);
     var result = new List<Item>();
     foreach (var value in values)
     {
         if (!string.IsNullOrEmpty(value))
         {
             var list =  (IEnumerable<Item>)Enumerable.ToList<Item>(Enumerable.Where<Item>(Enumerable.Cast<Item>((IEnumerable)listParent.GetChildren()), (Func<Item, bool>)(c => c[this.MatchOnFieldName].ToLower().Equals(value.ToLower()))));
             result.AddRange(list);
         }
     }
     return result;
 }
 public CachingManager(BaseDataMap map)
 {
     BaseDataMap = map;
     Caching = new Caching();
 }
 public virtual bool IsUpdateMediaItem(BaseDataMap map, object importRow, ref Item newItem, string importValue, ref LevelLogger logger, out string newTimeStamp)
 {
     var isUpdateMediaItemLogger = logger.CreateLevelLogger();
     newTimeStamp = null;
     if (UpdateMediaItemStrategy == UpdateStrategy.AlwaysUpdate)
     {
         return true;
     }
     if (UpdateMediaItemStrategy == UpdateStrategy.OnlyWhenUpdatedTimestamp)
     {
         var getTimeLogger = isUpdateMediaItemLogger.CreateLevelLogger();
         var importRowTimeStamp = GetTimeStampIdentifier(map, importRow, ref newItem, importValue, ref getTimeLogger);
         if (getTimeLogger.HasErrors())
         {
             return false;
         }
         if (importRowTimeStamp == null)
         {
             isUpdateMediaItemLogger.AddError("IsUpdateMediaItem failed when 'importRowTimeStamp' was null", String.Format(
                     "The method IsUpdateMediaItem failed because the 'importRowTimeStamp' was null. This field is used to retrieve the timestamp of last updated value on importRow. ImportRow: {0}.",
                     map.GetImportRowDebugInfo(importRow)));
             return false;
         }
         newTimeStamp = importRowTimeStamp;
         var lastUpdatedTimeStamp = newItem[Sitecore.SharedSource.DataSync.Utility.Constants.FieldNameDataSyncTimeStamp];
         if (!String.IsNullOrEmpty(lastUpdatedTimeStamp))
         {
             return !lastUpdatedTimeStamp.Trim().ToLower().Equals(importRowTimeStamp.Trim().ToLower());
         }
         // If the timestamp field is empty, then we must update
         return true;
     }
     var mediaItem = (MediaItem)newItem;
     if (mediaItem != null)
     {
         return !mediaItem.HasMediaStream(FieldNameBlog);
     }
     isUpdateMediaItemLogger.AddError("Item could not be case to mediaItem in IsUpdateMediaItem", String.Format("The method IsUpdateMediaItem failed because the item could not be casted to a mediaItem and therefor we couldn't be determined if the item had a MediaStream. ImportRow: {0}.",
             map.GetImportRowDebugInfo(importRow)));
     return false;
 }
 public virtual string GetOriginalFileNameWithExtension(BaseDataMap map, object importRow, ref Item newItem, string importValue, ref LevelLogger logger)
 {
     var getOriginalLogger = logger.CreateLevelLogger();
     var getOriginalFileNameWithExtensionFromWhatField = GetOriginalFileNameWithExtensionFromWhatField;
     if (!String.IsNullOrEmpty(getOriginalFileNameWithExtensionFromWhatField))
     {
         var fileName = map.GetFieldValue(importRow, getOriginalFileNameWithExtensionFromWhatField, ref getOriginalLogger);
         if (!String.IsNullOrEmpty(fileName))
         {
             return fileName;
         }
     }
     return String.Empty;
 }
 public virtual string GetTimeStampIdentifier(BaseDataMap map, object importRow, ref Item newItem, string importValue, ref LevelLogger logger)
 {
     var getTimeStampLogger = logger.CreateLevelLogger();
     if (String.IsNullOrEmpty(GetTimeStampIdentifierFromWhatField))
     {
         getTimeStampLogger.AddError("No value in 'GetTimeStampIdentifierFromWhatField'", String.Format(
                 "The method GetTimeStampIdentifier failed because there wasn't any value in the field 'GetTimeStampIdentifierFromWhatField'. This field is used to retrieve the timestamp of last updated value on importRow. ImportRow: {0}.",
                 map.GetImportRowDebugInfo(importRow)));
         return null;
     }
     var getFieldValueLogger = getTimeStampLogger.CreateLevelLogger();
     var timeStamp = map.GetFieldValue(importRow, GetTimeStampIdentifierFromWhatField, ref getFieldValueLogger);
     if (String.IsNullOrEmpty(timeStamp))
     {
         getFieldValueLogger.AddError("GetTimeStampIdentifier failed", String.Format("The method GetTimeStampIdentifier failed because the 'timestamp' from the importRow was null or empty. Please make sure each importRow has a timestamp. ImportRow: {0}.",
                 map.GetImportRowDebugInfo(importRow)));
         return null;
     }
     return timeStamp;
 }
        public override void FillField(BaseDataMap map, object importRow, ref Item newItem, string importValue, out bool updatedField, ref LevelLogger logger)
        {
            var fillFieldLogger = logger.CreateLevelLogger();
            try
            {
                updatedField = false;

                if (ID.IsNullOrEmpty(MediaItemId))
                {
                    fillFieldLogger.AddError(CategoryConstants.TheImageMediaLibraryPathIsNotSet, String.Format("The image media library path is not set. ImportRow: {0}.", map.GetImportRowDebugInfo(importRow)));
                    return;
                }
                var getImageAlTextLogger = fillFieldLogger.CreateLevelLogger("GetImageAltText");
                var imageAltText = GetImageAltText(map, importRow, ref newItem, importValue, ref fillFieldLogger);
                if (getImageAlTextLogger.HasErrors())
                {
                    getImageAlTextLogger.AddError(CategoryConstants.GetimagealttextMethodFailed, String.Format("The method GetImageAltText failed. ImportRow: {0}.", map.GetImportRowDebugInfo(importRow)));
                    return;
                }
                var getOriginalFileNameLogger = fillFieldLogger.CreateLevelLogger("GetOriginalFileNameWithExtension");
                var originalFileNameWithExtension = GetOriginalFileNameWithExtension(map, importRow, ref newItem, importValue, ref getOriginalFileNameLogger);
                if (getOriginalFileNameLogger.HasErrors())
                {
                    getOriginalFileNameLogger.AddError(CategoryConstants.GetoriginalfilenamewithextensionFailed, String.Format("The method GetOriginalFileNameWithExtension failed. ImportRow: {0}.", map.GetImportRowDebugInfo(importRow)));
                    return;
                }
                var getFileNameLogger = fillFieldLogger.CreateLevelLogger("GetFileName");
                var fileName = GetFileName(map, importRow, ref newItem, importValue, ref getFileNameLogger);
                if (getFileNameLogger.HasErrors())
                {
                    getFileNameLogger.AddError(CategoryConstants.GetfilenameFailed, String.Format("The method GetFileName failed. ImportRow: {0}.", map.GetImportRowDebugInfo(importRow)));
                    return;
                }
                fileName = StringUtility.GetNewItemName(fileName, map.ItemNameMaxLength);

                if (!IsRequired && String.IsNullOrEmpty(importValue))
                {
                    return;
                }
                var imageType = "";
                var getImageAsMemoryStreamLogger = fillFieldLogger.CreateLevelLogger("GetImageAsMemoryStream");
                var memoryStream = GetImageAsMemoryStream(map, importRow, ref newItem, importValue, ref getImageAsMemoryStreamLogger, out imageType);
                if (getImageAsMemoryStreamLogger.HasErrors())
                {
                    getImageAsMemoryStreamLogger.AddError(CategoryConstants.GetImageAsMemoryStreamFailed, String.Format("The method GetImageAsMemoryStream failed. ImportRow: {0}.", map.GetImportRowDebugInfo(importRow)));
                    return;
                }
                if (memoryStream == null && !IsRequired)
                {
                    return;
                }
                if (String.IsNullOrEmpty(originalFileNameWithExtension))
                {
                    if (!String.IsNullOrEmpty(imageType))
                    {
                        originalFileNameWithExtension = imageType;
                    }
                    else
                    {
                        originalFileNameWithExtension = ".jpeg";
                    }
                }

                var getMediaFolderLogger = fillFieldLogger.CreateLevelLogger("GetMediaFolderItem");
                var mediaItemId = GetMediaFolderItem(map, importRow, ref newItem, ref getMediaFolderLogger);
                if (mediaItemId == (ID)null)
                {
                    getMediaFolderLogger.AddError(CategoryConstants.GetMediaFolderItemReturnedANullItemForTheMediaFolderitem, String.Format("The method GetMediaFolderItem returned a null item for the media folderItem. ImportRow: {0}.", map.GetImportRowDebugInfo(importRow)));
                    return;
                }
                if (getMediaFolderLogger.HasErrors())
                {
                    getMediaFolderLogger.AddError(CategoryConstants.GetMediaFolderItemFailed, String.Format("The method GetMediaFolderItem failed with an error. ImportRow: {0}.", map.GetImportRowDebugInfo(importRow)));
                    return;
                }
                var imageItem = ImageHandler.ImageHelper(fileName, originalFileNameWithExtension, imageAltText, mediaItemId, IsReplaceIfExist, memoryStream, ref fillFieldLogger);
                if (imageItem != null)
                {
                    var height = GetImageHeight(map, importRow, ref newItem, importValue, ref fillFieldLogger);
                    var width = GetImageWidth(map, importRow, ref newItem, importValue, ref fillFieldLogger);
                    ImageHandler.AttachImageToItem(map, importRow, newItem, NewItemField, imageItem, ref fillFieldLogger, height, width);
                }
            }
            catch (Exception ex)
            {
                updatedField = false;
                fillFieldLogger.AddError(CategoryConstants.ExceptionOccuredWhileProcessingImageImages, String.Format(
                        "An exception occured in FillField in processing of the image/images. Exception: {0}. ImportRow: {1}.",
                        map.GetExceptionDebugInfo(ex), map.GetImportRowDebugInfo(importRow)));
            }
        }
 private static void DeleteMediaItemIfEmpty(BaseDataMap map, ref Item newItem, ref LevelLogger logger)
 {
     var mediaItem = (MediaItem)newItem;
     if (mediaItem != null)
     {
         if (!mediaItem.HasMediaStream(FieldNameBlog))
         {
             logger.AddInfo("Deleted Empty MediaItem Without Blob", String.Format("The media doesn't contain any Blob value (no image). To prevent an empty Media Item without a blob to remain in the Media Library, the MediaItem was deleted. Item: {0}", map.GetItemDebugInfo(newItem)));
             newItem.Delete();
             newItem = null;
             logger.IncrementCounter("DeletedEmptyMediaItem");
         }
     }
 }
 public virtual IEnumerable<Item> GetMatchingChildItem(BaseDataMap map, Item listParent,string importValue)
 {
     IEnumerable<Item> t = (from Item c in listParent.GetChildren()
                            where c.DisplayName.ToLower().Equals(StringUtility.GetNewItemName(importValue, map.ItemNameMaxLength))
                            select c).ToList();
     return t;
 }
 public virtual string GetAbsoluteImageUrl(BaseDataMap map, object importRow, ref Item newItem, string src, ref LevelLogger logger)
 {
     if (src.StartsWith(DoublePipe))
     {
         return src.Replace(DoublePipe, HttpPrefix);
     }
     return src;
 }
 //fills it's own field
 public void FillField(BaseDataMap map, ref Item newItem, Item importRow)
 {
     Field f = newItem.Fields[NewItemField];
     if(f != null)
         f.Value = importRow.Paths.FullPath;
 }
 protected void Run(BaseDataMap map, LevelLogger logger, OutputHandlerBase exporter)
 {
     Context.Job.Status.State = JobState.Running;
     logger.AddKey(Utility.Constants.DataSyncItemId, map.ImportItem.ID.ToString());
     logger.AddData(Utility.Constants.DataSyncItem, map.ImportItem);
     logger.AddData(Logger.Log.Constants.Identifier, map.ImportItem.Name);
     var startedAt = DateTime.Now;
     logger = map.Process();
     var finishededAt = DateTime.Now;
     logger.AddData(Logger.Log.Constants.StartTime, startedAt);
     logger.AddData(Logger.Log.Constants.EndTime, finishededAt);
     try
     {
         MailManager.SendLogReport(ref logger, exporter);
     }
     catch (Exception exception)
     {
         Diagnostics.Log.Error(exporter.GetIdentifier() + " failed in sending out the mail. Please see the exception message for more details. Exception:" + exception.Message + ". Status:\r\n" +
             exporter.Export(), typeof(DataSyncWizard));
     }
     if (logger.HasErrors())
     {
         Context.Job.Status.Failed = true;
     }
     else
     {
         Context.Job.Status.State = JobState.Finished;
     }
 }