private void RebuildIndex(ISearchIndex index, bool isRemoteIndex = false)
        {
            if (IndexCustodian.IsRebuilding(index))
            {
                WriteVerbose($"Skipping full index rebuild for {index.Name} because it's already running.");
                var job = Sitecore.Jobs.JobManager.GetJob($"{"Index_Update"}_IndexName={index.Name}");

                if (job == null || !AsJob)
                {
                    return;
                }

                WriteVerbose($"Background job existed: {job.Name}");
                WriteObject(job);
            }
            else
            {
                WriteVerbose($"Starting full index rebuild for {index.Name}.");
                var job = (isRemoteIndex) ? IndexCustodian.FullRebuildRemote(index) : IndexCustodian.FullRebuild(index);

                if (job == null || !AsJob)
                {
                    return;
                }

                WriteVerbose($"Background job created: {job.Name}");
                WriteObject(job);
            }
        }
示例#2
0
        public virtual void RebuildCognitiveIndexes()
        {
            List <string> cogIndexes = new List <string>();
            var           nodes      = Sitecore.Configuration.Factory.GetConfigNodes("contentSearch/configuration/indexes/index");

            foreach (XmlNode n in nodes)
            {
                var id = n.Attributes?["id"];
                if (id == null || !id.Value.StartsWith("cognitive"))
                {
                    continue;
                }

                var dbNode = n.SelectSingleNode("locations/crawler/Database");
                var value  = dbNode?.FirstChild?.InnerText;
                if (string.IsNullOrEmpty(value))
                {
                    continue;
                }

                cogIndexes.Add(value);
            }

            foreach (var dbName in cogIndexes)
            {
                var searchIndex = ContentSearch.GetIndex(GetCognitiveIndexName(dbName));
                IndexCustodian.FullRebuild(searchIndex);
            }
        }
示例#3
0
        protected virtual void UpdateIndex(BulkLoadContext context, ICollection <ItemChange> itemChanges,
                                           Database database, ISearchIndex index)
        {
            Job job = null;

            if (!context.ShouldUpdateIndex(index))
            {
                context.Log.Warn($"Skipping updating index '{index.Name}' because its empty.");
                return;
            }

            var touchedPercentage = (uint)Math.Ceiling((double)itemChanges.Count / Math.Max(1, index.Summary.NumberOfDocuments) * 100);

            if (context.IndexRebuildThresholdPercentage.HasValue &&
                touchedPercentage > context.IndexRebuildThresholdPercentage.Value)
            {
                context.Log.Info($"Rebuilding index '{index.Name}' because {touchedPercentage}% is changed.");
                job = IndexCustodian.FullRebuild(index);
            }
            else if (context.Destination != null &&
                     !itemChanges.Any(ic => ic.Deleted) &&   // Refresh doesn't do deletes.
                     context.IndexRefreshThresholdPercentage.HasValue &&
                     touchedPercentage > context.IndexRefreshThresholdPercentage.Value)
            {
                context.Log.Info($"Refreshing index '{index.Name}' from '{context.Destination.ItemPath}' because {touchedPercentage}% is changed.");
                job = IndexCustodian.Refresh(index, new SitecoreIndexableItem(database.GetItem(new ID(context.Destination.ItemId))));
            }
            else
            {
                var sitecoreIds = GetItemsToIndex(itemChanges, database);
                context.Log.Info($"Updating index '{index.Name}' with {sitecoreIds.Count} items.");
                job = IndexCustodian.IncrementalUpdate(index, sitecoreIds);
            }
            job.Wait();
        }
        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();
            }
        }
