예제 #1
0
        public void Migrate()
        {
            try
            {
                IndexCustodian.PauseIndexing();

                var stopWatch = new Stopwatch();
                stopWatch.Start();

                var database = Database.GetDatabase(_configuration.TargetDatabase);
                using (new DatabaseSwitcher(database))
                {
                    using (new Sitecore.SecurityModel.SecurityDisabler())
                    {
                        foreach (var root in _configuration.Roots)
                        {
                            _migrationHelper.MigrateRoot(root.SourceItemId);
                        }
                    }
                }

                stopWatch.Stop();

                Sitecore.Diagnostics.Log.Info(String.Format("[FieldMigrator] Migration Completed in {0}", stopWatch.Elapsed), this);
            }
            finally
            {
                IndexCustodian.ResumeIndexing();
            }
        }
예제 #2
0
        private bool ChangeTemplate(Item startItem, Item sourceTemplateItem, Item targetTemplateItem, StringBuilder sBuilder, bool @checked)
        {
            bool result = false;

            if (chkFastandFurious.Checked)
            {
                // https://blog.horizontalintegration.com/2016/02/12/disablers-disablers-disablers-disablers-a-lesson-in-mass-sitecore-updates/
                using (new SecurityDisabler())
                    using (new ProxyDisabler())
                        using (new DatabaseCacheDisabler())
                            using (new EventDisabler())
                                using (new BulkUpdateContext())
                                {
                                    try
                                    {
                                        sBuilder.AppendLine("ChangeTemplate Started In Fast And Furious way");
                                        // https://blog.krusen.dk/disable-indexing-temporarily-in-sitecore-7/
                                        IndexCustodian.PauseIndexing();
                                        ChangeTemplateExecute(startItem, sourceTemplateItem, targetTemplateItem, sBuilder);

                                        if (@checked)
                                        {
                                            foreach (Item item in startItem.Children)
                                            {
                                                ChangeTemplateExecute(item, sourceTemplateItem, targetTemplateItem, sBuilder);
                                            }
                                        }
                                    }
                                    finally
                                    {
                                        IndexCustodian.ResumeIndexing();
                                    }
                                }
            }
            else
            {
                sBuilder.AppendLine("ChangeTemplate Started In Slow and Steady way");
                // Process Main Item
                ChangeTemplateExecute(startItem, sourceTemplateItem, targetTemplateItem, sBuilder);

                if (@checked)
                {
                    foreach (Item item in startItem.Children)
                    {
                        ChangeTemplateExecute(item, sourceTemplateItem, targetTemplateItem, sBuilder);
                    }
                }
            }

            result = true;
            return(result);
        }
예제 #3
0
        /// <summary>
        ///     processes each field against the data provided by subclasses
        /// </summary>
        public string Process()
        {
            using (new Sitecore.Data.BulkUpdateContext())
            {
                Sitecore.Configuration.Settings.Indexing.Enabled = false;

                #region process

                IEnumerable <object> importItems;
                var removedItems = Enumerable.Empty <object>();
                IndexCustodian.PauseIndexing();
                try
                {
                    importItems = GetImportData();
                }
                catch (Exception ex)
                {
                    importItems = Enumerable.Empty <object>();
                    Log("Connection Error", ex.Message);
                }

                long line = 0;

                try
                {
                    //Loop through the data source
                    foreach (var importRow in importItems)
                    {
                        line++;

                        var newItemName = GetNewItemName(importRow);
                        if (string.IsNullOrEmpty(newItemName))
                        {
                            continue;
                        }

                        var thisParent = GetParentNode(importRow, newItemName);
                        if (thisParent.IsNull())
                        {
                            throw new NullReferenceException("The new item's parent is null");
                        }

                        CreateNewItem(thisParent, importRow, newItemName);
                    }
                }
                catch (Exception ex)
                {
                    Log("Error (line: " + line + ")", ex.Message);
                }

                if (!string.IsNullOrEmpty(MissingItemsQuery))
                {
                    try
                    {
                        removedItems = SyncDeletions();
                        line         = 0;
                        //Loop through the data source
                        foreach (var removeRow in removedItems)
                        {
                            line++;
                            var itemName = GetNewItemName(removeRow);
                            if (string.IsNullOrEmpty(itemName))
                            {
                                continue;
                            }

                            var thisParent = GetParentNode(removeRow, itemName);
                            if (thisParent.IsNull())
                            {
                                throw new NullReferenceException("The new item's parent is null");
                            }

                            RemoveItem(thisParent, removeRow, itemName);
                            Log("Removed Missing Item", itemName + " was removed from Sitecore");
                        }
                    }
                    catch (Exception ex)
                    {
                        Log("SyncDeletions Error (line: " + line + ")", ex.Message);
                    }
                }
                IndexCustodian.ResumeIndexing();

                var lineNumber = 0;
                if (!string.IsNullOrEmpty(HistorySnapshotQuery))
                {
                    try
                    {
                        TakeHistorySnapshot();
                    }
                    catch (Exception ex)
                    {
                        Log("TakeHistorySnapshot Error (line: " + lineNumber + ")", ex.Message);
                    }
                }

                //if no messages then you're good
                if (log.Length < 1 || !log.ToString().Contains("Error"))
                {
                    Log("Success", "the import completed successfully");
                }

                return(log.ToString());

                #endregion

                Sitecore.Configuration.Settings.Indexing.Enabled = true;
            }
        }
