public virtual void FillField(BaseDataMap map, object importRow, ref Item newItem, string importValue, out bool updatedField, ref LevelLogger logger)
        {
            var fillFieldLogger = logger.CreateLevelLogger();

            updatedField = false;
            //store the imported value as is
            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 f = newItem.Fields[NewItemField];

            if (f != null)
            {
                if (f.Value != importValue)
                {
                    fillFieldLogger.AddInfo(CategoryConstants.UpdatedField, String.Format("Updated value in field from '{0}' to '{1}'", LimitText(f.Value), LimitText(importValue)));
                    f.Value      = importValue;
                    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 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);
        }
Example #3
0
        public static MediaItem ImageHelper(string filename, string originalFileNameWithExtension, string imageAltText, ID mediaItemParentId, bool isToReplaceExistingImage, byte[] imageBytes, ref LevelLogger logger)
        {
            var imageHelperLogger = logger.CreateLevelLogger();

            var filepath = Helper.GetSitecoreMediaItemPath(mediaItemParentId);

            if (string.IsNullOrEmpty(filepath))
            {
                imageHelperLogger.AddError(CategoryConstants.TheImageMediaLibraryPathIsNotSet, String.Format("The image media library path is not set. mediaItemParentId: {0}.", mediaItemParentId));
                return(null);
            }

            var mediaItem = Helper.IsImageExisting(mediaItemParentId, filename);

            if (mediaItem != null)
            {
                if (isToReplaceExistingImage)
                {
                    //AttachNewImageToMediaItem(mediaItem, filename, imageBytes, imageAltText, filepath, ref errorMessage);
                }
                else
                {
                    return(mediaItem);
                }
            }
            var imageItem = CreateMediaItem(filename, originalFileNameWithExtension, imageAltText, filepath, imageBytes, ref imageHelperLogger);

            return(imageItem);
        }
        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);
            }
        }
Example #5
0
        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 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);
            }
        }
Example #7
0
        /// <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);
        }
Example #8
0
        public virtual MediaItem GetMediaItemFromImageLibrary(BaseDataMap map, ID mediaItemId, string key, string value, ref LevelLogger logger)
        {
            var getMediaItemLogger = logger.CreateLevelLogger();
            var root = ImageHandler.Database.GetItem(mediaItemId);

            if (root != null)
            {
                var getItemsByKeyLogger = getMediaItemLogger.CreateLevelLogger();
                var items = map.GetItemsByKey(root, key, value, ref getItemsByKeyLogger);
                if (getItemsByKeyLogger.HasErrors() || items == null)
                {
                    getMediaItemLogger.AddError("Failed in retrieving mediaItem from key", String.Format(
                                                    "An error occured trying to retrieve the mediaItem on fieldName: '{0}' and value: {1}. The error happend in GetItemsByKey method.",
                                                    key, value));
                    return(null);
                }
                if (items.Count > 1)
                {
                    getMediaItemLogger.AddError("More than one item with the same key", String.Format(
                                                    "There were more than one items with the same key. The key must be unique. Therefor the image was not set. FieldName key: {0}. Value: {1}.",
                                                    key, value));
                    return(null);
                }
                if (items.Count == 1)
                {
                    return(items[0]);
                }
            }
            return(null);
        }
        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 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 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);
                }
            }
        }
Example #12
0
        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);
        }
        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);
        }
Example #14
0
        /// <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);
        }
        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));
        }
Example #17
0
        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 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 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);
        }
Example #20
0
        public override void ValidateImportData(IList <object> importData, ref LevelLogger logger)
        {
            var validateImportDataLogger = logger.CreateLevelLogger();

            foreach (var fieldDefinition in FieldDefinitions)
            {
                var newField = fieldDefinition.GetExistingFieldNames();
                foreach (var existingFieldName in fieldDefinition.GetExistingFieldNames())
                {
                    if (!HeaderColumns.ContainsKey(existingFieldName.ToLower()))
                    {
                        validateImportDataLogger.AddError("A column was expected but not found", String.Format("--- A column with name {0} was expected.\r\n", existingFieldName));
                    }
                }
            }
            if (!validateImportDataLogger.HasErrors())
            {
                base.ValidateImportData(importData, ref validateImportDataLogger);
            }
        }
        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);
        }