示例#5
0
        private void RebuildIndex(ISearchIndex index, bool isRemoteIndex = false)
        {
            if (IndexCustodian.IsRebuilding(index))
            {
                WriteVerbose($"Skipping full index rebuild for {index.Name} because it's already running.");
                var jobManager = TypeResolver.ResolveFromCache <IJobManager>();
                var job        = jobManager.GetJob($"Index_Update_IndexName={index.Name}");

                if (job == null || !AsJob)
                {
                    return;
                }

                WriteVerbose($"Background job existed: {job.Name}");
                WriteObject(job);
            }
            else
            {
                WriteVerbose($"Starting full index rebuild for {index.Name}.");
                var indexManager = TypeResolver.ResolveFromCache <IIndexManager>();
                var job          = indexManager.FullRebuild(index, isRemoteIndex);

                if (job == null || !AsJob)
                {
                    return;
                }

                WriteVerbose($"Background job created: {job.Name}");
                WriteObject(job);
            }
        }
        public override IEnumerable <TestingSearchResultItem> GetActiveTests(DataUri hostItemDataUri = null, string searchText = null, ID deviceId = null)
        {
            TestingSearch testingSearch      = new TestingSearch();
            ISearchIndex  testingSearchIndex = Sitecore.ContentTesting.ContentSearch.TestingSearch.GetTestingSearchIndex();

            if (testingSearchIndex == null)
            {
                return(Enumerable.Empty <TestingSearchResultItem>());
            }
            int num = 0;

            while (IndexCustodian.IsRebuilding(testingSearchIndex) && num < 10)
            {
                Thread.Sleep(200);
                num++;
            }
            if (hostItemDataUri != null)
            {
                testingSearch.HostItem = hostItemDataUri;
            }
            if (!string.IsNullOrEmpty(searchText))
            {
                testingSearch.SearchText = searchText;
            }
            if (deviceId != (ID)null)
            {
                testingSearch.DeviceId = deviceId;
            }
            return(testingSearch.GetRunningTests());
        }
        public void Run(ITaskOutput output, NameValueCollection metaData)
        {
            // Create the standard users
            CreateSecurityAccounts.CreateAccounts();

            // Rebuild the core and master indexes
            IndexCustodian.FullRebuild(ContentSearchManager.GetIndex("sitecore_core_index"), true);
            IndexCustodian.FullRebuild(ContentSearchManager.GetIndex("sitecore_master_index"), true);
        }
