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");
         }
     }
 }
        protected virtual bool UpdateItem(Item item, object importRow, string itemName, Item parentItem, ref LevelLogger logger)
        {
            var updateItemLogger = logger.CreateLevelLogger("Update Item");
            var updatedItem = false;
            try
            {
                using (new LanguageSwitcher(ImportToLanguageVersion))
                {
                    using (new SecurityDisabler())
                    {
                        if (AddLanguageVersionIfNoneExists(item, ref logger))
                        {
                            updateItemLogger.IncrementCounter(IncrementConstants.LanguageVersionAdded);
                        }

                        // Move the item to it's correct position
                        if (!DoNotMoveItemToParentFromImport)
                        {
                            if (item.ParentID != parentItem.ID)
                            {
                                MoveItem(item, parentItem, ref updateItemLogger);
                            }
                        }
                        else
                        {
                            // When we do not move the item to it's importet parent, then we must set the parentItem to the currenct parent, to enable the validation of duplicate items names.
                            parentItem = item.Parent;
                        }

                        if (OnDuplicateItemNamesGeneratePostfixNumber)
                        {
                            string errorMessage = "";
                            var checkIfItemNameLogger = updateItemLogger.CreateLevelLogger();
                            var newItemName = CheckIfItemNameIsUniqueAndGeneratePostFixNumberIfNot(importRow, item, itemName, itemName, parentItem, 1, ref checkIfItemNameLogger);
                            if (checkIfItemNameLogger.HasErrors())
                            {
                                checkIfItemNameLogger.AddError("Error in 'CheckIfItemNameIsUniqueAndGeneratePostFixNumberIfNot'", String.Format(
                                         "The 'CheckIfItemNameIsUniqueAndGeneratePostFixNumberIfNot' method failed with an error. The itemname was not changed to a postfixnumber since the check failed. But the Update process was continued. ImportRow: {0}. ErrorMessage: {1}",
                                         GetImportRowDebugInfo(importRow), errorMessage));
                                logger.IncrementCounter(IncrementConstants.FailureItems);
                            }
                            if (!itemName.Equals(newItemName))
                            {
                                updateItemLogger.AddInfo("Item name regenerated", String.Format("The item name '{0}' was regenerated to '{1}' to avoid duplicate item name.", itemName, newItemName));
                                itemName = newItemName;
                                logger.IncrementCounter(IncrementConstants.ItemNameRegenerated);
                            }
                        }
                        if(OnDuplicateItemNamesGeneratePostfixNumber || UpdateItemName)
                        {
                            if (item.Name != itemName)
                            {
                                item.Editing.BeginEdit();
                                updateItemLogger.AddInfo("Item name updated", String.Format("The item name '{0}' was updated to '{1}'.", item.Name, itemName));
                                item.Name = itemName;
                                item.Editing.EndEdit();
                                logger.IncrementCounter(IncrementConstants.RenamedItems);
                            }
                        }

                        if (ValidateIfItemKeyIsUnique)
                        {
                            if (!IsItemNameUnique(parentItem, item, ref updateItemLogger))
                            {
                                // The validation of the item found that there exists more than one item under the parent with the same item key.
                                // We logged the error, but continue processing item. The duplicated item names must be corrected manually.
                                updateItemLogger.IncrementCounter(IncrementConstants.FailureItems);
                                return false;
                            }
                        }

                        // Change template if type has changed and we are not explicit told not to
                        if (!DoNotChangeTemplate && ToWhatTemplates.Count > 0)
                        {
                            string errorMessage = String.Empty;
                            var getToWhatLogger = updateItemLogger.CreateLevelLogger();
                            var toWhatTemplate = GetToWhatTemplateItem(importRow, ref getToWhatLogger);
                            if (getToWhatLogger.HasErrors())
                            {
                                getToWhatLogger.AddError("Failure in 'GetToWhatTemplateItem' method", String.Format(
                                        "The 'GetToWhatTemplateItem' method failed with an error. ImportRow: {0}. Therefor it was not possible to determine wheether the item template should change. The Change template process was aborted as well as the rest of the update item process. {1}",
                                        GetImportRowDebugInfo(importRow), errorMessage));
                                updateItemLogger.IncrementCounter(IncrementConstants.FailureItems);
                                return false;
                            }
                            if (toWhatTemplate != null)
                            {
                                var templateItem = toWhatTemplate as TemplateItem;
                                if (templateItem != null)
                                {
                                    if (item.TemplateID != toWhatTemplate.ID)
                                    {
                                        string fromTemplateDebugInfo = GetTemplateDebugInfo(item.Template);
                                        item.Editing.BeginEdit();
                                        item.ChangeTemplate(templateItem);
                                        updateItemLogger.AddInfo("Change Template",
                                            String.Format("Changed template from '{0}' to '{1}'.", fromTemplateDebugInfo,
                                                GetTemplateDebugInfo(item.Template)));
                                        item.Editing.EndEdit();
                                        updateItemLogger.IncrementCounter(IncrementConstants.ChangedTemplate);
                                    }
                                }
                            }
                            else
                            {
                                updateItemLogger.IncrementCounter(IncrementConstants.FailureItems);
                                return false;
                            }
                        }

                        // Add in the field mappings
                        var updatedFields = false;
                        var failedItem = false;
                        item.Editing.BeginEdit();

                        foreach (IBaseField fieldDefinition in FieldDefinitions)
                        {
                            var fieldLogger = updateItemLogger.CreateLevelLogger("Field");
                            string errorMessage = String.Empty;
                            var existingFieldNames = fieldDefinition.GetExistingFieldNames();
                            var fieldValueDelimiter = fieldDefinition.GetFieldValueDelimiter();
                            fieldLogger.AddKey("FieldName", fieldDefinition.GetNewItemField());
                            fieldLogger.AddKey("ImportRowFieldName", String.Join(fieldValueDelimiter, fieldDefinition.GetExistingFieldNames().ToArray()));

                            var getFieldLogger = fieldLogger.CreateLevelLogger();
                            IEnumerable<string> values = GetFieldValues(existingFieldNames, importRow, ref getFieldLogger);

                            if (getFieldLogger.HasErrors())
                            {
                                getFieldLogger.AddError("Error in extracting a value from a field", String.Format("An error occured in extracting the values from a specific field: '{0}' on the item: '{1}'. The processing of the item is aborted and no fields has been updated. ErrorMessage: {2}",
                                    fieldDefinition, GetItemDebugInfo(item), errorMessage));
                                updateItemLogger.IncrementCounter(IncrementConstants.FailureItems);
                                return false;
                            }
                            bool updateField;
                            var importValue = String.Join(fieldValueDelimiter, values.ToArray());
                            var fieldDefinitionLogger = fieldLogger.CreateLevelLogger();
                            fieldDefinition.FillField(this, importRow, ref item, importValue, out updateField, ref fieldDefinitionLogger);

                            if (fieldDefinitionLogger.HasErrors())
                            {
                                fieldDefinitionLogger.AddError("Error processing a field", String.Format("An error occured in processing a field on the item: '{0}'. The processing of the item in itself is not aborted and the rest of the fields has been processed.", GetItemDebugInfo(item)));
                                failedItem = true;
                            }
                            if (updateField)
                            {
                                fieldLogger.AddInfo("Update Field", String.Format("The field '{0}' was updated.", fieldDefinition.GetNewItemField()));
                                updatedFields = true;
                            }
                        }
                        if (updatedFields)
                        {
                            item.Editing.EndEdit();
                            updateItemLogger.AddInfo("Updated Field on Item", String.Format("The item had fields that were updated."));
                            updateItemLogger.IncrementCounter(IncrementConstants.UpdatedFields);
                        }
                        else
                        {
                            item.Editing.CancelEdit();
                        }
                        if (failedItem)
                        {
                            updateItemLogger.IncrementCounter(IncrementConstants.FailureItems);
                            return false;
                        }

                        // Calls the subclass method to handle custom fields and properties
                        bool processedCustomData;
                        if (!ProcessCustomData(ref item, importRow, out processedCustomData))
                        {
                            updateItemLogger.IncrementCounter(IncrementConstants.FailureItems);
                            return false;
                        }
                        if (processedCustomData)
                        {
                            updateItemLogger.AddInfo("Custom Data processed", String.Format("Custom data was processed on item."));
                            updateItemLogger.IncrementCounter(IncrementConstants.ProcessedCustomData);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                updateItemLogger.AddError("Exception occured in UpdateItem method", String.Format("An exception occured in UpdateItem. ImportRow: {0}. Item: {1}, ItemName: {2}, Exception: {3}", GetImportRowDebugInfo(importRow), GetItemDebugInfo(item), itemName, GetExceptionDebugInfo(ex)));
                updateItemLogger.IncrementCounter(IncrementConstants.FailureItems);
                return false;
            }
            return true;
        }
 protected virtual void MoveItemToDisabledFolder(Item item, ref LevelLogger logger)
 {
     item.Editing.BeginEdit();
     item.MoveTo(DisableItemsFolderItem);
     logger.IncrementCounter(IncrementConstants.DisabledItems);
     item.Editing.EndEdit();
 }
 protected virtual void MoveItem(Item item, Item targetParentItem, ref LevelLogger logger)
 {
     using (new SecurityDisabler())
     {
         item.Editing.BeginEdit();
         logger.AddInfo("Moved Item", String.Format("Moved item from '{0}' to '{1}'.", GetItemDebugInfo(item), GetItemDebugInfo(targetParentItem)));
         item.MoveTo(targetParentItem);
         item.Editing.EndEdit();
         //Logger.MovedItems += 1;
         logger.IncrementCounter(IncrementConstants.MovedItems);
     }
 }
        protected virtual void DisableItemsNotPresentInImport(ref LevelLogger logger)
        {
            var disableItemsLogger = logger.CreateLevelLogger("DisableItemsNotPresentInImport");
            try
            {
                if (DisableItemsFolderItem == null)
                {
                    disableItemsLogger.AddError("Error", "The 'Disable Items Folder' contained an ID, but the item was null. This setting must point to a folder to move disabled items to. This field must be set when the 'Disable Items Not Present In Import' is checked.");
                    return;
                }
                using (new SecurityDisabler())
                {
                    string errorMessage = String.Empty;
                    var importRows = GetImportData();
                    var itemsInSitecore = GetItemsByTemplate(Parent, ToWhatTemplates.Values.ToList(), ref disableItemsLogger);
                    var itemsKeyList = GetItemsKeyList(importRows, ref disableItemsLogger);
                    if (disableItemsLogger.HasErrors())
                    {
                        disableItemsLogger.AddError("Error", String.Format("In the DisableItemsNotPresentInImport method the GetItemsKeyList failed. The disabling process was terminated. {0}.", errorMessage));
                        return;
                    }

                    if (itemsInSitecore.Any())
                    {
                        foreach (var item in itemsInSitecore)
                        {
                            try
                            {
                                var field = item.Fields[IdentifyTheSameItemsByFieldDefinition.GetNewItemField()];
                                if (field != null)
                                {
                                    string keyValue = field.Value;
                                    if (!String.IsNullOrEmpty(keyValue))
                                    {
                                        if (!itemsKeyList.Contains(keyValue))
                                        {
                                            MoveItemToDisabledFolder(item, ref disableItemsLogger);
                                        }
                                    }
                                    else
                                    {
                                        disableItemsLogger.AddError("Error",
                                                        String.Format(
                                                            "In the method DisableItemsNotPresentInImport the field: '{0}' was found but was empty. This module assumes that all key field must be shared and contain a value. So please make the field shared or alter the module code :-). Item: '{1}'. itemsInSitecore: '{2}'.",
                                                            IdentifyTheSameItemsByFieldDefinition.GetNewItemField
                                                                (), GetItemDebugInfo(item), itemsInSitecore.Count));
                                        //Logger.FailedDisabledItems += 1;
                                        logger.IncrementCounter(IncrementConstants.FailedDisabledItems);
                                    }
                                }
                                else
                                {
                                    disableItemsLogger.AddError("Error", String.Format(
                                                                "In the method DisableItemsNotPresentInImport the field: '{0}' was not found. This field should be provided since it markes the identifyer of the item. Item: '{1}'. ItemsInSitecore: '{2}'.",
                                                                IdentifyTheSameItemsByFieldDefinition.GetNewItemField
                                                                    (), GetItemDebugInfo(item), itemsInSitecore.Count));
                                    //Logger.FailedDisabledItems += 1;
                                    logger.IncrementCounter(IncrementConstants.FailedDisabledItems);
                                }
                            }
                            catch (Exception ex)
                            {
                                disableItemsLogger.AddError("Error",
                                    String.Format(
                                        "An exception occured in Process method When Disabling Items Not Present In Import in foreach (var item in itemsInSitecore). Item: {0}. Exception: {1}",
                                        GetItemDebugInfo(item), GetExceptionDebugInfo(ex)));
                                //Logger.FailedDisabledItems += 1;
                                logger.IncrementCounter(IncrementConstants.FailedDisabledItems);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                disableItemsLogger.AddError("Error",
                    String.Format(
                        "An exception occured in Process method When Disabling Items Not Present In Import. Exception: {0}",
                        ex.Message));
            }
        }
        protected virtual bool CreateItem(object importRow, Item parent, ref Item item, string itemName, ref LevelLogger logger)
        {
            var createItemLogger = logger.CreateLevelLogger();
            try
            {
                if (string.IsNullOrEmpty(itemName))
                {
                    createItemLogger.AddError("Item name could not be parsed", String.Format(
                            "The item name could not be parsed for importRow: {0}. Therefor the item could not be created.",
                            GetImportRowDebugInfo(importRow)));
                    logger.IncrementCounter(IncrementConstants.FailureItems);
                    return false;
                }
                if (parent == null)
                {
                    createItemLogger.AddError("Parent is null", String.Format(
                            "The 'parent' parameter is null. Therefor the item could not be created. ImportRow: {0}.",
                            GetImportRowDebugInfo(importRow)));
                    logger.IncrementCounter(IncrementConstants.FailureItems);
                    return false;
                }
                if (!ToWhatTemplates.Any())
                {
                    createItemLogger.AddError("The 'Import To What Template' item is null", String.Format(
                            "The 'Import To What Template' item is null. ImportRow: {0}. Therefor the item could not be created.",
                            GetImportRowDebugInfo(importRow)));
                    logger.IncrementCounter(IncrementConstants.FailureItems);
                    return false;
                }
                string errorMessage = String.Empty;
                var getToWhatLogger = createItemLogger.CreateLevelLogger();
                CustomItemBase toWhatTemplate = GetToWhatTemplateItem(importRow, ref getToWhatLogger);
                if (getToWhatLogger.HasErrors())
                {
                    getToWhatLogger.AddError("The 'GetToWhatTemplateItem' failed", String.Format(
                            "The 'GetToWhatTemplateItem' method failed with an error. ImportRow: {0}. Therefor the item could not be created. {1}",
                            GetImportRowDebugInfo(importRow), errorMessage));
                    logger.IncrementCounter(IncrementConstants.FailureItems);
                    return false;
                }

                if (toWhatTemplate == null)
                {
                    logger.IncrementCounter(IncrementConstants.FailureItems);
                    return false;
                }

                using (new LanguageSwitcher(ImportToLanguageVersion))
                {
                    var template = toWhatTemplate as TemplateItem;
                    if (template != null)
                    {
                        var templateItem = template;
                        item = parent.Add(itemName, templateItem);
                    }
                    var whatTemplate = toWhatTemplate as BranchItem;
                    if (whatTemplate != null)
                    {
                        var branchItem = whatTemplate;
                        item = parent.Add(itemName, branchItem);
                    }
                }
                if (item == null)
                {
                    createItemLogger.AddError("Created item was null", String.Format("The new item created was null. ImportRow: {0}.", GetImportRowDebugInfo(importRow)));
                    logger.IncrementCounter(IncrementConstants.FailureItems);
                    return false;
                }
                logger.IncrementCounter("Created Items");
                var addItemToCacheLogger = createItemLogger.CreateLevelLogger();
                var keyValue = GetValueFromFieldToIdentifyTheSameItemsBy(importRow, ref addItemToCacheLogger);
                CachingManager.AddItemToCache(Parent, IdentifyTheSameItemsByFieldDefinition.GetNewItemField(), item, keyValue, ref addItemToCacheLogger);
                if (addItemToCacheLogger.HasErrors())
                {
                    addItemToCacheLogger.AddError("The 'AddItemToCache' failed in the CreateItem", String.Format(
                            "The 'AddItemToCache' method failed with an error. ImportRow: {0}. The item was created, but not added to the cache. {1}",
                            GetImportRowDebugInfo(importRow), errorMessage));
                    logger.IncrementCounter(IncrementConstants.FailureItems);
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                createItemLogger.AddError("Exception in CreateItem", String.Format(
                        "An exception occured in CreateItem. Exception: {0}",
                        GetExceptionDebugInfo(ex)));
                logger.IncrementCounter(IncrementConstants.FailureItems);
                return false;
            }
        }