public bool Start() { if (!Configuration.SubscriptionServiceEnabled) { return(false); } // renew subscriptions // 1: go through doclibs with email addresses var doclibs = ContentQuery.Query("+TypeIs:DocumentLibrary +ListEmail:* -ListEmail:\"\""); if (doclibs.Count > 0) { Logger.WriteInformation("Exchange subscription service enabled, running subscriptions (" + doclibs.Count.ToString() + " found)", ExchangeHelper.ExchangeLogCategory); foreach (var doclib in doclibs.Nodes) { try { ExchangeHelper.Subscribe(doclib); } catch (Exception ex) { Logger.WriteException(ex, ExchangeHelper.ExchangeLogCategory); } } } else { Logger.WriteInformation("Exchange subscription service enabled, no subscriptions found.", ExchangeHelper.ExchangeLogCategory); } return(true); }
/// <summary> /// Collects first-level child content that are identity types (users, groups or orgunits). If it encounters /// folders (or other non-identity containers) it will dive deeper for identities. /// </summary> private static void CollectSecurityIdentityChildren(NodeHead head, ICollection <int> userIds, ICollection <int> groupIds) { foreach (var childHead in ContentQuery.Query(SafeQueries.InFolder, QuerySettings.AdminSettings, head.Path).Identifiers.Select(NodeHead.Get).Where(h => h != null)) { // in case of identity types: simply add them to the appropriate collection and move on if (childHead.GetNodeType().IsInstaceOfOrDerivedFrom("User")) { if (!userIds.Contains(childHead.Id)) { userIds.Add(childHead.Id); } } else if (childHead.GetNodeType().IsInstaceOfOrDerivedFrom("Group") || childHead.GetNodeType().IsInstaceOfOrDerivedFrom("OrganizationalUnit")) { if (!groupIds.Contains(childHead.Id)) { groupIds.Add(childHead.Id); } } else { // collect identities recursively inside a folder CollectSecurityIdentityChildren(childHead, userIds, groupIds); } } }
public void QueryExecutor_ForceTopByConfig() { StorageContext.Search.DefaultTopAndGrowth = new[] { 10, 30, 80, 0 }; var qt = "Type:ContentType .AUTOFILTERS:OFF"; var sort = new[] { new SortInfo { FieldName = "Id" } }; var result = ContentQuery.Query(qt, new QuerySettings { Skip = 0, Top = 1000, Sort = sort }); var page = result.Nodes; var expectedSet = new List <int>(); foreach (var node in page) { expectedSet.Add(node.Id); } var expectedStr = String.Join(", ", expectedSet); result = ContentQuery.Query(qt, new QuerySettings { Skip = 0, Top = 0, Sort = sort }); page = result.Nodes; var currentSet = new List <int>(); foreach (var node in page) { currentSet.Add(node.Id); } var currentStr = String.Join(", ", currentSet); Assert.AreEqual(expectedStr, currentStr); //Assert.IsTrue(currentSet.Except(expectedSet).Count() == 0, "Returned list contains unexpected ids."); //Assert.IsTrue(expectedSet.Except(currentSet).Count() == 0, "Expected list contains ids that were not returned."); }
// ================================================================================================ Public methods /// <summary> /// Retrieves all posts under given contextPath. /// </summary> /// <param name="contextPath">Path of context, ie. workspace.</param> /// <returns></returns> public static IEnumerable <PostInfo> GetPostsForWorkspace(string contextPath) { var queryText = string.Format("+InTree:\"{0}\" +Type:Post", contextPath); var settings = new QuerySettings { EnableAutofilters = false, Sort = new SortInfo[] { new SortInfo { FieldName = "CreationDate", Reverse = true } } }; var posts = ContentQuery.Query(queryText, settings).Nodes.Select(n => new PostInfo(n)); // gather all journalid-s: these are ids to which post has already been created in the Content Repository var journalIds = posts.Select(p => p.JournalId).Distinct(); var journalItems = Journals.GetItemsForWorkspace(contextPath); // get last paths of journals. Get all journals grouped by nodeids var lastPaths = (from j in journalItems group j by j.NodeId into grp select grp.First()).ToDictionary(j => j.NodeId, j => j.Wherewith); // gather crudposts, where createdby is a valid user (not SYSTEMUSER) // and it has not been persisted to the content repository yet (journalid is not contained in journalids above) var crudPosts = journalItems.Select(j => new PostInfo(j, lastPaths[j.NodeId])).Where(p => p.CreatedBy != null && !journalIds.Contains(p.JournalId)); // gather likes and comments corresponding to content under this workspace var postsFolderPath = RepositoryPath.Combine(contextPath, "Posts"); queryText = string.Format("+InTree:\"{0}\" +(Type:Comment Type:Like) -InTree:\"{1}\"", contextPath, postsFolderPath); var contentComments = ContentQuery.Query(queryText, settings).Nodes.Select(n => PostInfo.CreateFromCommentOrLike(n)).Where(p => p != null).Distinct(new CommentsLikesComparer()); return(posts.Union(crudPosts).Union(contentComments).OrderByDescending(p => p.CreationDate)); }
public void Linq_EmptyReference() { Content[] result; string expected, actual; QueryResult qresult; var mother1 = Node.LoadNode(TestRoot2.Path + "/Mother1"); var mother2 = Node.LoadNode(TestRoot2.Path + "/Mother2"); var child1 = Node.LoadNode(TestRoot2.Path + "/Child1"); var child2 = Node.LoadNode(TestRoot2.Path + "/Child2"); var child3 = Node.LoadNode(TestRoot2.Path + "/Child3"); qresult = ContentQuery.Query(String.Concat("+Mother:null +InTree:", TestRoot2.Path, " .AUTOFILTERS:OFF")); result = Content.All.DisableAutofilters().Where(c => c.InTree(TestRoot2) && ((RefTestNode)c.ContentHandler).Mother == null).OrderBy(c => c.Name).ToArray(); Assert.IsTrue(result.Length == 3, String.Format("#5: count is {0}, expected: 3", result.Length)); expected = String.Concat(child3.Id, ", ", mother1.Id, ", ", mother2.Id); actual = String.Join(", ", result.Select(x => x.Id)); Assert.IsTrue(expected == actual, String.Format("#6: actual is {0}, expected: {1}", actual, expected)); qresult = ContentQuery.Query(String.Concat("-Mother:null +InTree:", TestRoot2.Path, " +TypeIs:repositorytest_reftestnode .AUTOFILTERS:OFF")); result = Content.All.DisableAutofilters().Where(c => c.InTree(TestRoot2) && ((RefTestNode)c.ContentHandler).Mother != null && c.ContentHandler is RefTestNode).OrderBy(c => c.Name).ToArray(); Assert.IsTrue(result.Length == 2, String.Format("#5: count is {0}, expected: 2", result.Length)); expected = String.Concat(child1.Id, ", ", child2.Id); actual = String.Join(", ", result.Select(x => x.Id)); Assert.IsTrue(expected == actual, String.Format("#6: actual is {0}, expected: {1}", actual, expected)); }
// ================================================================================================ Public methods /// <summary> /// Retrieves all posts under given contextPath. /// </summary> /// <param name="contextPath">Path of context, ie. workspace.</param> /// <returns></returns> public static IEnumerable <PostInfo> GetPostsForWorkspace(string contextPath) { // execute the query in the name of the current user var settings = new QuerySettings { EnableAutofilters = FilterStatus.Disabled, Sort = new[] { new SortInfo("CreationDate", true) } }; var posts = ContentQuery.Query(ContentRepository.SafeQueries.InTreeAndTypeIs, settings, contextPath, "Post"); // gather likes and comments corresponding to content under this workspace var postsFolderPath = RepositoryPath.Combine(contextPath, "Posts"); var contentComments = ContentQuery.Query("+InTree:@0 +(Type:Comment Type:Like) -InTree:@1", settings, contextPath, postsFolderPath); // load nodes in elevated mode to have user data (e.g. creator, avatar, etc.) accessible using (new SystemAccount()) { var p1 = posts.Nodes.Select(n => new PostInfo(n)).ToList(); var p2 = contentComments.Nodes.Select(PostInfo.CreateFromCommentOrLike) .Where(p => p != null) .Distinct(new CommentsLikesComparer()) .OrderByDescending(p => p.CreationDate) .ToList(); return(p1.Union(p2)); } }
/// <summary> /// Deletes a Like from the given Post/Content/Comment /// </summary> /// <param name="itemId"></param> public static void DeleteLike(string clientId, out int postId) { // this method can only be called if the post already exists in the Content Repository // but itemId may still be referring to journalId, so let's load the corresponding content. Therefore string.Empty is enough here var post = GetPostFromId(clientId, string.Empty); var likeFolderPath = RepositoryPath.Combine(post.Path, "Likes"); var queryText = string.Format("+InFolder:\"{0}\" +Type:Like +CreatedById:{1}", likeFolderPath, SenseNet.ContentRepository.User.Current.Id); var likeContents = ContentQuery.Query(queryText, new QuerySettings { EnableAutofilters = false }).Nodes; //var likeContent = ContentQuery.Query(string.Format("+ParentId:{0} +Type:Like +CreatedById:{1}", post.Id, SenseNet.ContentRepository.User.Current.Id)).Nodes.FirstOrDefault(); foreach (var likeContent in likeContents) { var likeGc = likeContent as GenericContent; if (likeGc != null) { likeGc.Delete(true); } } // return postId, as it will be used for LikeList and LikeMarkup postId = post.Id; }
/// <summary> /// Replaces the given tag to the given new tag on every content in reppository. /// Also used for deleting tags, by calling with newtag = String.Empty parameter. /// </summary> /// <param name="tag">Tag to replace.</param> /// <param name="newtag">Tag to replace with.</param> /// <param name="pathList">The path list.</param> public static void ReplaceTag(string tag, string newtag, List <string> pathList) { tag = tag.ToLower(); newtag = newtag.ToLower(); if (tag == string.Empty) { return; } var query = $"+Tags:\"{tag}\""; if (pathList != null && pathList.Count > 0) { query = string.Concat(query, $" +InTree:({pathList.Aggregate(string.Empty, (current, path) => string.Concat(current, "\"", path, "\"", " ")).TrimEnd(' ')})"); } foreach (var tmp in ContentQuery.Query(query).Nodes) { if (tmp["Tags"] != null) { tmp["Tags"] = (tmp["Tags"].ToString().ToLower().Replace(tag, newtag)).Trim(); } tmp.Save(); } }
public static string[] RunPagesBackground(HttpContext context, out Exception[] exceptions) { List <string> pageList = new List <string>(); List <Exception> exceptionList = new List <Exception>(); var pagesNodes = ContentQuery.Query(ContentRepository.SafeQueries.TypeIs, QuerySettings.AdminSettings, typeof(Page).Name).Nodes; foreach (var pageItem in pagesNodes) { Page p = (Page)pageItem; if (p != null && p.HasTemporaryPortletInfo) { Site site = p.Site; if (site != null) { Page.RunPage(HttpContext.Current, p.Path, p, out var exc); pageList.Add(p.Path); if (exc != null) { exceptionList.Add(exc); } } } } exceptions = exceptionList.ToArray(); return(pageList.ToArray()); }
private static IEnumerable <User> SearchInLucene(string path, string typeName, string name) { var cquery = String.Format("+TypeIs:{0} +InTree:\"{1}\" +Name:\"{2}\"", typeName, path, name); var result = ContentQuery.Query(cquery); return(result.Nodes.Cast <User>()); }
public static string GetRunningWorkflowsText(Node relatedContent) { if (!SearchManager.ContentQueryIsAllowed) { return(string.Empty); } var cl = ContentList.GetContentListForNode(relatedContent); if (cl == null) { return(string.Empty); } var result = ContentQuery.Query("+InTree:@0 +TypeIs:Workflow +WorkflowStatus:1 +RelatedContent:@1 .AUTOFILTERS:OFF .LIFESPAN:OFF", null, cl.Path + "/Workflows", relatedContent.Id); var sb = new StringBuilder(); foreach (var wfInstance in result.Nodes) { if (sb.Length > 0) { sb.Append(", "); } sb.Append(wfInstance.DisplayName); } return(sb.ToString()); }
private static void PreloadContentTemplates() { try { QueryResult queryResult; var timer = new Stopwatch(); timer.Start(); using (new SystemAccount()) { queryResult = ContentQuery.Query(SafeQueries.PreloadContentTemplates, null, RepositoryStructure.ContentTemplateFolderPath, RepositoryPath.GetDepth(RepositoryStructure.ContentTemplateFolderPath) + 2); // ReSharper disable once UnusedVariable // this is a preload operation, we do not want to use the result var templates = queryResult.Nodes.ToList(); } timer.Stop(); SnLog.WriteInformation($"***** Content template preload time: {timer.Elapsed} ******* Count: {queryResult.Count}"); } catch (Exception ex) { SnLog.WriteException(ex); } }
public bool Start() { if (Settings.GetValue(MailHelper.MAILPROCESSOR_SETTINGS, MailHelper.SETTINGS_MODE, null, MailProcessingMode.ExchangePull) != MailProcessingMode.ExchangePush) { return(false); } // renew subscriptions // 1: go through doclibs with email addresses var doclibs = ContentQuery.Query("+TypeIs:DocumentLibrary +ListEmail:* -ListEmail:\"\""); if (doclibs.Count > 0) { SnLog.WriteInformation(String.Concat("Exchange subscription service enabled, running subscriptions (", doclibs.Count.ToString(), " found)"), categories: ExchangeHelper.ExchangeLogCategory); foreach (var doclib in doclibs.Nodes) { try { ExchangeHelper.Subscribe(doclib); } catch (Exception ex) { SnLog.WriteException(ex, categories: ExchangeHelper.ExchangeLogCategory); } } } else { SnLog.WriteInformation("Exchange subscription service enabled, no subscriptions found.", categories: ExchangeHelper.ExchangeLogCategory); } return(true); }
private static void PreloadContentTemplates() { try { QueryResult queryResult; var timer = new Stopwatch(); timer.Start(); using (new SystemAccount()) { queryResult = ContentQuery.Query( string.Format("+InTree:\"{0}\" +Depth:{1}", Repository.ContentTemplateFolderPath, RepositoryPath.GetDepth(Repository.ContentTemplateFolderPath) + 2), new QuerySettings { EnableAutofilters = false }); var templates = queryResult.Nodes.ToList(); } timer.Stop(); Logger.WriteInformation(string.Format("***** Content template preload time: {0} ******* Count: {1}", timer.Elapsed, queryResult.Count)); //Trace.WriteLine(string.Format(">>>>Preload: Content template preload time: {0} ******* Count: {1}", timer.Elapsed, queryResult.Count)); } catch (Exception ex) { Logger.WriteException(ex); } }
public void Querying_ParserAndKeywordAnalyzer() { var queries = new Tuple <string, int>[] { new Tuple <string, int>("Keywords:helo1", 1), // 0 new Tuple <string, int>("Keywords:helo", 0), // 1 new Tuple <string, int>("Keywords:helo*", 1), // 2 new Tuple <string, int>("Keywords:helo2", 0), // 3 new Tuple <string, int>("Keywords:hElo2", 1), // 4 new Tuple <string, int>("Keywords:bye/Bye", 1), // 5 new Tuple <string, int>("Keywords:bye/*", 1), // 6 new Tuple <string, int>("Keywords:naES", 0), // 7 new Tuple <string, int>("Keywords:naes", 1), // 8 }; var content = Content.CreateNew("Contract", TestRoot, null); content["Keywords"] = "helo1 hElo2 bye/Bye naes"; content.Save(); foreach (var query in queries) { var count = ContentQuery.Query(query.Item1 + " .COUNTONLY").Count; var message = String.Format("Result count of '{0}' is {1}. Extpected: {2}", query.Item1, count, query.Item2); Assert.IsTrue(count == query.Item2, message); } }
public void Security_ContentQuery_FieldLevel_Executing() { var rootFolderName = "Security_ContentQuery_AccessLevel_ExecutingAndLinq"; var rootFolder = EnsureTestStructure(rootFolderName); var savedUser = User.Current; User.Current = TestUser; try { var settings = new QuerySettings { EnableAutofilters = FilterStatus.Disabled, Sort = new[] { new SortInfo { FieldName = "Index", Reverse = false } } }; var r1 = ContentQuery.Query("Name:(See Preview PreviewWithoutWatermark PreviewWithoutRedaction Open OpenMinor)", settings).Nodes.Select(x => x.Name).ToArray(); var r2 = ContentQuery.Query("InFolder:@0", settings, rootFolder.Path).Nodes.Select(x => x.Name).ToArray(); var r3 = ContentQuery.Query("+InFolder:@0 +Index:>0", settings, rootFolder.Path).Nodes.Select(x => x.Name).ToArray(); var r4 = ContentQuery.Query("+InFolder:@0 +Description:value", settings, rootFolder.Path).Nodes.Select(x => x.Name).ToArray(); var r5 = ContentQuery.Query("+InFolder:@0 value .SORT:Index", settings, rootFolder.Path).Nodes.Select(x => x.Name).ToArray(); Assert.AreEqual("See, Preview, PreviewWithoutWatermark, PreviewWithoutRedaction, OpenMinor", String.Join(", ", r1)); Assert.AreEqual("See, Preview, PreviewWithoutWatermark, PreviewWithoutRedaction, OpenMinor", String.Join(", ", r2)); Assert.AreEqual("See, Preview, PreviewWithoutWatermark, PreviewWithoutRedaction, OpenMinor", String.Join(", ", r3)); Assert.AreEqual("Preview, PreviewWithoutWatermark, PreviewWithoutRedaction, OpenMinor", String.Join(", ", r4)); Assert.AreEqual("PreviewWithoutRedaction, OpenMinor", String.Join(", ", r5)); } finally { User.Current = savedUser; } }
/// <summary> /// Deletes a Like from the given Post/Content/Comment /// </summary> /// <param name="itemId"></param> public static void DeleteLike(string clientId, out int postId) { // this method can only be called if the post already exists in the Content Repository // but itemId may still be referring to journalId, so let's load the corresponding content. Therefore string.Empty is enough here var post = GetPostFromId(clientId, string.Empty); var likeFolderPath = RepositoryPath.Combine(post.Path, "Likes"); var likeContents = ContentQuery.Query("+InFolder:@0 +Type:Like +CreatedById:@1", new QuerySettings { EnableAutofilters = FilterStatus.Disabled }, likeFolderPath, User.Current.Id).Nodes; foreach (var likeContent in likeContents) { var likeGc = likeContent as GenericContent; if (likeGc != null) { likeGc.Delete(true); } } // return postId, as it will be used for LikeList and LikeMarkup postId = post.Id; }
private Resource GetResourceForClassName(string classname) { var res = Node.LoadNode("/Root/Localization/" + classname + "Resources.xml") as Resource; if (res != null) { return(res); } var resources = ContentQuery.Query("+Type:Resource", new QuerySettings { EnableAutofilters = false }).Nodes.OrderBy(i => i.Index); foreach (Resource resc in resources) { var xml = new XmlDocument(); xml.Load(resc.Binary.GetStream()); var classelement = xml.SelectSingleNode("/Resources/ResourceClass[@name='" + classname + "']"); if (classelement != null) { return(resc); } } return(null); }
public static IEnumerable <PostInfo> GetPostsForContent(Node content) { // share posts of current content var queryText = string.Format("+SharedContent:\"{0}\" +Type:Post", content.Id.ToString()); var settings = new QuerySettings { Sort = new SortInfo[] { new SortInfo { FieldName = "CreationDate", Reverse = true } } }; var posts = ContentQuery.Query(queryText, settings).Nodes.Select(n => new PostInfo(n)); // gather all journalid-s: these are ids to which post has already been created in the Content Repository var journalIds = posts.Select(p => p.JournalId).Distinct(); var journalItems = Journals.GetItemsForContent(content.Id); // get last paths of journals. Get all journals grouped by nodeids var lastPaths = (from j in journalItems group j by j.NodeId into grp select grp.First()).ToDictionary(j => j.NodeId, j => j.Wherewith); // gather crudposts, where createdby is a valid user (not SYSTEMUSER) // and it has not been persisted to the content repository yet (journalid is not contained in journalids above) var crudPosts = journalItems.Select(j => new PostInfo(j, lastPaths[j.NodeId])).Where(p => p.CreatedBy != null && !journalIds.Contains(p.JournalId)); return(posts.Union(crudPosts).OrderByDescending(p => p.CreationDate)); }
public void Globalization_IndexingLocalized_InvalidKey() { var testResClass = "TestResClass"; var testResKey = "TestKey_Invalid"; var valueEn = "value_en"; var valueHu = "value_hu"; var valueDe = "value_de"; var en = CultureInfo.GetCultureInfo("en-US"); var hu = CultureInfo.GetCultureInfo("hu-HU"); var de = CultureInfo.GetCultureInfo("de-DE"); AddResource(en, testResClass, testResKey, valueEn, TheOneResource); AddResource(hu, testResClass, testResKey, valueHu, TheOneResource); AddResource(de, testResClass, testResKey, valueDe, TheOneResource); var resDef = String.Concat("$", testResClass, ",xx,", testResKey);// invalid key var content = Content.CreateNew("Car", TestRoot, null); content["DisplayName"] = resDef; content.Save(); var versionId = content.ContentHandler.VersionId; var result = ContentQuery.Query(String.Format("DisplayName:{0} .AUTOFILTERS:OFF", resDef)); Assert.IsFalse(result.Count == 0, String.Format("Resource key is not found: {0}", resDef)); result = ContentQuery.Query(String.Format("DisplayName:'{0}' .AUTOFILTERS:OFF", valueEn)); Assert.IsFalse(result.Count == 1, String.Format("English value is found: {0}", valueEn)); result = ContentQuery.Query(String.Format("DisplayName:'{0}' .AUTOFILTERS:OFF", valueHu)); Assert.IsFalse(result.Count == 1, String.Format("Hungarian value is found: {0}", valueHu)); result = ContentQuery.Query(String.Format("DisplayName:'{0}' .AUTOFILTERS:OFF", valueDe)); Assert.IsFalse(result.Count == 1, String.Format("Deusch value is found: {0}", valueDe)); }
// ================================================================================================ Private methods /// <summary> /// Get a post from clientId. If it is a manual post, it comes from repository. /// If it is a journal post, it either comes from journal and a repository post is created, or is already persisted to repository. /// </summary> /// <param name="clientId"></param> /// <param name="contextPath">New posts from journal items will be created under contextPath</param> /// <returns></returns> private static Node GetPostFromId(string clientId, string contextPath) { Node post = null; var itemID = PostInfo.GetIdFromClientId(clientId); if (PostInfo.IsJournalId(clientId)) { // CRUD post, create a manual post // only create it if it is not yet created! post = ContentQuery.Query(string.Format("JournalId:{0}", itemID)).Nodes.FirstOrDefault(); if (post == null) { var item = Journals.GetSingleItem(itemID); // lastpath is empty here: we wont use it from this scenario var postInfo = new PostInfo(item, string.Empty); var sharedContent = Node.LoadNode(item.NodeId); post = CreatePost(contextPath, postInfo.Text, item.When, itemID, postInfo.Type, sharedContent, postInfo.Details); } } else { post = Node.LoadNode(itemID); } return(post); }
/// <summary> /// Gets the number of participants. /// </summary> /// <param name="item">The CalendarEvent item.</param> /// <returns>Number of approved participants.</returns> private static int GetNumberOfParticipants(Node item) { var regForm = item.GetReference <Node>("RegistrationForm"); if (regForm != null) { var qResult = ContentQuery.Query("+Type:eventregistrationformitem +ParentId:@0", new QuerySettings { EnableAutofilters = FilterStatus.Disabled, EnableLifespanFilter = FilterStatus.Disabled }, regForm.Id); var i = 0; foreach (var node in qResult.Nodes) { var subs = Content.Create(node); var guests = 0; int.TryParse(subs["GuestNumber"].ToString(), out guests); i += (guests + 1); } return(i); } return(0); }
public static IEnumerable <PostInfo> GetPostsForUser(User user, string profilePath) { // get all wall container workspaces - instead of loading the content of the journal and individually determine the wall container workspace //var wallWorkspacesPaths = ContentQuery.Query("+TypeIs:Workspace +IsWallContainer:1").Nodes.Select(n => n.Path); // gather users's posts: // - gather all journal posts from everywhere, that was created by the user // - gather all big posts that were put out to his/her wall var queryText = string.Format("(+CreatedById:\"{0}\" +Type:Post -PostType:{1}) (+InTree:\"{2}\" +Type:Post)", user.Id, (int)PostType.BigPost, profilePath); var settings = new QuerySettings { EnableAutofilters = false, Sort = new SortInfo[] { new SortInfo { FieldName = "CreationDate", Reverse = true } } }; var posts = ContentQuery.Query(queryText, settings).Nodes.Select(n => new PostInfo(n)); // gather all journalid-s: these are ids to which post has already been created in the Content Repository var journalIds = posts.Select(p => p.JournalId).Distinct(); var journalItems = Journals.GetItemsForUser(user); // get last paths of journals. Get all journals grouped by nodeids var lastPaths = (from j in journalItems group j by j.NodeId into grp select grp.First()).ToDictionary(j => j.NodeId, j => j.Wherewith); // gather users's activities // gather crudposts, where createdby is current user // and it has not been persisted to the content repository yet (journalid is not contained in journalids above) var crudPosts = journalItems.Select(j => new PostInfo(j, lastPaths[j.NodeId])).Where(p => p.CreatedBy != null && !journalIds.Contains(p.JournalId)); return(posts.Union(crudPosts).OrderByDescending(p => p.CreationDate)); }
private RelatedSensitiveFolders GetRelatedFolders(List <string> names) { var result = ContentQuery.Query(ContentRepository.SafeQueries.TypeIsAndName, QuerySettings.AdminSettings, "Folder", names); var apps = new List <string>(); var temps = new List <string>(); var views = new List <string>(); foreach (var node in result.Nodes) { var path = node.Path.ToLowerInvariant(); if (path.Contains("/(apps)/")) { apps.Add(path); } else if (path.Contains("/contenttemplates/")) { temps.Add(path); } else if (path.Contains("/contentviews/")) { views.Add(path); } } return(new RelatedSensitiveFolders { Applications = apps.ToArray(), ContentTemplates = temps.ToArray(), ContentViews = views.ToArray() }); }
/// <summary> /// Gets all security identities (users, groups and org units) in a subtree. /// </summary> private static List <int> GetSecurityIdentityIds(Node node) { using (new SystemAccount()) { // import scenario if (!SearchManager.ContentQueryIsAllowed) { var resultIds = NodeQuery.QueryNodesByTypeAndPathAndName(new[] { ActiveSchema.NodeTypes["Group"], ActiveSchema.NodeTypes["OrganizationalUnit"], ActiveSchema.NodeTypes["User"] }, false, node.Path, true, null).Identifiers.ToList(); // workaround for the nodequery above: it does not return the root node itself if (node is ISecurityMember && !resultIds.Contains(node.Id)) { resultIds.Add(node.Id); } return(resultIds); } return(ContentQuery.Query(SafeQueries.SecurityIdentitiesInTree, QuerySettings.AdminSettings, node.Path).Identifiers.ToList()); } }
public static string GetRunningWorkflowsText(Node relatedContent) { if (!StorageContext.Search.IsOuterEngineEnabled) { return(string.Empty); } var cl = ContentList.GetContentListForNode(relatedContent); if (cl == null) { return(string.Empty); } var query = string.Format("+InTree:\"{0}\" +TypeIs:Workflow +WorkflowStatus:1 +RelatedContent:{1} .AUTOFILTERS:OFF .LIFESPAN:OFF", cl.Path + "/Workflows", relatedContent.Id); var result = ContentQuery.Query(query); var sb = new StringBuilder(); foreach (var wfInstance in result.Nodes) { if (sb.Length > 0) { sb.Append(", "); } sb.Append(wfInstance.DisplayName); } return(sb.ToString()); }
private static void PreloadContentTemplates() { try { QueryResult queryResult; var timer = new Stopwatch(); timer.Start(); using (new SystemAccount()) { queryResult = ContentQuery.Query(SafeQueries.PreloadContentTemplates, null, Repository.ContentTemplateFolderPath, RepositoryPath.GetDepth(Repository.ContentTemplateFolderPath) + 2); var templates = queryResult.Nodes.ToList(); } timer.Stop(); Logger.WriteInformation(Logger.EventId.NotDefined, string.Format("***** Content template preload time: {0} ******* Count: {1}", timer.Elapsed, queryResult.Count)); //Trace.WriteLine(string.Format(">>>>Preload: Content template preload time: {0} ******* Count: {1}", timer.Elapsed, queryResult.Count)); } catch (Exception ex) { Logger.WriteException(ex); } }
private bool TryLoadFirstContent() { var result = false; if (string.IsNullOrEmpty(this._contentPath) && !string.IsNullOrEmpty(this.UsedContentTypeName) && _displayMode != GetViewModeName(ViewMode.InlineNew)) { try { var cql = $"+TypeIs:{UsedContentTypeName} +InFolder:{PortalContext.Current.ContextNodeHead.Path} .SORT:Index"; var qresult = ContentQuery.Query(cql, QuerySettings.AdminSettings); var firstNode = qresult.Nodes.FirstOrDefault(); if (firstNode != null) { _contentPath = firstNode.Path; _displayMode = GetViewModeName(ViewMode.Browse); result = true; } } catch (Exception exc) // logged { SnLog.WriteException(exc); } } return(result); }
// ======================================================================================== static methods public static IEnumerable <WorkspaceGroupList> GetWorkspaceGroupLists(User user) { // 1. query groups under workspaces var settings = new QuerySettings { EnableAutofilters = FilterStatus.Disabled }; var groups = ContentQuery.Query("+TypeIs:Group +Workspace:* -InTree:@0", settings, new[] { RepositoryStructure.ImsFolderPath, RepositoryStructure.ContentTemplateFolderPath }).Nodes; // Elevation: this is a technical method that should // always return the full list of relevant groups and related // workspaces, regardless of the current users permissions. using (new SystemAccount()) { // 2. select groups in which the current user is a member (Owner, Editor) var wsGroups = groups.Select(g => new WorkspaceGroup { Workspace = ((Group)g).Workspace, Group = (Group)g }); wsGroups = wsGroups.Where(wsg => wsg.Workspace != null && user.IsInGroup(wsg.Group)); // 3. group by workspaces var wsGroupLists = from wsg in wsGroups orderby wsg.Workspace.DisplayName group wsg by wsg.Workspace into w select new WorkspaceGroupList { Workspace = w.Key, Groups = w }; return(wsGroupLists); } }
public void Indexing_Culture_TurkeyTest() { // cleanup DestroyPlayground(); var originalCulture = Thread.CurrentThread.CurrentCulture; try { var parent = Content.CreateNew("Folder", TestRoot, "ABCDI"); parent.Save(); Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("tr-TR"); var content = Content.CreateNew("Folder", parent.ContentHandler, "Whatever"); content.Save(); var result = ContentQuery.Query("+InFolder:@0 .AUTOFILTERS:OFF", null, parent.Path); Assert.AreEqual(1, result.Count, "#1 Query result count is incorrect."); Assert.AreEqual(content.Id, result.Identifiers.FirstOrDefault(), "#2 The content was not found."); // querying should work with both cultures Thread.CurrentThread.CurrentCulture = originalCulture; result = ContentQuery.Query("+InFolder:@0 .AUTOFILTERS:OFF", null, parent.Path); Assert.AreEqual(1, result.Count, "#3 Query result count is incorrect."); Assert.AreEqual(content.Id, result.Identifiers.FirstOrDefault(), "#4 The content was not found."); } finally { Thread.CurrentThread.CurrentCulture = originalCulture; } }