public void CanUnderstandSimpleEquality() { var q = new DocumentQuery<IndexedUser>(null, null, "IndexName", null) .WhereEquals("Name", "ayende"); Assert.Equal("Name:[[ayende]]", q.ToString()); }
public void CanUnderstandSimpleContainsWithVariable() { var ayende = "ayende" + 1; var q = new DocumentQuery<IndexedUser>(null, null, "IndexName", null) .WhereContains("Name", ayende); Assert.Equal("Name:ayende1", q.ToString()); }
public void CanUnderstandGreaterThanOnInt() { // should DocumentQuery<T> understand how to generate range field names? var q = new DocumentQuery<IndexedUser>(null, null, "IndexName", null) .WhereGreaterThan("Age_Range", 3); Assert.Equal("Age_Range:{0x00000003 TO NULL}", q.ToString()); }
private static bool ValidatePreviewGuid(object value) { var identifier = ValidationHelper.GetGuid(value, Guid.Empty); var query = new DocumentQuery().WhereEquals("DocumentWorkflowCycleGUID", identifier); return query.HasResults(); }
public void CanUnderstandOr() { var q = new DocumentQuery<IndexedUser>(null, null, "IndexName", null) .WhereContains("Name", "ayende") .OrElse() .WhereContains("Email", "*****@*****.**"); Assert.Equal("Name:ayende OR Email:[email protected]", q.ToString()); }
private async Task DoSomething() { DocumentClient client = new DocumentClient(new Uri("docdb.documents.azure.com"), "xxx"); Database database = client.GetDatabaseReference("db"); if (!await database.ExistsAsync()) { await database.CreateAsync(); } DocumentCollection collection = client.GetCollectionReference("db", "coll"); if (!await collection.ExistsAsync()) { await collection.CreateAsync(new PartitioningPolicy { PartitionKeyName = "Artist" }, 1000); } Song song = new Song { Album = "IV", Artist = "Led Zeppelin", SongTitle = "Stairway to Heaven", Year = 1971 }; await collection.CreateDocumentAsync(song); song.Album = "Greatest Hits"; await collection.ReplaceDocumentAsync(song); Document readSong = await collection.ReadDocumentAsync("Led Zeppelin", "Stairway to Heaven"); await collection.DeleteDocumentAsync("Led Zeppelin", "Stairway to Heaven"); IQueryable<Song> query = new DocumentQuery<Song>().Where(s => s.Year == 1971).Take(10); await collection.ExecuteQueryAsync<Song>(query); FeedResponse<dynamic> results = await collection.ExecuteQuerySegmentedAsync<Song>(query); results = await collection.ExecuteQuerySegmentedAsync<Song>(query, new FeedOptions { RequestContinuation = results.ResponseContinuation }); await collection.UpdateThroughputAsync(500); await collection.StoredProcedures.CreateStoredProcedureAsync(new StoredProcedure { Id = "Aggregate", Body = "function() { ..}" }); }
public void CanUnderstandSimpleEqualityOnInt() { var q = new DocumentQuery<IndexedUser>(null, null, "IndexName", null) .WhereEquals("Age", 3, false); Assert.Equal("Age:3", q.ToString()); }
public IAdvancedQueryable <TEntity> WhereIn(string key, IEnumerable <object> values) { _queryable = DocumentQuery.WhereIn(key, values).ToQueryable(); return(this); }
public void CanUnderstandGreaterThan() { var q = new DocumentQuery<IndexedUser>(null, null, "IndexName", null) .WhereGreaterThan("Birthday", new DateTime(2010, 05, 15)); Assert.Equal("Birthday:{20100515000000000 TO NULL}", q.ToString()); }
public IAdvancedQueryable <TEntity> FuzzySearch(string key, string term, decimal fuzzyLevel = .5M) { _queryable = DocumentQuery.WhereEquals(key, term).Fuzzy(fuzzyLevel).ToQueryable(); return(this); }
public IAdvancedQueryable <TEntity> Include(Expression <Func <TEntity, object> > predicate) { _queryable = DocumentQuery.Include(predicate).ToQueryable(); return(this); }
public void CanUnderstandLessThanOrEqual() { var q = new DocumentQuery<IndexedUser>(null, null, "IndexName", null) .WhereLessThanOrEqual("Birthday", new DateTime(2010, 05, 15)); Assert.Equal("Birthday:[* TO 20100515000000000]", q.ToString()); }
public abstract T GetCount <T>(DocumentQuery query, DocumentMeta meta = null);
internal ResourceFeedReader(DocumentClient client, ResourceType resourceType, FeedOptions options, string resourceLink, object partitionKey = null) { this.documentQuery = new DocumentQuery <T>(client, resourceType, typeof(T), resourceLink, options, partitionKey); }
/// <summary> /// Gets the CMS Page using Dynamic Routing, returning the culture variation that either matches the given culture or the Slug's culture, or the default site culture if not found. /// </summary> /// <param name="Url">The Url (part after the domain), if empty will use the Current Request</param> /// <param name="Culture">The Culture, not needed if the Url contains the culture that the UrlSlug has as part of it's generation.</param> /// <param name="SiteName">The Site Name, defaults to current site.</param> /// <param name="Columns">List of columns you wish to include in the data returned.</param> /// <returns>The Page that matches the Url Slug, for the given or matching culture (or default culture if one isn't found).</returns> public static ITreeNode GetPage(string Url = "", string Culture = "", string SiteName = "", IEnumerable <string> Columns = null) { // Load defaults SiteName = (!string.IsNullOrWhiteSpace(SiteName) ? SiteName : DynamicRouteInternalHelper.SiteContextSafe().SiteName); string DefaultCulture = DynamicRouteInternalHelper.SiteContextSafe().DefaultVisitorCulture; if (string.IsNullOrWhiteSpace(Url)) { Url = EnvironmentHelper.GetUrl(HttpContext.Current.Request.Url.AbsolutePath, HttpContext.Current.Request.ApplicationPath, SiteName); } // Handle Preview, during Route Config the Preview isn't available and isn't really needed, so ignore the thrown exception bool PreviewEnabled = false; try { PreviewEnabled = PortalContext.ViewMode != ViewModeEnum.LiveSite; } catch (InvalidOperationException) { } GetCultureEventArgs CultureArgs = new GetCultureEventArgs() { DefaultCulture = DefaultCulture, SiteName = SiteName, Request = HttpContext.Current.Request, PreviewEnabled = PreviewEnabled, Culture = Culture }; using (var DynamicRoutingGetCultureTaskHandler = DynamicRoutingEvents.GetCulture.StartEvent(CultureArgs)) { // If culture not set, use the LocalizationContext.CurrentCulture if (string.IsNullOrWhiteSpace(CultureArgs.Culture)) { try { CultureArgs.Culture = LocalizationContext.CurrentCulture.CultureName; } catch (Exception) { } } // if that fails then use the System.Globalization.CultureInfo if (string.IsNullOrWhiteSpace(CultureArgs.Culture)) { try { CultureArgs.Culture = System.Globalization.CultureInfo.CurrentCulture.Name; } catch (Exception) { } } DynamicRoutingGetCultureTaskHandler.FinishEvent(); } // set the culture Culture = CultureArgs.Culture; // Convert Columns to string ColumnsVal = Columns != null?string.Join(",", Columns.Distinct()) : "*"; // Create GetPageEventArgs Event ARgs GetPageEventArgs Args = new GetPageEventArgs() { RelativeUrl = Url, Culture = Culture, DefaultCulture = DefaultCulture, SiteName = SiteName, PreviewEnabled = PreviewEnabled, ColumnsVal = ColumnsVal, Request = HttpContext.Current.Request }; // Run any GetPage Event hooks which allow the users to set the Found Page ITreeNode FoundPage = null; using (var DynamicRoutingGetPageTaskHandler = DynamicRoutingEvents.GetPage.StartEvent(Args)) { if (Args.FoundPage == null) { try { // Get Page based on Url Args.FoundPage = CacheHelper.Cache <TreeNode>(cs => { // Using custom query as Kentico's API was not properly handling a Join and where. DataTable NodeTable = ConnectionHelper.ExecuteQuery("DynamicRouting.UrlSlug.GetDocumentsByUrlSlug", new QueryDataParameters() { { "@Url", Url }, { "@Culture", Culture }, { "@DefaultCulture", DefaultCulture }, { "@SiteName", SiteName }, { "@PreviewEnabled", PreviewEnabled } }, topN: 1, columns: "DocumentID, ClassName").Tables[0]; if (NodeTable.Rows.Count > 0) { int DocumentID = ValidationHelper.GetInteger(NodeTable.Rows[0]["DocumentID"], 0); string ClassName = ValidationHelper.GetString(NodeTable.Rows[0]["ClassName"], ""); DocumentQuery Query = DocumentHelper.GetDocuments(ClassName) .WhereEquals("DocumentID", DocumentID); // Handle Columns if (!string.IsNullOrWhiteSpace(ColumnsVal)) { Query.Columns(ColumnsVal); } // Handle Preview if (PreviewEnabled) { Query.LatestVersion(true) .Published(false); } else { Query.PublishedVersion(true); } TreeNode Page = Query.FirstOrDefault(); // Cache dependencies on the Url Slugs and also the DocumentID if available. if (cs.Cached) { if (Page != null) { cs.CacheDependency = CacheHelper.GetCacheDependency(new string[] { "dynamicrouting.urlslug|all", "dynamicrouting.versionhistoryurlslug|all", "dynamicrouting.versionhistoryurlslug|bydocumentid|" + Page.DocumentID, "documentid|" + Page.DocumentID, }); } else { cs.CacheDependency = CacheHelper.GetCacheDependency(new string[] { "dynamicrouting.urlslug|all", "dynamicrouting.versionhistoryurlslug|all" }); } } // Return Page Data return(Query.FirstOrDefault()); } else { return(null); } }, new CacheSettings(1440, "DynamicRoutine.GetPage", Url, Culture, DefaultCulture, SiteName, PreviewEnabled, ColumnsVal)); } catch (Exception ex) { // Add exception so they can handle DynamicRoutingGetPageTaskHandler.EventArguments.ExceptionOnLookup = ex; } } // Finish event, this will trigger the After DynamicRoutingGetPageTaskHandler.FinishEvent(); // Return whatever Found Page FoundPage = DynamicRoutingGetPageTaskHandler.EventArguments.FoundPage; } return(FoundPage); }
public override List <T> ReadList <T>(DocumentQuery query) { throw new NotImplementedException(); }
public override T GetCount <T>(DocumentQuery query, DocumentMeta meta = null) { throw new NotImplementedException(); }
/// <summary> /// Returns the <see cref="DocumentQuery"/> ordered by <see cref="TreeNode.NodeOrder"/> /// </summary> /// <typeparam name="TNode"></typeparam> /// <param name="query">The current DocumentQuery</param> /// <returns></returns> public static DocumentQuery <TNode> OrderByNodeOrder <TNode>(this DocumentQuery <TNode> query) where TNode : TreeNode, new() => query.OrderBy(nameof(TreeNode.NodeOrder));
/// <summary> /// Returns the <see cref="DocumentQuery"/> filtered to a single Node with a <see cref="TreeNode.DocumentID"/> matching the provided value /// </summary> /// <typeparam name="TNode"></typeparam> /// <param name="query">The current DocumentQuery</param> /// <param name="documentID">Value of the <see cref="TreeNode.DocumentID" /> to filter by</param> /// <returns></returns> public static DocumentQuery <TNode> WhereDocumentIDEquals <TNode>(this DocumentQuery <TNode> query, int documentID) where TNode : TreeNode, new() => query.WhereEquals(nameof(TreeNode.DocumentID), documentID);
/// <summary> /// Returns the <see cref="DocumentQuery"/> filtered to a single Node with a <see cref="TreeNode.NodeGUID"/> matching the provided value /// </summary> /// <typeparam name="TNode"></typeparam> /// <param name="query">The current DocumentQuery</param> /// <param name="nodeGuid">Value of the <see cref="TreeNode.NodeGUID" /> to filter by</param> /// <returns></returns> public static DocumentQuery <TNode> WhereNodeGUIDEquals <TNode>(this DocumentQuery <TNode> query, Guid nodeGuid) where TNode : TreeNode, new() => query.WhereEquals(nameof(TreeNode.NodeGUID), nodeGuid);
public string GetJobs() { string resultCount = string.Empty; oJob = new RecuritingAPI(sEndpoint, sUser, sPass); Get_Job_Postings_RequestType oRequest = new Get_Job_Postings_RequestType(); WorkdayAPI.RecuritingService1.Response_FilterType oRespFilter = new WorkdayAPI.RecuritingService1.Response_FilterType(); Job_Posting_Response_GroupType oRespGroup = new Job_Posting_Response_GroupType(); Job_Posting_Site_Request_ReferencesType siteref = new Job_Posting_Site_Request_ReferencesType(); Job_Posting_SiteObjectType jobsiteObj = new Job_Posting_SiteObjectType(); Job_Posting_SiteObjectIDType ID = new Job_Posting_SiteObjectIDType(); // TODO: need to investigate the purpose of those values below and if we can move them into the appSettings ID.type = "WID"; ID.Value = "03ca6cbf24cc10fabe92ff4b5f82a0ac"; jobsiteObj.ID = new Job_Posting_SiteObjectIDType[1]; jobsiteObj.ID[0] = ID; siteref.Job_Posting_Site_Reference = new Job_Posting_SiteObjectType[1]; siteref.Job_Posting_Site_Reference[0] = jobsiteObj; Job_Posting_Request_CriteriaType criteria = new Job_Posting_Request_CriteriaType(); criteria.Job_Posting_Site_Reference = siteref.Job_Posting_Site_Reference; criteria.Show_Only_Active_Job_PostingsSpecified = true; criteria.Show_Only_Active_Job_Postings = true; oRequest.Request_Criteria = criteria; oRespFilter.Count = 999; oRespFilter.CountSpecified = true; oRequest.Response_Filter = oRespFilter; oRespGroup.Include_Reference = true; oRespGroup.Include_Job_Requisition_Restrictions_Data = true; oRespGroup.Include_Job_Requisition_Definition_Data = true; oRespGroup.Include_Qualifications = true; oRespGroup.Include_Job_Requisition_Attachments = false; oRequest.Response_Group = oRespGroup; Get_Job_Postings_ResponseType oResponse = oJob.GetJobPosting(oRequest, oRespFilter, oRespGroup); string jobsxml = XmlTools.ToXmlString(oResponse); jobsxml = jobsxml.Replace("utf-16", "utf-8"); xmlDocument = xmlDocument + DateTime.Now.Ticks + ".xml"; using (System.IO.StreamWriter file = new System.IO.StreamWriter(xmlDocument)) { file.Write(jobsxml); } XmlDocument doc = new XmlDocument(); doc.Load(xmlDocument); var nodes = doc.GetElementsByTagName("d1p1:Job_Posting_Data"); int jobsCreatedCount = 0; int jobsUpdatedCount = 0; int jobsErrorCount = 0; int jobsDeletedCount = 0; string jobsDeletedID = "", jobsUpdatedID = "", jobsErrorID = "", jobsCreatedID = ""; TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser); TreeNode parentNode = tree.SelectSingleNode(SiteContext.CurrentSiteName, "/Company/Jobs", "en-us"); DocumentQuery cmsjobs = DocumentHelper.GetDocuments("AT.Jobs") .Path("/Company/Jobs", PathTypeEnum.Children) .OnSite(SiteContext.CurrentSiteName); foreach (XmlNode xn in nodes) { var jobPostingID = xn.ChildNodes.Item(0).InnerText.ToString(); try { bool isJobInCMS = false; foreach (var jobs in cmsjobs) { string jobsID = jobs.GetValue("Job_Posting_ID").ToString(); if (jobsID.ToString().ToLower() == xn.ChildNodes.Item(0).InnerText.ToString().ToLower()) { if (parentNode != null) { var documents = DocumentHelper.GetDocuments() .Types("AT.Jobs") .Path("/Company/Jobs", PathTypeEnum.Children) .WhereLike("Job_Posting_ID", jobPostingID) .OnSite(SiteContext.CurrentSiteName) .Culture("en-us") .WithCoupledColumns(); if (!DataHelper.DataSourceIsEmpty(documents) && documents.Tables[0].Rows.Count == 1) { // Loop through all documents foreach (DataRow documentRow in documents.Tables[0].Rows) { // Create a new Tree node from the data row CMS.DocumentEngine.TreeNode editDocument = CMS.DocumentEngine.TreeNode.New("AT.Jobs", documentRow, tree); // Change coupled data SetNodeValue(xn, editDocument); editDocument.Update(); } } jobsUpdatedCount++; jobsUpdatedID += jobPostingID + "\r\n"; } isJobInCMS = true; break; } } if (!isJobInCMS) { if (parentNode != null) { // Create a new instance of the Tree node CMS.DocumentEngine.TreeNode newNode = CMS.DocumentEngine.TreeNode.New("AT.Jobs", tree); // Set the document's properties newNode.DocumentName = xn.ChildNodes.Item(1).InnerText; newNode.DocumentCulture = "en-us"; SetNodeValue(xn, newNode); newNode.Insert(parentNode); jobsCreatedCount++; jobsCreatedID += jobPostingID + "\r\n"; } else { EventLogProvider.LogInformation("No parent", "No parent", "Page can't be created as there is no parent page."); } } } catch (Exception ex) { jobsErrorCount++; jobsErrorID += jobPostingID + "\r\n"; } finally { CleanupXMLFIles(); } } string result = jobsCreatedCount + " Jobs were created and " + jobsUpdatedCount + " Jobs were updated and " + jobsDeletedCount + " Jobs were deleted and " + jobsErrorCount + " Jobs have errors."; string reportResults = String.Format("{0} \r\n\r\n========List of jobs created IDs========\r\n\r\n {1}\r\n========List of jobs updated IDs========\r\n\r\n {2}\r\n========List of jobs deleted IDs========\r\n\r\n {3}\r\n========List of jobs with error IDs========\r\n\r\n {4}", result, jobsCreatedID, jobsUpdatedID, jobsDeletedID, jobsErrorID); EventLogProvider.LogEvent(EventType.INFORMATION, "Workday", "Workday Import Report", reportResults); return(result); }
/// <summary> /// Sets in the Viewbag the CurrentDocument (TreeNode), CurrentSite (SiteInfo), and CurrentCulture (CultureInfo) /// </summary> /// <param name="DocumentID">The Document ID</param> /// <param name="CultureCode">The culture if you wish it to not be based on the found Document's</param> /// <param name="SiteName">The SiteName if you wish it to not be based on the Document's</param> public void SetContext(int DocumentID, string CultureCode = null, string SiteName = null) { TreeNode DocumentNodeForClass = new DocumentQuery().WhereEquals("DocumentID", DocumentID).FirstOrDefault(); TreeNode DocumentContext = null; if (DocumentNodeForClass != null) { // Set Page Builder Context HttpContext.Kentico().PageBuilder().Initialize(DocumentID); CacheableDocumentQuery RepeaterQuery = new CacheableDocumentQuery(DocumentNodeForClass.ClassName); RepeaterQuery.WhereEquals("DocumentID", DocumentID); RepeaterQuery.CacheItemNameParts.Add("documentid|" + DocumentID); if (EnvironmentHelper.PreviewEnabled) { RepeaterQuery.LatestVersion(true); RepeaterQuery.Published(false); } else { RepeaterQuery.PublishedVersion(true); } DocumentContext = RepeaterQuery.GetTypedResult().Items.FirstOrDefault(); } if (DocumentContext != null) { ViewBag.CurrentDocument = DocumentContext; if (string.IsNullOrWhiteSpace(SiteName)) { SiteName = DocumentContext.NodeSiteName; } if (string.IsNullOrWhiteSpace(CultureCode)) { CultureCode = DocumentContext.DocumentCulture; } } if (!string.IsNullOrWhiteSpace(SiteName)) { ViewBag.CurrentSite = CacheHelper.Cache <SiteInfo>(cs => { SiteInfo SiteObj = SiteInfoProvider.GetSiteInfo(SiteName); if (cs.Cached) { cs.CacheDependency = CacheHelper.GetCacheDependency("cms.site|byid|" + SiteObj.SiteID); } return(SiteObj); }, new CacheSettings(CacheHelper.CacheMinutes(SiteName), "GetSiteInfo", SiteName)); } if (!string.IsNullOrWhiteSpace(CultureCode)) { ViewBag.CurrentCulture = CacheHelper.Cache <CultureInfo>(cs => { CultureInfo CultureObj = CultureInfoProvider.GetCultureInfo(CultureCode); if (cs.Cached) { cs.CacheDependency = CacheHelper.GetCacheDependency(CultureInfo.TYPEINFO.ObjectClassName + "|byid|" + CultureObj.CultureID); } return(CultureObj); }, new CacheSettings(CacheHelper.CacheMinutes(SiteName), "GetCultureInfo", CultureCode));; } }
public async Task<IActionResult> Get(string id) { var query = new DocumentQuery(id); var document = await _messageDispatcher.Execute(query); return document != null ? (IActionResult) Json(document) : NotFound(); }
public static void OverrideGetPageEvent(object sender, GetPageEventArgs args) { string cultureCode = args.Culture; //Occasionally the culture code may come out as full text such as English - United Kingdom, using this info we can fetch the culture code if (args.Culture.Length > 5) { cultureCode = CultureInfoProvider.GetCultures().Where(a => a.CultureName == args.Culture).First().CultureCode; } UpdateCacheItem <string>("CurrentRelUrl", args.RelativeUrl); UpdateCacheItem <string>("CultureCode", cultureCode); if (args.FoundPage == null) { try { args.FoundPage = CacheHelper.Cache <TreeNode>(cs => { //TODO: ADD Culture DataTable PossibleUrlPatterns = GetPossibleUrls(args.RelativeUrl, cultureCode); if (PossibleUrlPatterns.Rows.Count > 0) { var matchedUrl = GetUrlMatch(args.RelativeUrl, cultureCode, PossibleUrlPatterns); if (matchedUrl == null || !matchedUrl.HasMatch) { return(null); } DocumentQuery Query = DocumentHelper.GetDocuments(matchedUrl.UrlBreakdown.KenticoData.ClassName).WhereEquals("NodeId", matchedUrl.UrlBreakdown.KenticoData.NodeId).CombineWithAnyCulture(); if (args.PreviewEnabled) { Query.LatestVersion(true).Published(false); } else { Query.PublishedVersion(true); } TreeNode page = Query.FirstOrDefault(); if (cs.Cached) { if (page != null) { cs.CacheDependency = CacheHelper.GetCacheDependency(new string[] { $"{WildcardUrlInfo.OBJECT_TYPE}|all", "documentid|" + page.DocumentID }); } else { cs.CacheDependency = CacheHelper.GetCacheDependency(new string[] { $"{WildcardUrlInfo.OBJECT_TYPE}dynamicrouting.wildcards|all" }); } } return(page); } else { return(null); } }, new CacheSettings(args.PreviewEnabled ? 0 : 1440, "DynamicRouting.GetPage", args.RelativeUrl, cultureCode, args.DefaultCulture, args.SiteName, args.PreviewEnabled, args.ColumnsVal)); } catch (Exception ex) { args.ExceptionOnLookup = ex; } if (args.FoundPage == null) { HttpContext.Current.Response.StatusCode = 404; } } }
public abstract int Delete <T>(DocumentQuery query);
protected override bool ActionBody(BaseProcess action) { bool isProcessed = true; IAction updateAction = null; try { Guid enterpriseId = GetValue <Guid>(ARG_PAGE_ENTERPRISE_ID); bool removeIsAbsent = GetValue <bool>(ARG_REMOVE_IS_ABSENT); var stockEntriesOutbound = GetValue <IEnumerable <Guid> >(ARG_STOCK_ENTRY_IDS); LocalContext.SaveLog( $"{MoscowDateTimeOffset().ToString()} Начало обработки ответов от системы Меркурий."); // Получение последнего номера шага IList <MercuryQueueStepModel> responses = StepService.GetStepsByStatus(QueryId, null, 0, "0.0", null); IList <MercuryQueueStepModel> completed = responses.Where(r => r.StatusName == MQSStatus.COMPLETE.ToString() && r.ProcessMark != Consts.PROCESSED_MARK).ToList(); bool anyError = responses.Any(x => x.StatusName != MQSStatus.COMPLETE.ToString()); List <Guid> updIds = GetValue <List <Guid> >(ARG_UPDATED_STOCK_ENTRY_IDS); List <Guid> skippedIds = GetValue <List <Guid> >(ARG_SKIPEED_STOCK_ENTRY_IDS); // Обработка успешных ответов if (completed.Count > 0) { foreach (MercuryQueueStepModel step in completed) { if (NeedStopSteps()) { LocalContext.SaveLog( $" Выполннение прервано (StopQueueSteps). Выполнение будет продолжено после запуска очереди."); SetValue("Status", MQSStatus.STOPPED); return(true); } MercuryNS.Body body = ParseMercuryHelper.ParseBodyResponseFile(Path.Combine(MercurySettings.ResponseDirectory, step.FileResponse)); if (body.ReceiveApplicationResultResponse != null && body.ReceiveApplicationResultResponse.Application != null) { MercuryNS.GetStockEntryListResponse response = body.ReceiveApplicationResultResponse.Application.Result as MercuryNS.GetStockEntryListResponse; MercuryNS.StockEntryList stockEntriesFromMerc = response?.StockEntryList; if (stockEntriesFromMerc != null && stockEntriesFromMerc.Count > 0) { LocalContext.SaveLog( $" Обработка файла ответа от Меркурия. Имя файла {step.FileResponse}."); var queryForPullStockEntryGuids = new DocumentQuery(GetService <IMethaStorage>(), GetService <IQueryGenerator>(), GetService <ICacheManager>()); queryForPullStockEntryGuids .ResultField("SE", "@Id") .ResultField("SE", "GUID") .Using("StockEntry", "SE", ObjectStatus.osActive); queryForPullStockEntryGuids.Where(w => w.Or(o => { foreach (var seId in stockEntriesOutbound) { o.EQ("@Id", seId); } })); var seOutboundIds = LocalReader.QueryDocuments(queryForPullStockEntryGuids).Result.Select(d => d["GUID"]); var stockEntriesFromMip = LoadStockEntriesFromMIP(stockEntriesFromMerc); foreach (var se in stockEntriesFromMerc.Where(d => seOutboundIds.Contains(d.GUID))) { var seFromMIP = stockEntriesFromMip.FirstOrDefault(d => (string)d["GUID"] == (string)se.GUID); if ((double)se.Batch.Volume < (double)seFromMIP["Volume"]) { isProcessed = false; LocalContext.SaveLog( $" Выписка уже производилась"); } if ((string)se.UUID != (string)seFromMIP["UUID"]) { isProcessed = false; LocalContext.SaveLog( $" Выписка уже производилась"); } } } else { LocalContext.SaveLog( $" Файл ответа {step.FileResponse} от системы 'Меркурий' не содержит информацию о складских записях."); } } else { anyError = true; body.Fault.ToString(); // TODO сохранить ошибку в логе //body.Fault ResultDescription = "Система 'Меркурий' вернула исключение"; } } } else { isProcessed = false; ResultDescription = "Нет успешно обработанных ответов"; LocalContext.SaveLog(ResultDescription); } var notCompleted = responses.Where(r => r.StatusName != MQSStatus.COMPLETE.ToString()); foreach (var nc in notCompleted) { AppendUserErrorInfoFromXML(nc, Guid.Empty, null, null); } if (string.IsNullOrWhiteSpace(ResultDescription)) { ResultDescription = "Обработаны ответы от системы 'Меркурий'."; } } catch (ConcurrencyDocException except) { isProcessed = false; DefaultConcurrentExceptionLog(except); } catch (Exception e) { AppendUserErrorInfo(Guid.Empty, null, UserErrorConsts.ET_MIP, UserErrorConsts.StockList.RTE_PROCESS_RESPONSE, UserErrorConsts.DEFAULT_LAS_SUPPRT_ERROR); isProcessed = false; LocalContext.SaveLog(e.ToString()); ResultDescription = "Ошибка анализа результатов"; } LocalContext.SaveLog( $"{MoscowDateTimeOffset().ToString()} Окончание обработки ответов от системы 'Меркурий'."); return(isProcessed); }
public virtual T ReadAnyCacheOfFromQuery <T>(DocumentQuery query) { if (!query.HasCacheOf) { return(default);
/// <summary> /// Begins the work. /// </summary> protected override void BeginWork() { BootParameters.ShouldNotBe(null); base.BeginWork(); _jobParameter = (DocumentQuery)XmlUtility.DeserializeObject(BootParameters, typeof(DocumentQuery)); }
public IAdvancedQueryable <TEntity> FuzzySearch(Expression <Func <TEntity, string> > expression, string term, decimal fuzzyLevel = .5M) { _queryable = DocumentQuery.WhereEquals(expression, term).Fuzzy(fuzzyLevel).ToQueryable(); return(this); }
private void SetupControl() { pageTree.LineImagesFolder = "~/CMSModules/RelationshipsExtended/Controls/RelatedCategories_Files"; pageTree.NodeStyle.CssClass = "InputNode"; pageTree.ShowLines = true; // Build a list of the pages var docQuery = new DocumentQuery().OrderBy("NodeLevel, NodeOrder"); foreach (string Path in StartingPathArray) { docQuery.Path(Path, PathTypeEnum.Section); } if (!string.IsNullOrWhiteSpace(RelatedNodeSiteName)) { docQuery.OnSite(RelatedNodeSiteName); } List <CMS.DocumentEngine.TreeNode> Nodes = docQuery.TypedResult.ToList(); // Get existing selected nodes string where = string.Format("NodeClassID in (select ClassID from CMS_Class where ClassName in ('{0}'))", string.Join("','", AllowedPageTypes.Split(";| ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries))); // Split off Where condition for if they provide a Where to filter out other items. string AdditionalWhere = where; // Filter to show items not already selected if (ddlCurrentNodeDirection.SelectedValue == "LeftNode") { where = SqlHelper.AddWhereCondition(where, string.Format("({0})", string.Format("NodeID in (Select RightNodeID from CMS_Relationship where LeftNodeID = {1} and RelationshipNameID in (Select RelationshipNameID from CMS_RelationshipName where RelationshipName = '{0}'))", RelationshipName, CurrentNodeID))); } else { where = SqlHelper.AddWhereCondition(where, string.Format("({0})", string.Format("NodeID in (Select LeftNodeID from CMS_Relationship where RightNodeID = {1} and RelationshipNameID in (Select RelationshipNameID from CMS_RelationshipName where RelationshipName = '{0}'))", RelationshipName, CurrentNodeID))); } where = SqlHelper.AddWhereCondition(where, string.Format("NodeID <> {0}", CurrentNodeID)); AlreadySelectedNodes = new DocumentQuery().Where(where).Columns("NodeID").Select(x => x.NodeID).ToList(); // Exclude the current node, can't relate a node to itself. AlreadySelectedNodes.Add(CurrentNodeID); // If the WhereCondition is set, also add any Nodes that match this to "Already selected" so they can't be selected // Filter on the where condition if given FilterSelectableNodes = false; List <int> VisibleNodes = new List <int>(); if (!string.IsNullOrWhiteSpace(WhereCondition)) { AdditionalWhere = SqlHelper.AddWhereCondition(AdditionalWhere, WhereCondition); FilterSelectableNodes = true; SelectableSelectedNodes.AddRange(new DocumentQuery().Where(AdditionalWhere).Columns("NodeID").Select(x => x.NodeID).ToList()); } pageTree.Nodes.Clear(); TreeNode RootNode = new TreeNode("[Tree Root]", "0") { SelectAction = TreeNodeSelectAction.None }; Dictionary <int, TreeNode> NodeIDToTreeNode = new Dictionary <int, TreeNode>(); NodeIDToTreeNode.Add(0, RootNode); // Build the tree for (int i = 0; i < Nodes.Count(); i++) { var Node = Nodes[i]; // Skip Root node if (string.IsNullOrWhiteSpace(Node.NodeName)) { continue; } TreeNode newNode = CreateTreeNode(Node); if (!NodeIDToTreeNode.ContainsKey(Node.NodeID)) { NodeIDToTreeNode.Add(Node.NodeID, newNode); } // Add to the parent if it exists, if it doesn't then add to root. if (NodeIDToTreeNode.ContainsKey(Node.NodeParentID)) { NodeIDToTreeNode[Node.NodeParentID].ChildNodes.Add(newNode); } else { NodeIDToTreeNode[0].ChildNodes.Add(newNode); } } if (RemoveUnselectableChildTrees) { HideUnselectableChildren(RootNode); } // Add root pageTree.Nodes.Add(RootNode); if (SelectionMode == "Checkbox") { btnAdd.Visible = true; } else { btnAdd.Visible = false; pageTree.SelectedNodeChanged += PageTree_SelectedNodeChanged; } }
public IAdvancedQueryable <TEntity> WhereEquals(string key, object value) { _queryable = DocumentQuery.WhereEquals(key, value).ToQueryable(); return(this); }
public void NoOpShouldProduceEmptyString() { var q = new DocumentQuery <IndexedUser>(null, null, "IndexName", null); Assert.Equal("", q.ToString()); }
public IAdvancedQueryable <TEntity> WhereBetween(string key, object lessValue, object greaterValue) { _queryable = DocumentQuery.WhereBetween(key, lessValue, greaterValue).ToQueryable(); return(this); }
public static List <long> QueryDocuments(Application app, string documentsDir) { logger.Info("Execute document query..."); List <long> documentIdList = new List <long>(); string filePath = documentsDir + "\\query.json"; if (File.Exists(filePath)) { logger.Info("Query File found: " + filePath); string inputJSON = File.ReadAllText(filePath); IList <JToken> jTokens = JToken.Parse(inputJSON)["contents"].Children().ToList(); foreach (JToken jToken in jTokens) { Content content = jToken.ToObject <Content>(); DocumentType documentType = app.Core.DocumentTypes.Find(content.documentType); if (documentType == null) { throw new Exception("Document type was not found"); } DocumentQuery documentQuery = app.Core.CreateDocumentQuery(); documentQuery.AddDisplayColumn(DisplayColumnType.AuthorName); documentQuery.AddDisplayColumn(DisplayColumnType.DocumentDate); documentQuery.AddDisplayColumn(DisplayColumnType.ArchivalDate); documentQuery.AddDocumentType(documentType); KeywordRecordType keywordRecordType = documentType.KeywordRecordTypes[0]; foreach (var kt in keywordRecordType.KeywordTypes) { if (content.keywords.ContainsKey(kt.Name)) { switch (kt.DataType) { case KeywordDataType.AlphaNumeric: documentQuery.AddKeyword(kt.CreateKeyword(content.keywords[kt.Name])); break; case KeywordDataType.Currency: case KeywordDataType.SpecificCurrency: case KeywordDataType.Numeric20: documentQuery.AddKeyword(kt.CreateKeyword(decimal.Parse(content.keywords[kt.Name]))); break; case KeywordDataType.Date: case KeywordDataType.DateTime: documentQuery.AddKeyword(kt.CreateKeyword(DateTime.Parse(content.keywords[kt.Name]))); break; case KeywordDataType.FloatingPoint: documentQuery.AddKeyword(kt.CreateKeyword(double.Parse(content.keywords[kt.Name]))); break; case KeywordDataType.Numeric9: documentQuery.AddKeyword(kt.CreateKeyword(long.Parse(content.keywords[kt.Name]))); break; } } } using (QueryResult queryResults = documentQuery.ExecuteQueryResults(long.MaxValue)) { logger.Info("Number of " + content.documentType + " Documents Found: " + queryResults.QueryResultItems.Count().ToString()); foreach (QueryResultItem queryResultItem in queryResults.QueryResultItems) { if (!documentIdList.Contains(queryResultItem.Document.ID)) { documentIdList.Add(queryResultItem.Document.ID); } logger.Info(string.Format("Document ID: {0}", queryResultItem.Document.ID.ToString())); logger.Info(string.Format("Author: {0}, Document Date: {1}, Archival Date: {2}", queryResultItem.DisplayColumns[0].Value.ToString(), DateTime.Parse(queryResultItem.DisplayColumns[1].Value.ToString()).ToShortDateString(), DateTime.Parse(queryResultItem.DisplayColumns[2].Value.ToString()).ToShortDateString())); foreach (var keyword in queryResultItem.Document.KeywordRecords[0].Keywords) { logger.Info(keyword.KeywordType.Name + " : " + keyword.Value.ToString()); } logger.Info(""); } } } } logger.Info(""); return(documentIdList); }
public void CanUnderstandProjectionOfMultipleFields() { var q = new DocumentQuery<IndexedUser>(null, null, "IndexName", null) .WhereGreaterThanOrEqual("Birthday", new DateTime(2010, 05, 15)) .SelectFields<IndexedUser>("Name", "Age"); string fields = q.ProjectionFields.Any() ? "<" + String.Join(", ", q.ProjectionFields.ToArray()) + ">: " : ""; Assert.Equal("<Name, Age>: Birthday:[20100515000000000 TO NULL]", fields + q.ToString()); }
public override int Delete <T>(DocumentQuery query) { throw new NotImplementedException(); }
private void ProcessTask_After(object sender, StagingSynchronizationEventArgs e) { if (e.TaskType == TaskTypeEnum.UpdateDocument) { // First table is the Node Data DataTable NodeTable = e.TaskData.Tables[0]; if (NodeTable != null && NodeTable.Columns.Contains("NodeGuid")) { // Get node ID TreeNode NodeObj = new DocumentQuery().WhereEquals("NodeGUID", NodeTable.Rows[0]["NodeGuid"]).FirstOrDefault(); // Don't want to trigger updates as we set the data in the database, so we won't log synchronziations using (new CMSActionContext() { LogSynchronization = false, LogIntegration = false }) { #region "Node Baz (Node object w/out Ordering)" // Get NodeBaz and Handle List <int> BazIDs = RelHelper.NewBoundObjectIDs(e, "demo.nodebaz", "NodeID", "BazID", BazInfo.TYPEINFO); NodeBazInfoProvider.GetNodeBazes().WhereEquals("NodeID", NodeObj.NodeID).WhereNotIn("BazID", BazIDs).ForEachObject(x => x.Delete()); List <int> CurrentBazIDs = NodeBazInfoProvider.GetNodeBazes().WhereEquals("NodeID", NodeObj.NodeID).Select(x => x.BazID).ToList(); foreach (int NewBazID in BazIDs.Except(CurrentBazIDs)) { NodeBazInfoProvider.AddTreeToBaz(NodeObj.NodeID, NewBazID); } #endregion #region "Node Region (Node object w/out Ordering)" // Get NodeRegion and Handle List <int> RegionCategoryIDs = RelHelper.NewBoundObjectIDs(e, "demo.nodeRegion", "NodeID", "RegionCategoryID", CategoryInfo.TYPEINFO); NodeRegionInfoProvider.GetNodeRegions().WhereEquals("NodeID", NodeObj.NodeID).WhereNotIn("RegionCategoryID", RegionCategoryIDs).ForEachObject(x => x.Delete()); List <int> CurrentRegionCategoryIDs = NodeRegionInfoProvider.GetNodeRegions().WhereEquals("NodeID", NodeObj.NodeID).Select(x => x.RegionCategoryID).ToList(); foreach (int NewRegionCategoryID in RegionCategoryIDs.Except(CurrentRegionCategoryIDs)) { NodeRegionInfoProvider.AddTreeToCategory(NodeObj.NodeID, NewRegionCategoryID); } #endregion #region "Node Foo (Node object with Ordering)" // Get NodeFoo and Handle List <int> FooIDInOrders = RelHelper.NewOrderedBoundObjectIDs(e, "demo.nodeFoo", "NodeID", "FooID", "NodeFooOrder", FooInfo.TYPEINFO); NodeFooInfoProvider.GetNodeFoos().WhereEquals("NodeID", NodeObj.NodeID).WhereNotIn("FooID", FooIDInOrders).ForEachObject(x => x.Delete()); List <int> CurrentFooIDs = NodeFooInfoProvider.GetNodeFoos().WhereEquals("NodeID", NodeObj.NodeID).Select(x => x.FooID).ToList(); foreach (int NewFooID in FooIDInOrders.Except(CurrentFooIDs)) { NodeFooInfoProvider.AddTreeToFoo(NodeObj.NodeID, NewFooID); } // Now handle the ordering for (int FooIndex = 0; FooIndex < FooIDInOrders.Count; FooIndex++) { int FooID = FooIDInOrders[FooIndex]; NodeFooInfo CurrentObj = NodeFooInfoProvider.GetNodeFooInfo(NodeObj.NodeID, FooID); if (CurrentObj != null && CurrentObj.NodeFooOrder != (FooIndex + 1)) { CurrentObj.SetObjectOrder(FooIndex + 1); } } #endregion } if (RelHelper.IsStagingEnabled(NodeObj.NodeSiteID)) { // Check if we need to generate a task for a server that isn't the origin server RelHelper.CheckIfTaskCreationShouldOccur(NodeObj.NodeGUID); } } else if (NodeTable == null || !NodeTable.Columns.Contains("NodeGuid")) { EventLogProvider.LogEvent("E", "DemoProcessTask", "No Node Table Found", eventDescription: "First Table in the incoming Staging Task did not contain the Node GUID, could not processes."); } } }
/// <summary> /// Saves relationship. /// </summary> public void SaveRelationship() { if (TreeNode == null) { return; } // Check modify permissions if (MembershipContext.AuthenticatedUser.IsAuthorizedPerDocument(TreeNode, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Denied) { return; } bool currentNodeIsOnLeftSide = !DefaultSide; // Selected node Id int selectedNodeId = ValidationHelper.GetInteger(hdnSelectedNodeId.Value, 0); if (BindOnPrimaryNodeOnly) { selectedNodeId = RelHelper.GetPrimaryNodeID(selectedNodeId); } var relationshipName = RelationshipName; var relationshipNameInfo = RelationshipNameInfo.Provider.Get(relationshipName); int relationshipNameId; if (relationshipNameInfo != null) { relationshipNameId = relationshipNameInfo.RelationshipNameId; } else { throw new NullReferenceException("[RelatedDocuments.SaveRelationship]: Missing relationship name to use for relation."); } if ((selectedNodeId <= 0) || (relationshipNameId <= 0)) { return; } try { // Test to make sure the selected page is a Right Side macro-allowed page or left side, and also matches the Page type limiter var SelectedTreeNode = (AllowAllTypes ? new DocumentQuery() : new DocumentQuery(AllowedPageTypes)).WhereEquals("NodeID", selectedNodeId).FirstOrDefault(); // If null probably not an allowed page type, but we will need it to validate below if (SelectedTreeNode == null) { SelectedTreeNode = new DocumentQuery().WhereEquals("NodeID", selectedNodeId).FirstOrDefault(); } var CurrentPageMacroResolver = MacroResolver.GetInstance(); CurrentPageMacroResolver.SetNamedSourceData("CurrentDocument", TreeNode); var PageMacroResolver = MacroResolver.GetInstance(); PageMacroResolver.SetNamedSourceData("CurrentDocument", SelectedTreeNode); // Left side if (currentNodeIsOnLeftSide) { if (!AllowAllTypes && !ClassNames.Contains(SelectedTreeNode.ClassName.ToLower())) { AddError(ResHelper.LocalizeExpression("RelatedPages.BadPageType")); } else if (!ValidationHelper.GetBoolean(CurrentPageMacroResolver.ResolveMacros(IsLeftSideMacro), false) || !ValidationHelper.GetBoolean(PageMacroResolver.ResolveMacros(IsRightSideMacro), false)) { AddError(ResHelper.LocalizeExpression("RelatedPages.LeftSideRightSideInvalid")); } else if (TreeNode.NodeID == SelectedTreeNode.NodeID) { AddError(ResHelper.LocalizeExpression("RelatedPages.CannotSelectSelf")); } else { RelationshipInfo.Provider.Add(TreeNode.NodeID, selectedNodeId, relationshipNameId); if (RelHelper.IsStagingEnabled()) { // Log synchronization DocumentSynchronizationHelper.LogDocumentChange(TreeNode.NodeSiteName, TreeNode.NodeAliasPath, TaskTypeEnum.UpdateDocument, TreeProvider); } ShowConfirmation(GetString("relationship.wasadded")); } } // Right side else { if (!AllowAllTypes && !ClassNames.Contains(SelectedTreeNode.ClassName.ToLower())) { AddError(ResHelper.LocalizeExpression("RelatedPages.BadPageType")); } else if (!ValidationHelper.GetBoolean(CurrentPageMacroResolver.ResolveMacros(IsLeftSideMacro), false) || !ValidationHelper.GetBoolean(PageMacroResolver.ResolveMacros(IsRightSideMacro), false)) { AddError(ResHelper.LocalizeExpression("RelatedPages.LeftSideRightSideInvalid")); } else if (TreeNode.NodeID == SelectedTreeNode.NodeID) { AddError(ResHelper.LocalizeExpression("RelatedPages.CannotSelectSelf")); } else { RelationshipInfo.Provider.Add(selectedNodeId, TreeNode.NodeID, relationshipNameId); if (RelHelper.IsStagingEnabled()) { // Log synchronization DocumentSynchronizationHelper.LogDocumentChange(TreeNode.NodeSiteName, SelectedTreeNode.NodeAliasPath, TaskTypeEnum.UpdateDocument, TreeProvider); } ShowConfirmation(GetString("relationship.wasadded")); } } } catch (Exception ex) { ShowError(ex.Message); } }
public void NoOpShouldProduceEmptyString() { var q = new DocumentQuery<IndexedUser>(null, null, "IndexName", null); Assert.Equal("", q.ToString()); }
public abstract T Read <T>(DocumentQuery query, DocumentMeta meta = null);
public void CanUnderstandEqualOnDate() { var q = new DocumentQuery<IndexedUser>(null, null, "IndexName", null) .WhereEquals("Birthday", new DateTime(2010, 05, 15)); Assert.Equal("Birthday:20100515000000000", q.ToString()); }
public abstract List <T> ReadList <T>(DocumentQuery query);
/// <summary> /// Begins the work. /// </summary> protected override void BeginWork() { BootParameters.ShouldNotBe(null); base.BeginWork(); _jobParameter =(DocumentQuery)XmlUtility.DeserializeObject(BootParameters, typeof(DocumentQuery)); }
private void UrlSlug_Update_Before_IsCustomRebuild(object sender, ObjectEventArgs e) { UrlSlugInfo UrlSlug = (UrlSlugInfo)e.Object; TreeNode Node = new DocumentQuery() .WhereEquals("NodeID", UrlSlug.UrlSlugNodeID) .Columns("NodeSiteID, NodeAliasPath, NodeGuid, NodeAlias") .FirstOrDefault(); // First check if there is already a custom URL slug, if so cancel if (UrlSlug.UrlSlugIsCustom) { var ExistingMatchingSlug = UrlSlugInfoProvider.GetUrlSlugs() .WhereNotEquals("UrlSlugNodeID", UrlSlug.UrlSlugNodeID) .WhereEquals("UrlSlug", UrlSlug.UrlSlug) .Where($"UrlSlugNodeID in (Select NodeID from CMS_Tree where NodeSiteID = {Node.NodeSiteID})") .Columns("UrlSlugNodeID") .FirstOrDefault(); if (ExistingMatchingSlug != null) { TreeNode ConflictNode = new DocumentQuery() .WhereEquals("NodeID", ExistingMatchingSlug.UrlSlugNodeID) .Columns("NodeSiteID, NodeAliasPath") .FirstOrDefault(); var Error = new NotSupportedException($"This custom URL Slug '{UrlSlug.UrlSlug}' on {Node.NodeAliasPath} is already the pattern of an existing document ({ConflictNode.NodeAliasPath}). Operation aborted."); EventLogProvider.LogException("DynamicRouting", "CustomUrlSlugConflict", Error, Node.NodeSiteID); throw Error; } } // This prevents the recursive url slug updates from the first update from removing the "Ignore" on this item. RecursionControl AlreadyDeterminedIfShouldIgnore = new RecursionControl("AlreadyDeterminedIfShouldIgnore_" + UrlSlug.UrlSlugGuid); if (CMSActionContext.CurrentLogSynchronization && AlreadyDeterminedIfShouldIgnore.Continue) { // Delete existing ignore records DynamicRouteInternalHelper.RemoveIgnoreStagingTaskOfUrlSlug(UrlSlug.UrlSlugID); // If the staging task Should be created if ( (UrlSlug.UrlSlugIsCustom && !ValidationHelper.GetBoolean(UrlSlug.GetOriginalValue("UrlSlugIsCustom"), true)) || (!UrlSlug.UrlSlugIsCustom && ValidationHelper.GetBoolean(UrlSlug.GetOriginalValue("UrlSlugIsCustom"), false)) || (UrlSlug.UrlSlugIsCustom && ValidationHelper.GetBoolean(UrlSlug.GetOriginalValue("UrlSlugIsCustom"), false) && UrlSlug.UrlSlug != ValidationHelper.GetString(UrlSlug.GetOriginalValue("UrlSlug"), UrlSlug.UrlSlug)) ) { // Staging task should be created, so proceed as normal } else { // Staging task should not be created, add entry so this task won't be generated UrlSlugStagingTaskIgnoreInfoProvider.SetUrlSlugStagingTaskIgnoreInfo(new UrlSlugStagingTaskIgnoreInfo() { UrlSlugStagingTaskIgnoreUrlSlugID = UrlSlug.UrlSlugID }); } } // If the Url Slug is custom or was custom, then need to rebuild after. if (UrlSlug.UrlSlugIsCustom || ValidationHelper.GetBoolean(UrlSlug.GetOriginalValue("UrlSlugIsCustom"), UrlSlug.UrlSlugIsCustom)) { // Add hook so the Url Slug will be re-rendered after it's updated RecursionControl Trigger = new RecursionControl("UrlSlugNoLongerCustom_" + UrlSlug.UrlSlugGuid); var Triggered = Trigger.Continue; } }