예제 #4
0
 public void ImportItems(DataItem dataItem)
 {
     IndexCustodian.PauseIndexing();
     _itemRepository.Add(dataItem);
     IndexCustodian.ResumeIndexing();
 }
예제 #5
0
        // TODO: while EventDisabler breaks template creation, see if you can find a way around that, maybe by raising the event manually or by manually sending it to the client: Sitecore.Context.ClientPage.SendMessage((object) this, $"template:added(id={template.ID})")
        /// <summary>
        /// Imports the templates in the given set by creating them in Sitecore
        /// </summary>
        /// <remarks>
        /// Note that item paths are used as unique identifiers for each template. Note that the import
        /// will not overwrite existing items
        /// </remarks>
        /// <param name="templates">The set of JSON templates to import</param>
        /// <param name="templateRoot">The root item to import all of the templates under</param>
        /// <returns></returns>
        public virtual bool ImportTemplates(List <JsonSitecoreTemplate> templates, Item templateRoot = null)
        {
            // get the root item to add the templates to
            templateRoot = templateRoot ?? GetTemplateRoot();

            var shouldPauseIndexing = false;

            if (SitecoreUMLConfiguration.Instance.DisableIndexingDuringImport)
            {
                shouldPauseIndexing = true;
                IndexCustodian.PauseIndexing();
            }

            try
            {
                // get the templates to be used when adding the new items
                var templateTemplate        = _database.GetTemplate(Sitecore.TemplateIDs.Template);
                var templateFolderTemplate  = _database.GetTemplate(Sitecore.TemplateIDs.TemplateFolder);
                var templateSectionTemplate = _database.GetTemplate(Sitecore.TemplateIDs.TemplateSection);
                var templateFieldTemplate   = _database.GetTemplate(Sitecore.TemplateIDs.TemplateField);

                // caches the added items by their original path (i.e. not the full Sitecore path) to boost
                //   performance while setting base templates
                var addedItemsCache = new Dictionary <string, Item>();


                using (new SecurityDisabler())
                    using (new DatabaseCacheDisabler())
                    {
                        // create the templates
                        foreach (var jsonTemplate in templates)
                        {
                            // 1. make the full Sitecore path to the template
                            var path = templateRoot.Paths.Path + jsonTemplate.Path;

                            // if the path already exists then log a message and move onto the next template
                            if (_database.GetItem(path) != null)
                            {
                                Log.Warn($"SitecoreUML Import Warning: Item with path '{path}' skipped as an item with that path already exists", this);
                                continue;
                            }

                            // 2. add the template and its parent folders (if necessary)
                            var templateItem = _database.CreateItemPath(path, templateFolderTemplate, templateTemplate);
                            addedItemsCache.Add(jsonTemplate.Path, templateItem);

                            // NOTE: adding the field section was moved into the add fields loop, due to the added support
                            //       for controlling field sections in UML documentation
                            //// 3. add a field section to the new template
                            //var templateSectionItem = templateItem.Add(SitecoreUMLConfiguration.Instance.DefaultFieldSectionName, templateSectionTemplate);
                            var addedTemplateSectionItems = new Dictionary <string, Item>();

                            // 4. add the fields to the new template
                            var standardValuesToAdd = new List <Tuple <ID, string> >();
                            foreach (var jsonField in jsonTemplate.Fields)
                            {
                                // if the field type name/alias is not recognized then log a message and skip it
                                if (!SitecoreUMLConfiguration.Instance.UmlFieldTypeAliases.ContainsKey(jsonField.FieldType))
                                {
                                    Log.Warn($"SitecoreUML Import Warning: Field type name or alias {jsonField.FieldType} was not recognized. Field {jsonField.Name} will be skipped for template {jsonTemplate.Name}.", this);
                                    continue;
                                }
                                // get the field type from the field type name/alias
                                var fieldType = SitecoreUMLConfiguration.Instance.UmlFieldTypeAliases[jsonField.FieldType];

                                // add/get the template section item
                                Item templateSectionItem;
                                var  templateSectionName = !string.IsNullOrEmpty(jsonField.SectionName)
                                ? jsonField.SectionName
                                : SitecoreUMLConfiguration.Instance.DefaultFieldSectionName;

                                if (addedTemplateSectionItems.ContainsKey(templateSectionName))
                                {
                                    templateSectionItem = addedTemplateSectionItems[templateSectionName];
                                }
                                else
                                {
                                    templateSectionItem = templateItem.Add(templateSectionName, templateSectionTemplate);
                                    addedTemplateSectionItems.Add(templateSectionName, templateSectionItem);
                                }

                                // add the field
                                var templateFieldItem =
                                    (TemplateFieldItem)templateSectionItem.Add(jsonField.Name, templateFieldTemplate);

                                // update the field based on the imported data
                                templateFieldItem.BeginEdit();

                                templateFieldItem.Sortorder = jsonField.SortOrder;
                                templateFieldItem.Type      = fieldType;
                                templateFieldItem.Title     = jsonField.Title;
                                templateFieldItem.Source    = jsonField.Source;

                                if (jsonField.Shared)
                                {
                                    templateFieldItem.InnerItem[TemplateFieldIDs.Shared] = "1";
                                }
                                if (jsonField.Unversioned)
                                {
                                    templateFieldItem.InnerItem[TemplateFieldIDs.Unversioned] = "1";
                                }

                                templateFieldItem.EndEdit();

                                // if set, add StandardValue to the list of those to be aded
                                if (jsonField.StandardValue != null)
                                {
                                    standardValuesToAdd.Add(
                                        new Tuple <ID, string>(templateFieldItem.ID, jsonField.StandardValue));
                                }
                            }

                            // 5. add the standard values item and set the values, if appropriate
                            if (!standardValuesToAdd.Any())
                            {
                                continue;
                            }

                            var standardValuesItem = new TemplateItem(templateItem).CreateStandardValues();
                            using (new EditContext(standardValuesItem))
                            {
                                foreach (var standardValueToAdd in standardValuesToAdd)
                                {
                                    standardValuesItem[standardValueToAdd.Item1] = standardValueToAdd.Item2;
                                }
                            }
                        }

                        // get the Standard Template, which will be the default base template (only added if no other base templates)
                        var standardTemplate      = _database.GetTemplate(Sitecore.TemplateIDs.StandardTemplate);
                        var standardTemplateIDStr = standardTemplate.ID.ToString();

                        // set the base templates
                        foreach (var jsonTemplate in templates)
                        {
                            Item item;
                            // if we skipped adding the item (already existed) then skip it here too
                            if (!addedItemsCache.TryGetValue(jsonTemplate.Path, out item))
                            {
                                continue;
                            }

                            string baseTemplatesFieldValue = null;
                            foreach (var baseTemplatePath in jsonTemplate.BaseTemplates)
                            {
                                Item baseTemplateItem;
                                // if the base template isn't newly added we still want to make it a base template
                                if (!addedItemsCache.TryGetValue(baseTemplatePath, out baseTemplateItem))
                                {
                                    baseTemplateItem = _database.GetItem(templateRoot.Paths.Path + baseTemplatePath);
                                }

                                baseTemplatesFieldValue = baseTemplatesFieldValue != null
                                ? $"{baseTemplatesFieldValue}|{baseTemplateItem.ID}"
                                : $"{baseTemplateItem.ID}";
                            }

                            // set the Base Templates field value
                            using (new EditContext(item))
                            {
                                item[Sitecore.FieldIDs.BaseTemplate] = baseTemplatesFieldValue ?? standardTemplateIDStr;
                            }
                        }
                    }
            }
            finally
            {
                if (shouldPauseIndexing)
                {
                    IndexCustodian.ResumeIndexing();
                }
            }

            return(true);
        }