示例#8
0
        protected virtual void RemoveItemFromCaches(IItemMetadata metadata, string databaseName)
        {
            try
            {
                if (databaseName != Database.Name)
                {
                    return;
                }

                // this is a bit heavy handed, sure.
                // but the caches get interdependent stuff - like caching child IDs
                // that make it difficult to cleanly remove a single item ID from all cases in the cache
                // either way, this should be a relatively rare occurrence (from runtime changes on disk)
                // and we're preserving prefetch, etc. Seems pretty zippy overall.
                CacheManager.ClearAllCaches();

                if (metadata == null)
                {
                    return;
                }

                if (metadata.TemplateId == TemplateIDs.Template.Guid ||
                    metadata.TemplateId == TemplateIDs.TemplateField.Guid ||
                    (metadata.Path != null && metadata.Path.EndsWith("__Standard Values", StringComparison.OrdinalIgnoreCase)))
                {
                    Database.Engines.TemplateEngine.Reset();
                }

                if (_syncConfiguration != null && (_syncConfiguration.UpdateLinkDatabase || _syncConfiguration.UpdateSearchIndex))
                {
                    var item = GetSourceItemFromId(new ID(metadata.Id), true);

                    if (item == null)
                    {
                        return;
                    }

                    if (_syncConfiguration.UpdateLinkDatabase)
                    {
                        Globals.LinkDatabase.UpdateReferences(item);
                    }

                    if (_syncConfiguration.UpdateSearchIndex)
                    {
                        foreach (var index in ContentSearchManager.Indexes)
                        {
                            IndexCustodian.UpdateItem(index, new SitecoreItemUniqueId(item.Uri));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // we catch this because this method runs on a background thread. If an unhandled exception occurs there, the app pool terminates and that's Naughty(tm).
                Log.Error($"[Unicorn] Exception occurred while processing a background item cache removal on {metadata?.Path ?? "unknown item"}", ex, this);
            }
        }
        private void RefreshItem(ISearchIndex index, IIndexable indexable, string itemPath)
        {
            WriteVerbose($"Starting index rebuild for item {itemPath} in {index.Name}.");
            var job = IndexCustodian.Refresh(index, indexable);

            if (job != null && AsJob)
            {
                WriteVerbose($"Background job created: {job.Name}");
                WriteObject(job);
            }
        }
        private void DeleteItem(ISearchIndex index, IIndexableId indexableId, string itemPath)
        {
            WriteVerbose($"Removing item {itemPath} from index {index.Name}.");
            var job = IndexCustodian.DeleteItem(index, indexableId);

            if (job != null && AsJob)
            {
                WriteVerbose($"Background job created: {job.Name}");
                WriteObject(job);
            }
        }
示例#11
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);
        }
示例#12
0
        protected virtual void RemoveItemFromCaches(IItemMetadata metadata, string databaseName)
        {
            if (databaseName != Database.Name)
            {
                return;
            }

            // this is a bit heavy handed, sure.
            // but the caches get interdependent stuff - like caching child IDs
            // that make it difficult to cleanly remove a single item ID from all cases in the cache
            // either way, this should be a relatively rare occurrence (from runtime changes on disk)
            // and we're preserving prefetch, etc. Seems pretty zippy overall.
            Database.Caches.DataCache.Clear();
            Database.Caches.ItemCache.Clear();
            Database.Caches.ItemPathsCache.Clear();
            Database.Caches.PathCache.Clear();

            if (metadata == null)
            {
                return;
            }

            if (metadata.TemplateId == TemplateIDs.Template.Guid || metadata.TemplateId == TemplateIDs.TemplateField.Guid || metadata.Path.EndsWith("__Standard Values", StringComparison.OrdinalIgnoreCase))
            {
                Database.Engines.TemplateEngine.Reset();
            }

            if (_syncConfiguration.UpdateLinkDatabase || _syncConfiguration.UpdateSearchIndex)
            {
                var item = GetItemFromId(new ID(metadata.Id), true);

                if (item == null)
                {
                    return;
                }

                if (_syncConfiguration.UpdateLinkDatabase)
                {
                    Globals.LinkDatabase.UpdateReferences(item);
                }

                if (_syncConfiguration.UpdateSearchIndex)
                {
                    foreach (var index in ContentSearchManager.Indexes)
                    {
                        IndexCustodian.UpdateItem(index, new SitecoreItemUniqueId(item.Uri));
                    }
                }
            }
        }
示例#13
0
        protected virtual void UpdateSearchIndexes(Item[] items, ILogger logger)
        {
            logger?.Info("");
            logger?.Info("[I] Updating search indexes for changed items.");

            foreach (var index in ContentSearchManager.Indexes)
            {
                var changes = items.Select(change => new SitecoreItemUniqueId(change.Uri));

                IndexCustodian.IncrementalUpdate(index, changes);
            }

            logger?.Debug($"> Queued updates for {items.Length} items in the search indexes. Will run async.");
        }
示例#14
0
        void HandleTweet(ITweet tweet)
        {
            if ((from tag in tweet.Hashtags where tag.Text == HashtagTrigger select tag).Any())
            {
                Log.Info("Index rebuild triggered from Twitter by '{0}'".FormatWith(tweet.Creator.Name), this);
                CrawlingLog.Log.Info("Index rebuild triggered from Twitter by '{0}'".FormatWith(tweet.Creator.Name));

                if (IndexCustodian.IsIndexingPaused(m_index) || IndexCustodian.IsRebuilding(m_index))
                {
                    CrawlingLog.Log.Warn("Indexing call muted");
                    Log.Info("Indexing call muted", this);
                    return;
                }

                IndexCustodian.FullRebuild(m_index);
            }
        }
        public void RunPostDeployAction(XDocument deployedItems, IPostDeployActionHost host, string parameter)
        {
            string[] indexNames = this.GetContentSearchIndexes(parameter);
            foreach (var indexName in indexNames)
            {
                var index = ContentSearchManager.GetIndex(indexName.Trim());

                if (index == null)
                {
                    host.LogMessage("The Content Search Index with name {0} supplied does not exist.", indexName);
                    continue;
                }

                host.LogMessage("Rebuilding index {0}...", indexName);
                IndexCustodian.FullRebuild(index, true);
                host.LogMessage("Rebuild of index {0} complete", indexName);
            }
        }
        public override ConversationResponse Respond(LuisResult result, ItemContextParameters parameters, IConversation conversation)
        {
            var message = "";
            var index   = (string)conversation.Data[IndexKey];

            if (index == "All")
            {
                IndexCustodian.RebuildAll(new [] { IndexGroup.Experience });
                message = "All indexes are being rebuilt";
            }
            else
            {
                var searchIndex = ContentSearchWrapper.GetIndex(index);
                IndexCustodian.FullRebuild(searchIndex);
                message = $"The {index} index is being rebuilt";
            }

            return(ConversationResponseFactory.Create(message));
        }
示例#17
0
        public override ConversationResponse Respond(LuisResult result, ItemContextParameters parameters, IConversation conversation)
        {
            var message = "";
            var index   = (string)conversation.Data[IndexKey];

            if (index == AllOption)
            {
                IndexCustodian.RebuildAll(new [] { IndexGroup.Experience });
                message = Translator.Text("Chat.Intents.RebuildIndex.AllRebuiltMessage");
            }
            else
            {
                var searchIndex = ContentSearchWrapper.GetIndex(index);
                IndexCustodian.FullRebuild(searchIndex);
                message = string.Format(Translator.Text("Chat.Intents.RebuildIndex.RebuildIndexMessage"), index);
            }

            return(ConversationResponseFactory.Create(message));
        }
示例#18
0
 private void RebuildIndex()
 {
     try
     {
         var index = ContentSearchManager.GetIndex(_indexName);
         if (index != null)
         {
             IndexRebuilding.Visible = true;
             IndexCustodian.FullRebuild(index, true);
         }
         else
         {
             IndexNotFound.Visible = true;
         }
     }
     catch (Exception ex)
     {
         IndexRebuildError.Text    = ex.Message;
         IndexRebuildError.Visible = true;
     }
 }
示例#19
0
        public IHttpActionResult Rebuild([FromBody] string indexname)
        {
            if (!IsAuthenticated)
            {
                return(Unauthorized());
            }

            using (new UserSwitcher(Context.Site.Domain.GetFullName(this.ApiUser), false))
            {
                if (!Context.User.IsAdministrator)
                {
                    return(Unauthorized());
                }

                var index = ContentSearchManager.Indexes.SingleOrDefault(idx => idx.Name == indexname);

                var payload = new IndexingUpdate
                {
                    IndexName                = index.Name,
                    State                    = State.Started,
                    NumberOfDocuments        = index.Summary.NumberOfDocuments,
                    LastUpdated              = index.Summary.LastUpdated,
                    IndexRebuildMilliseconds = IndexHealthHelper.GetIndexRebuildTime(index.Name),
                    IndexRebuildTime         = IndexingEventHandler.BuildTime(index)
                };

                if (index.Group == IndexGroup.Experience || !ContentSearchManager.Locator.GetInstance <ISearchIndexSwitchTracker>().IsIndexOn(index.Name))
                {
                    payload.State = State.NotStarting;
                    return(new JsonResult <IndexingUpdate>(payload, new JsonSerializerSettings(), Encoding.UTF8, this));
                }
                else
                {
                    var job = IndexCustodian.FullRebuild(index, true);
                    payload.Job   = job.DisplayName;
                    payload.State = State.Started;
                    return(new JsonResult <IndexingUpdate>(payload, new JsonSerializerSettings(), Encoding.UTF8, this));
                }
            }
        }
示例#20
0
        private void RebuildIndex(string indexName)
        {
            try
            {
                Diagnostics.Log.Info(string.Format("Rebuilding index {0}", indexName), this);

                ISearchIndex index = ContentSearchManager.GetIndex(indexName);

                if (index != null)
                {
                    IndexCustodian.FullRebuild(index);

                    //while (IndexCustodian.IsRebuilding(index))
                    //{
                    //    Thread.Sleep(1000);
                    //}
                }
            }
            catch (Exception ex)
            {
                Diagnostics.Log.Error("Error Rebuilding Index", ex, this);
            }
        }
示例#21
0
        public IJob FullRebuild(ISearchIndex index, bool isRemote)
        {
            var job = (isRemote) ? IndexCustodian.FullRebuildRemote(index) : IndexCustodian.FullRebuild(index);

            return(job == null ? null : new SpeJob(job));
        }
 public void Run()
 {
     CrawlingLog.Log.Debug($"[Index={this.index.Name}] RemoteRebuildStrategy triggered.", null);
     IndexCustodian.FullRebuildRemote(this.index, true);
 }
        /// <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;
            }
        }
示例#24
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);
        }
示例#25
0
        public IJob DeleteItem(ISearchIndex index, IIndexableId indexableId)
        {
            var job = IndexCustodian.DeleteItem(index, indexableId);

            return(job == null ? null : new SpeJob(job));
        }
示例#26
0
        public IJob Refresh(ISearchIndex index, IIndexable indexable)
        {
            var job = IndexCustodian.Refresh(index, indexable);

            return(job == null ? null : new SpeJob(job));
        }
示例#27
0
 public void ImportItems(DataItem dataItem)
 {
     IndexCustodian.PauseIndexing();
     _itemRepository.Add(dataItem);
     IndexCustodian.ResumeIndexing();
 }
示例#28
0
 public virtual Job FullRebuild(ISearchIndex searchIndex)
 {
     return(IndexCustodian.FullRebuild(searchIndex));
 }
示例#29
0
        private void RebuildInxdexes([NotNull] string databaseName)
        {
            Debug.ArgumentNotNull(databaseName, nameof(databaseName));

            IndexCustodian.RebuildAll();
        }