Example #22
0
        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));
            }
        }
Example #23
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);
        }
Example #24
0
        /// <summary>
        /// Create new media item
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="altText"></param>
        /// <param name="filepath"></param>
        /// <param name="fileBytes"></param>
        /// <param name="errorMessage"></param>
        /// <returns></returns>
        private static Item CreateMediaItem(string filename, string originalFileNameWithExtension, string altText, string filepath, byte[] fileBytes, ref LevelLogger logger)
        {
            var createMediaItemLogger = logger.CreateLevelLogger();;

            try
            {
                if (fileBytes != null)
                {
                    Item imageItem = null;
                    var  destPath  = filepath + "/" + filename;
                    using (var ms = new MemoryStream(fileBytes))
                    {
                        var options = new MediaCreatorOptions
                        {
                            FileBased = false,
                            IncludeExtensionInItemName = false,
                            KeepExisting  = false,
                            Versioned     = false,
                            AlternateText = altText,
                            Destination   = destPath,
                            Database      = Database
                        };
                        imageItem = MediaManager.Creator.CreateFromStream(ms, originalFileNameWithExtension, options);
                    }
                    if (imageItem != null)
                    {
                        return(imageItem);
                    }
                }
                else
                {
                    createMediaItemLogger.AddError(CreateMediaItemMissingDataToStream, String.Format("CreateMediaItem missing data to stream. Filename: {0}, AltText: {1}", filename, altText));
                }
            }
            catch (Exception ex)
            {
                createMediaItemLogger.AddError(CreateMediaItemFailed, String.Format("CreateMediaItem failed. Filename: {0}, AltText: {1}, Errormessage: {2}", filename, altText, ex.InnerException));
            }
            return(null);
        }
Example #25
0
        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);
        }
        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);
        }
Example #27
0
        public virtual bool VerifyConditionFromQuery(string line, ref LevelLogger logger)
        {
            var verifyConditionLogger = logger.CreateLevelLogger();

            if (!String.IsNullOrEmpty(Query))
            {
                if (Query.Contains(DefaultQueryDelimiterCharacter))
                {
                    var queryValues = Query.Split(DefaultQueryDelimiterCharacter);
                    if (queryValues.Length == 2)
                    {
                        string key   = queryValues[0];
                        string value = queryValues[1];
                        if (!String.IsNullOrEmpty(key) && !String.IsNullOrEmpty(value))
                        {
                            var retrievedValue = GetFieldValue(line, key, ref verifyConditionLogger);
                            return(value.ToLower().Equals(retrievedValue.ToLower()));
                        }
                        else
                        {
                            verifyConditionLogger.AddError("The Query was in wrong format. Either Key or value was null or empty", String.Format("The provided Query '{0}' was in wrong format. Either of the key or value was null or empty. Format should be 'key{1}value' ie 'Category{1}Summer'. " +
                                                                                                                                                 "Key: {2}. Value: {3}. Line: {4}.", Query, DefaultQueryDelimiterCharacter, key, value, line));
                        }
                    }
                    else
                    {
                        verifyConditionLogger.AddError("The Query was in wrong format.", String.Format("The provided Query '{0}' was in wrong format. Format should be 'key{1}value' ie 'Category{1}Summer'. " +
                                                                                                       "Line: {2}. QueryValues.Length: {3}.", Query, DefaultQueryDelimiterCharacter, line, queryValues.Length));
                    }
                }
                else
                {
                    verifyConditionLogger.AddError("The Query didn't contain a valid delimiter character", String.Format("The provided Query '{0}' didn't contain a valid delimiter character. This character must be: '{1}'. Line: {2}.  he VerifyConditionFromQuery method failed because the Query was null or empty.",
                                                                                                                         Query, DefaultQueryDelimiterCharacter, line));
                }
                return(false);
            }
            return(true);
        }
Example #28
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;
            }
        }
        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));
            }
        }
Example #30
0
        /// <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);
        }