private static SortedDictionary <string, string> MapSkin(Node skin) { //CONDITIONAL EXECUTE NodeQueryResult result; if (StorageContext.Search.IsOuterEngineEnabled && StorageContext.Search.SearchEngine != InternalSearchEngine.Instance) { var query = new NodeQuery(); query.Add(new StringExpression(StringAttribute.Path, StringOperator.StartsWith, skin.Path)); result = query.Execute(); } else { result = NodeQuery.QueryNodesByPath(skin.Path, false); } var dict = new SortedDictionary <string, string>(); foreach (Node n in result.Nodes) { if (n.Id != skin.Id) { var relpath = n.Path.Substring(skin.Path.Length + 1); if (!dict.ContainsKey(relpath)) { dict.Add(relpath, n.Path); } } } return(dict); }
private void Load() { var resNodeType = ActiveSchema.NodeTypes[typeof(Resource).Name]; if (resNodeType != null) { // search for all Resource content // Elevation: caching all string resource files // is independent from the current user. using (new SystemAccount()) { IEnumerable<Node> nodes; var r = NodeQuery.QueryNodesByTypeAndPath(ActiveSchema.NodeTypes["Resource"] , false , String.Concat(RepositoryStructure.ResourceFolderPath, RepositoryPath.PathSeparator) , true); nodes = r.Nodes.OrderBy(i => i.Index); LastResourceModificationDate = nodes.Any() ? nodes.Max(x => x.ModificationDate) : DateTime.MinValue; // Workaround: truncate milliseconds, because the 'If-Modified-Since' header sent // by clients will not contain milliseconds, so comparisons would fail. LastResourceModificationDate = LastResourceModificationDate.AddTicks(-(LastResourceModificationDate.Ticks % TimeSpan.TicksPerSecond)); ParseAll(nodes); } } }
/// <summary> /// Gets all users. /// </summary> /// <param name="pageIndex">Index of the page. (currently ignored)</param> /// <param name="pageSize">Size of the page. (currently ignored)</param> /// <param name="totalRecords">The total records.</param> /// NOTE: paging is not yet implemented /// <returns></returns> public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords) { MembershipUserCollection users = new MembershipUserCollection(); // create NodeQuery NodeQuery query = new NodeQuery(); query.Add(new TypeExpression(ActiveSchema.NodeTypes[typeof(User).Name], false)); if (_path != null) { query.Add(new StringExpression(StringAttribute.Path, StringOperator.StartsWith, _path)); } query.Orders.Add(new SearchOrder(StringAttribute.Name)); query.PageSize = pageSize; query.Skip = pageIndex * pageSize; // get paged resultlist var resultList = query.Execute(); foreach (Node node in resultList.Nodes) { User user = (User)node; users.Add(GetMembershipUser(user)); } // get total number of users totalRecords = resultList.Count; return(users); }
public XPathNavigator Execute(object param, bool raiseExceptions) { try { NodeQuery queryFromXml = NodeQuery.Parse(((XPathNavigator)param).OuterXml); var result = queryFromXml.Execute(); Result queryResult = new Result() { ContentList = result.Nodes.Select( node => new Services.ContentStore.Content(node)).ToArray() }; return(queryResult.ToXPathNavigator()); } catch (Exception exc) //logged { if (raiseExceptions) { throw; } Logger.WriteException(exc); return(new QueryException() { Message = exc.Message }.ToXPathNavigator()); } }
private User GetRegisteredUser(string resetEmail, string domain) { if (String.IsNullOrEmpty(resetEmail)) { throw new ArgumentNullException("resetEmail"); } if (String.IsNullOrEmpty(domain)) { throw new ArgumentNullException("domain"); } var query = new NodeQuery(); var expressionList = new ExpressionList(ChainOperator.And); expressionList.Add(new TypeExpression(ActiveSchema.NodeTypes[Configuration.UserTypeName], false)); expressionList.Add(new StringExpression(StringAttribute.Path, StringOperator.StartsWith, string.Concat(Repository.ImsFolderPath, RepositoryPath.PathSeparator, domain, RepositoryPath.PathSeparator))); expressionList.Add(new StringExpression(ActiveSchema.PropertyTypes["Email"], StringOperator.Equal, resetEmail)); query.Add(expressionList); AccessProvider.ChangeToSystemAccount(); var resultList = query.Execute(); AccessProvider.RestoreOriginalUser(); // no user has beeen found if (resultList.Count == 0) { return(null); } var u = resultList.Nodes.First() as User; return(u); }
/// <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()); } }
private void ReadSkinStructure() { Node[] nodes; if (RepositoryInstance.ContentQueryIsAllowed) { var query = new NodeQuery(); query.Add(new StringExpression(StringAttribute.Path, StringOperator.StartsWith, RepositoryStructure.SkinRootFolderPath)); query.Add(new TypeExpression(NodeType.GetByName("Skin"))); nodes = query.Execute().Nodes.ToArray(); } else { nodes = NodeQuery.QueryNodesByTypeAndPath(NodeType.GetByName("Skin"), false, RepositoryStructure.SkinRootFolderPath, false).Nodes.ToArray(); } try { _skinMapLock.TryEnterWriteLock(RepositoryEnvironment.DefaultLockTimeout); foreach (Node n in nodes) { _skinMap.Add(n.Name, MapSkin(n)); } } finally { if (_skinMapLock.IsWriteLockHeld) { _skinMapLock.ExitWriteLock(); } } }
private bool TryLoadFirstContent() { var result = false; if (String.IsNullOrEmpty(this._contentPath) && !String.IsNullOrEmpty(this.UsedContentTypeName) && this._displayMode != GetViewModeName(ViewMode.InlineNew)) { try { var query = new NodeQuery(); query.Add(new TypeExpression(ActiveSchema.NodeTypes[this.UsedContentTypeName], true)); query.Add(new IntExpression(IntAttribute.ParentId, ValueOperator.Equal, PortalContext.Current.ContextNodeHead.Id)); var queryResult = query.Execute().Nodes.ToList(); if (queryResult.Count > 0) { var nodeComparer = new NodeComparer <Node>(); queryResult.Sort(nodeComparer); this._contentPath = queryResult[0].Path; this._displayMode = GetViewModeName(ViewMode.Browse); result = true; } } catch (Exception exc) //logged { Logger.WriteException(exc); } } return(result); }
public Content Query(string queryXml, bool withProperties) { var resultset = ContentRepository.Content.Query(NodeQuery.Parse(queryXml)); var feed = resultset.Select <ContentRepository.Content, Content>(res => new Content(res.ContentHandler, withProperties, false, false, false, 0, 0)).ToArray(); return(CreateFakeRootForFeed(feed)); }
public ExpressionEnumerator(NodeQuery query) { _root = query; _expressionList = new List <Expression>(); AddExpressionToInnerList(query); _innerEnumerator = _expressionList.GetEnumerator(); }
// caller: IndexPopulator.Populator public void RebuildIndexDirectly(string path, IndexRebuildLevel level = IndexRebuildLevel.IndexOnly) { if (level == IndexRebuildLevel.DatabaseAndIndex) { using (var op2 = SnTrace.Index.StartOperation("IndexPopulator: Rebuild index documents.")) { using (new SystemAccount()) { var node = Node.LoadNode(path); DataBackingStore.SaveIndexDocument(node, false, false, out _); Parallel.ForEach(NodeQuery.QueryNodesByPath(node.Path, true).Nodes, n => { DataBackingStore.SaveIndexDocument(n, false, false, out _); }); } op2.Successful = true; } } using (var op = SnTrace.Index.StartOperation("IndexPopulator: Rebuild index.")) { IndexManager.IndexingEngine.WriteIndex( new[] { new SnTerm(IndexFieldName.InTree, path) }, null, SearchManager.LoadIndexDocumentsByPath(path, IndexManager.GetNotIndexedNodeTypes()) .Select(d => { var indexDoc = IndexManager.CompleteIndexDocument(d); OnNodeIndexed(d.Path); return(indexDoc); })); op.Successful = true; } }
internal static void RemoveNodesAndType(string contentTypeName) { var query = new NodeQuery(); var nt = ActiveSchema.NodeTypes[contentTypeName]; if (nt != null) { query.Add(new TypeExpression(nt)); foreach (var nodeId in query.Execute().Identifiers) { try { Node.ForceDelete(nodeId); } catch { //suppress the exception that occurs //when node doesn't exist with the given id } } } var ct = ContentType.GetByName(contentTypeName); if (ct != null) { ct.Delete(); ContentTypeManager.Reset(); } }
private void Load() { // search for all Resource content NodeQuery query = new NodeQuery(); query.Add(new StringExpression(StringAttribute.Path, StringOperator.StartsWith, String.Concat(Repository.ResourceFolderPath, RepositoryPath.PathSeparator))); query.Add(new TypeExpression(ActiveSchema.NodeTypes["Resource"])); IEnumerable <Node> nodes = null; if (StorageContext.Search.IsOuterEngineEnabled && StorageContext.Search.SearchEngine != InternalSearchEngine.Instance) { nodes = query.Execute().Nodes.OrderBy(i => i.Index); } else { var r = NodeQuery.QueryNodesByTypeAndPath(ActiveSchema.NodeTypes["Resource"] , false , String.Concat(Repository.ResourceFolderPath, RepositoryPath.PathSeparator) , true); nodes = r.Nodes.OrderBy(i => i.Index); } ParseAll(nodes); ////-- sort by index //NodeComparer<Node> resourceComparer = new NodeComparer<Node>(); //result.Sort(resourceComparer); }
private void CheckUniqueUser() { var path = Path; if (!path.StartsWith(string.Concat(Repository.ImsFolderPath, RepositoryPath.PathSeparator)) || Parent.Path == Repository.ImsFolderPath) { throw new InvalidOperationException("Invalid path: user nodes can only be saved under a /Root/IMS/[DomainName] folder."); } string domainPath = path.Substring(0, Repository.ImsFolderPath.Length + 1 + path.Substring(Repository.ImsFolderPath.Length + 1).IndexOf('/') + 1); //We validate here the uniqueness of the user. The constraint is the user name itself and that in Active Directory //there must not exist two users and/or groups with the same name under a domain. Organizational units may have //the same name as a user. //CONDITIONAL EXECUTE IEnumerable <int> identifiers; int count; if (StorageContext.Search.IsOuterEngineEnabled && StorageContext.Search.SearchEngine != InternalSearchEngine.Instance) { var query = new NodeQuery(); var nameExpression = new StringExpression(StringAttribute.Name, StringOperator.Equal, Name); var pathExpression = new StringExpression(StringAttribute.Path, StringOperator.StartsWith, domainPath); var orTypes = new ExpressionList(ChainOperator.Or); orTypes.Add(new TypeExpression(ActiveSchema.NodeTypes["User"])); orTypes.Add(new TypeExpression(ActiveSchema.NodeTypes["Group"])); query.Add(pathExpression); query.Add(nameExpression); query.Add(orTypes); var result = query.Execute(); identifiers = result.Identifiers; count = result.Count; } else { var nodes = NodeQuery.QueryNodesByTypeAndPathAndName(new List <NodeType> { ActiveSchema.NodeTypes["User"], ActiveSchema.NodeTypes["Group"] }, false, domainPath, false, Name).Nodes; var nodeList = nodes as NodeList <Node>; if (nodeList != null) { identifiers = nodeList.GetIdentifiers(); count = nodeList.Count; } else { identifiers = nodes.Select(x => x.Id); count = identifiers.Count(); } } if (count > 1 || (count == 1 && identifiers.First() != this.Id)) { var ids = String.Join(", ", (from x in identifiers select x.ToString()).ToArray()); throw GetUniqueUserException(domainPath, ids); } }
private static SortedDictionary <string, string> MapSkin(Node skin) { NodeQueryResult result; if (RepositoryInstance.ContentQueryIsAllowed) { var query = new NodeQuery(); query.Add(new StringExpression(StringAttribute.Path, StringOperator.StartsWith, skin.Path)); result = query.Execute(); } else { result = NodeQuery.QueryNodesByPath(skin.Path, false); } var dict = new SortedDictionary <string, string>(); foreach (Node n in result.Nodes) { if (n.Id != skin.Id) { var relpath = n.Path.Substring(skin.Path.Length + 1); if (!dict.ContainsKey(relpath)) { dict.Add(relpath, n.Path); } } } return(dict); }
private void Load() { // search for all Resource content NodeQuery query = new NodeQuery(); query.Add(new StringExpression(StringAttribute.Path, StringOperator.StartsWith, String.Concat(Repository.ResourceFolderPath, RepositoryPath.PathSeparator))); query.Add(new TypeExpression(ActiveSchema.NodeTypes["Resource"])); // Elevation: caching all string resource files // is independent from the current user. using (new SystemAccount()) { IEnumerable <Node> nodes = null; if (StorageContext.Search.IsOuterEngineEnabled && StorageContext.Search.SearchEngine != InternalSearchEngine.Instance) { nodes = query.Execute().Nodes.OrderBy(i => i.Index); } else { var r = NodeQuery.QueryNodesByTypeAndPath(ActiveSchema.NodeTypes["Resource"] , false , String.Concat(Repository.ResourceFolderPath, RepositoryPath.PathSeparator) , true); nodes = r.Nodes.OrderBy(i => i.Index); } ParseAll(nodes); } }
private ActionResult SearchNodeQuery(string searchStr, string searchRoot, string contentTypes) { if (!string.IsNullOrEmpty(searchStr)) { // simple nodequery var query = new NodeQuery(); query.Add(new SearchExpression(searchStr)); var nodes = query.Execute().Nodes; // filter with path if (!string.IsNullOrEmpty(searchRoot)) { nodes = nodes.Where(n => n.Path.StartsWith(searchRoot)); } // filter with contenttypes if (!string.IsNullOrEmpty(contentTypes)) { var contentTypesArr = GetContentTypes(contentTypes); nodes = nodes.Where(n => contentTypesArr.Contains(n.NodeType.Name)); } var contents = nodes.Where(n => n != null).Select(n => new Content(n, true, false, false, false, 0, 0)); return(Json(contents.ToArray(), JsonRequestBehavior.AllowGet)); } else { if (string.IsNullOrEmpty(searchRoot) && string.IsNullOrEmpty(contentTypes)) { return(Json(null, JsonRequestBehavior.AllowGet)); } var query = new NodeQuery(); var andExpression = new ExpressionList(ChainOperator.And); query.Add(andExpression); // filter with path if (!string.IsNullOrEmpty(searchRoot)) { andExpression.Add(new StringExpression(StringAttribute.Path, StringOperator.StartsWith, searchRoot)); } // filter with contenttypes if (!string.IsNullOrEmpty(contentTypes)) { var contentTypesArr = GetContentTypes(contentTypes); var orExpression = new ExpressionList(ChainOperator.Or); foreach (var contentType in contentTypesArr) { orExpression.Add(new TypeExpression(NodeType.GetByName(contentType), true)); } andExpression.Add(orExpression); } var nodes = query.Execute().Nodes; var contents = nodes.Select(n => new Content(n, true, false, false, false, 0, 0)); return(Json(contents.ToArray(), JsonRequestBehavior.AllowGet)); } }
public static LucQuery Create(NodeQuery nodeQuery) { NodeQueryParameter[] parameters; var result = new LucQuery(); SortField[] sortFields; string oldQueryText; var compiler = new SnLucCompiler(); var compiledQueryText = compiler.Compile(nodeQuery, out parameters); sortFields = (from order in nodeQuery.Orders select new SortField( GetFieldNameByPropertyName(order.PropertyName), GetSortType(order.PropertyName), order.Direction == OrderDirection.Desc)).ToArray(); oldQueryText = compiler.CompiledQuery.ToString(); oldQueryText = oldQueryText.Replace("[*", "[ ").Replace("*]", " ]").Replace("{*", "{ ").Replace("*}", " }"); var newQuery = new SnLucParser().Parse(oldQueryText); result.Query = newQuery; // compiler.CompiledQuery, result.User = nodeQuery.User; result.SortFields = sortFields; result.StartIndex = nodeQuery.Skip; result.PageSize = nodeQuery.PageSize; result.Top = nodeQuery.Top; result.EnableAutofilters = FilterStatus.Disabled; result.EnableLifespanFilter = FilterStatus.Disabled; //TODO: QUICK: route through NodeQuery result.QueryExecutionMode = QueryExecutionMode.Default; return(result); }
//============================================================ Interface public static void Preload() { if (!Repository.WarmupEnabled) { Logger.WriteInformation(Logger.EventId.NotDefined, "***** Warmup is not enabled, skipped."); return; } //types ThreadPool.QueueUserWorkItem(delegate { PreloadTypes(); }); //template replacers and resolvers ThreadPool.QueueUserWorkItem(delegate { TemplateManager.Init(); }); ThreadPool.QueueUserWorkItem(delegate { NodeQuery.InitTemplateResolvers(); }); //jscript evaluator ThreadPool.QueueUserWorkItem(delegate { JscriptEvaluator.Init(); }); //xslt ThreadPool.QueueUserWorkItem(delegate { PreloadXslt(); }); //content templates ThreadPool.QueueUserWorkItem(delegate { PreloadContentTemplates(); }); //preload controls ThreadPool.QueueUserWorkItem(delegate { PreloadControls(); }); //preload security items ThreadPool.QueueUserWorkItem(delegate { PreloadSecurity(); }); }
private static IEnumerable <Node> GetAllPages() { var query = new NodeQuery(); query.Add(new TypeExpression(ActiveSchema.NodeTypes["Page"], true)); return(query.Execute().Nodes); }
protected SiteMenuNodeEnumerator(string path, ExecutionHint executionHint, NodeQuery filter, int?depth, string contextPath, bool getContextChildren) : base(path, executionHint, filter, depth) { _contextPath = contextPath; _getContextChildren = getContextChildren; }
private void ReadSkinStructure() { //CONDITIONAL EXECUTE Node[] nodes; if (StorageContext.Search.IsOuterEngineEnabled && StorageContext.Search.SearchEngine != InternalSearchEngine.Instance) { var query = new NodeQuery(); query.Add(new StringExpression(StringAttribute.Path, StringOperator.StartsWith, Repository.SkinRootFolderPath)); query.Add(new TypeExpression(NodeType.GetByName("Skin"))); nodes = query.Execute().Nodes.ToArray(); } else { nodes = NodeQuery.QueryNodesByTypeAndPath(NodeType.GetByName("Skin"), false, Repository.SkinRootFolderPath, false).Nodes.ToArray(); } try { _skinMapLock.TryEnterWriteLock(LockHandler.DefaultLockTimeOut); foreach (Node n in nodes) { _skinMap.Add(n.Name, MapSkin(n)); } } finally { if (_skinMapLock.IsWriteLockHeld) { _skinMapLock.ExitWriteLock(); } } }
private void Initialize() { using (new SenseNet.ContentRepository.Storage.Security.SystemAccount()) { _contentPaths = new Dictionary <string, string>(); _contentTypes = new Dictionary <string, ContentType>(); // temporary save: read enumerator only once var contentTypes = new List <ContentType>(); var result = NodeQuery.QueryNodesByTypeAndPath(ActiveSchema.NodeTypes["ContentType"], false, String.Concat(Repository.ContentTypesFolderPath, SnCS.RepositoryPath.PathSeparator), true); foreach (ContentType contentType in result.Nodes) { contentTypes.Add(contentType); _contentPaths.Add(contentType.Name, contentType.Path); _contentTypes.Add(contentType.Name, contentType); } foreach (ContentType contentType in contentTypes) { if (contentType.ParentTypeName == null) { contentType.SetParentContentType(null); } else { contentType.SetParentContentType(_contentTypes[contentType.ParentTypeName]); } } AllFieldNames = contentTypes.SelectMany(t => t.FieldSettings.Select(f => f.Name)).Distinct().ToList(); FinalizeAllowedChildTypes(AllFieldNames); FinalizeIndexingInfo(); } }
//public object GetIndexDocumentInfo(Node node) //{ // return IndexDocumentInfo.Create(node); //} public IEnumerable<int> Execute(NodeQuery nodeQuery) { var query = LucQuery.Create(nodeQuery); var lucObjects = query.Execute(); return from lucObject in lucObjects select lucObject.NodeId; //return from lucObject in lucObjects select lucObject.VersionId; }
private List <string> SearchData(string appTypeName) { //CONDITIONAL EXECUTE NodeQueryResult result; if (StorageContext.Search.IsOuterEngineEnabled && StorageContext.Search.SearchEngine != InternalSearchEngine.Instance) { var q = new NodeQuery(new TypeExpression(ActiveSchema.NodeTypes["Folder"]), new StringExpression(StringAttribute.Name, StringOperator.Equal, appTypeName)); result = q.Execute(); } else { result = NodeQuery.QueryNodesByTypeAndPathAndName(ActiveSchema.NodeTypes["Folder"], false, null, false, appTypeName); } var data = new List <string>(); foreach (var node in result.Nodes) { foreach (var node1 in NodeEnumerator.GetNodes(node.Path).Where(n => n.Id != node.Id).OrderBy(x => x.Name)) { data.Add(node1.Path); } } Logger.WriteVerbose("ApplicationCache is created.", Logger.EmptyCategoryList, new Dictionary <string, object> { { "AppTypeName", appTypeName }, { "Count", data.Count } }); return(data); }
/// <summary> /// Returns an existing <see cref="Aspect"/> by the given name. /// If it is not found, returns null. /// </summary> /// <param name="name">Name of the <see cref="Aspect"/>.</param> public static Aspect LoadAspectByName(string name) { // IMPORTANT: // We can't use external query here because this method is called during indexing! // It would mean trying to query the index while writing to it, which would result in a deadlock. // For this reason, this method uses its own cache for finding aspects. // Try to find the aspect in cache var cacheKey = "SN_AspectCacheByName_" + name; var aspect = Cache.Get(cacheKey) as Aspect; if (aspect == null) { // Find aspect via node query. // DO NOT replace this call with either Linq or Content Query for the reasons detailed above! var result = NodeQuery.QueryNodesByTypeAndName(ActiveSchema.NodeTypes[typeof(Aspect).Name], false, name); aspect = result.Nodes.FirstOrDefault() as Aspect; // If not found, return null if (aspect == null) { return(null); } // Store in cache var dependency = CacheDependencyFactory.CreateNodeDependency(aspect); Cache.Insert(cacheKey, aspect, dependency); } return(aspect); }
//========================================================================== Helper methods private static void RemoveWorkflow(ContentList list) { // check if any workflow is running currently var targetPath = RepositoryPath.Combine(list.Path, "Workflows/MailProcess"); IEnumerable <Node> runningWorkflows; if (SearchManager.ContentQueryIsAllowed) { runningWorkflows = Content.All.DisableAutofilters().Where( c => c.TypeIs("MailProcessorWorkflow") && (string)c["WorkflowStatus"] == "$1" && c.InFolder(targetPath)).AsEnumerable().Select(c => c.ContentHandler); } else { runningWorkflows = NodeQuery.QueryNodesByTypeAndPathAndProperty(ActiveSchema.NodeTypes["MailProcessorWorkflow"], false, targetPath, false, new List <QueryPropertyData> { new QueryPropertyData { PropertyName = "WorkflowStatus", QueryOperator = Operator.Equal, Value = "1" } }).Nodes; } foreach (var wfnode in runningWorkflows) { wfnode.ForceDelete(); } }
internal static NodeQueryResult GetAllPage() { NodeQuery query = new NodeQuery(); query.Add(new TypeExpression(ActiveSchema.NodeTypes["Page"], true)); return(query.Execute()); }
protected SiteMenuNodeEnumerator(string path, ExecutionHint executionHint, NodeQuery filter, int? depth, string contextPath, bool getContextChildren) : base(path, executionHint, filter, depth) { _contextPath = contextPath; _getContextChildren = getContextChildren; }
public IEnumerable <int> Execute(NodeQuery nodeQuery) { var query = LucQuery.Create(nodeQuery); var lucObjects = query.Execute(); return(from lucObject in lucObjects select lucObject.NodeId); }
protected override void ParseConfiguration(Dictionary <string, object> info) { base.ParseConfiguration(info); _allowMultiple = GetConfigurationNullableValue <bool>(info, AllowMultipleName, null); _fieldName = GetConfigurationStringValue(info, FieldNameName, null); object temp; if (info.TryGetValue(AllowedTypesName, out temp)) { _allowedTypes = new List <string>((string[])temp); } if (info.TryGetValue(SelectionRootName, out temp)) { _selectionRoots = new List <string>((string[])temp); } if (info.TryGetValue(QueryName, out temp)) { _query = NodeQuery.Parse((string)temp); } foreach (var path in _selectionRoots) { if (path != ".") { try { RepositoryPath.CheckValidPath(path); } catch (InvalidPathException e) //rethrow { throw new InvalidPathException(String.Concat("Given path is invalid in SelectionRoot element. Field name: '", this.Name, "', path: '", path, "'. Reason: ", e.Message)); } } } }
protected override void SetDefaults() { _allowMultiple = null; _allowedTypes = null; _selectionRoots = null; _query = null; }
protected override IEnumerable<Node> GetEvents() { var query = new NodeQuery(ChainOperator.And); query.Add(new StringExpression(StringAttribute.Path, StringOperator.StartsWith, CalendarPath)); query.Add(new TypeExpression(ActiveSchema.NodeTypes["Book"])); var results = query.Execute().Nodes; return results; }
public static IEnumerable<Node> GetNodes(string path, ExecutionHint hint, NodeQuery filter, int? depth, string contextPath, bool getContextChildren) { if (path == null) throw new ArgumentNullException("path"); return new SiteMenuNodeEnumerator(path, hint, filter, depth, contextPath, getContextChildren); }
//====================================================================================== INodeQueryCompiler Members public string Compile(NodeQuery query, out NodeQueryParameter[] parameters) { _nodeQuery = query; CompiledQuery = TreeWalker(query); parameters = new NodeQueryParameter[0]; return CompiledQuery.ToString(); }
public static IEnumerable<Node> GetPortletsFromRepo() { var query = new NodeQuery(); var expression = new ExpressionList(ChainOperator.And); expression.Add(new StringExpression(StringAttribute.Path, StringOperator.StartsWith, PortletsFolderPath)); expression.Add(new TypeExpression(NodeType.GetByName("Portlet"))); query.Add(expression); return query.Execute().Nodes; }
public static SearchFolder Create(NodeQuery query) { var folder = new SearchFolder { _query = query, Children = query.Execute().Nodes }; return folder; }
public static void RemoveContentTypes() { //-- T1 torli a tobbit is var nodeTypeName = "T1"; var nodeType = ActiveSchema.NodeTypes[nodeTypeName]; if (nodeType != null) { NodeQuery query = new NodeQuery(); query.Add(new TypeExpression(nodeType)); foreach (var nodeId in query.Execute().Identifiers) Node.ForceDelete(nodeId); } ContentType ct = ContentType.GetByName(nodeType.Name); if (ct != null) ct.Delete(); }
private void SetPageData() { if (this.SmartUrl == null || this.CopyInProgress) { var savedFlag = SmartUrlChanged; this.SmartUrl = string.Empty; SmartUrlChanged = savedFlag; } if (this.SmartUrl != String.Empty) { NodeQueryResult result; using (new SystemAccount()) { if (StorageContext.Search.IsOuterEngineEnabled && StorageContext.Search.SearchEngine != InternalSearchEngine.Instance) { //this NodeQuery will be compiled to LucQuery because the outer engine is enabled var pageQuery = new NodeQuery(); pageQuery.Add(new TypeExpression(ActiveSchema.NodeTypes[typeof (Page).Name])); pageQuery.Add(new StringExpression(ActiveSchema.PropertyTypes["SmartUrl"], StringOperator.Equal, this.SmartUrl)); pageQuery.Add(new NotExpression(new StringExpression(StringAttribute.Path, StringOperator.Equal, this.Path))); result = pageQuery.Execute(); } else { //we need to execute a direct database query because the outer engine is disabled result = NodeQuery.QueryNodesByTypeAndPathAndProperty( ActiveSchema.NodeTypes[typeof (Page).Name], false, null, false, new List<QueryPropertyData>(new[] { new QueryPropertyData {PropertyName = "SmartUrl", Value = this.SmartUrl}, new QueryPropertyData {PropertyName = "Path", Value = this.Path, QueryOperator = Operator.NotEqual}})); } } if (result.Count > 0) { var page = result.Nodes.First() as Page; if (page != null) throw new Exception(String.Concat("'", this.SmartUrl, "' smartUrl is already mapped to page with path '", page.Path, "'")); } } SetBinary(); }
private LiteralControl CreateLastExport() { if (CurrentForm != null) { NodeQuery query = new NodeQuery(); query.Add(new IntExpression(IntAttribute.ParentId, ValueOperator.Equal, CurrentForm.Id)); query.Add(new StringExpression(StringAttribute.Name, StringOperator.EndsWith, ".csv")); query.Add(new TypeExpression(ActiveSchema.NodeTypes["File"])); query.Orders.Add(new SearchOrder(DateTimeAttribute.CreationDate, OrderDirection.Desc)); query.Top = 1; var nodeList = query.Execute(); if (nodeList.Count > 0) { Node node = nodeList.Nodes.First<Node>(); return new LiteralControl(string.Concat("<br />", HttpContext.GetGlobalResourceObject("FormPortlet", "LastExport") as string, "<a target='_blank' href='", node.Path, "'/>", node.CreationDate.ToString("yyyy.MM.dd HH:mm:ss"), "</a>")); } } return null; }
private FieldValidationResult ValidateWithQuery(List<Node> list, NodeQuery query) { var x = query.Execute(); List<int> idList = x.Identifiers.ToList(); idList.Sort(); foreach (Node node in list) { if (!idList.Contains(node.Id)) { var result = new FieldValidationResult(QueryName); result.AddParameter("Path", node.Path); return result; } } return FieldValidationResult.Successful; }
public override bool SetProperty(string name, object value) { var found = base.SetProperty(name, value); if (found) return true; var sv = value as string; switch (name) { case QueryName: if (!string.IsNullOrEmpty(sv)) _query = NodeQuery.Parse(sv); found = true; break; case AllowedTypesName: var types = value as IEnumerable<Node>; if (types != null && types.Count() > 0) { _allowedTypes = (from node in types select node.Name).ToList(); } found = true; break; case SelectionRootName: if (!string.IsNullOrEmpty(sv)) { var sl = sv.Split(new[] { ' ', ',', ';' }, StringSplitOptions.RemoveEmptyEntries); _selectionRoots = new List<string>(sl); } found = true; break; } return found; }
protected override void ParseConfiguration(XPathNavigator configurationElement, IXmlNamespaceResolver xmlNamespaceResolver, ContentType contentType) { //...xmlns="http://schemas.sensenet.com/SenseNet/ContentRepository/SearchExpression" //.... //<Configuration> // <AllowMultiple>true<AllowMultiple> // <AllowedTypes> // <Type>Folder</Type> // <Type>File</Type> // </AllowedTypes> // <SelectionRoot> // <Path>/Root/.../1</Path> // <Path>/Root/.../2</Path> // <SelectionRoot> // <Query> // <q:And> // <q:String op="StartsWith" property="Path">.</q:String> // <q:String op="NotEqual" property="Name">Restricted</q:String> // </q:And> // </Query> //</Configuration> foreach (XPathNavigator element in configurationElement.SelectChildren(XPathNodeType.Element)) { switch (element.LocalName) { case AllowMultipleName: _allowMultiple = element.InnerXml == "true"; break; case AllowedTypesName: _allowedTypes = new List<string>(); foreach (XPathNavigator typeElement in element.SelectChildren(TypeName, element.NamespaceURI)) { string typeName = typeElement.InnerXml; _allowedTypes.Add(typeName); } break; case SelectionRootName: _selectionRoots = new List<string>(); foreach (XPathNavigator pathElement in element.SelectChildren(PathName, element.NamespaceURI)) { string path = pathElement.InnerXml; if (path != ".") { try { RepositoryPath.CheckValidPath(path); } catch (InvalidPathException e) //rethrow { throw new InvalidPathException(String.Concat("Given path is invalid in SelectionRoot element. ContentType: ", contentType.Name, ", Field name: '", this.Name, "', path: '", path, "'. Reason: ", e.Message)); } } _selectionRoots.Add(path); } break; case QueryName: var sb = new StringBuilder(); sb.Append("<SearchExpression xmlns=\"").Append(NodeQuery.XmlNamespace).Append("\">"); sb.Append(element.InnerXml); sb.Append("</SearchExpression>"); _query = NodeQuery.Parse(sb.ToString()); break; case FieldNameName: _fieldName = element.InnerXml; break; } } }
public static NodeQueryResult GetWebContentTypeList() { var contentTypeNames = ConfigurationManager.AppSettings[ContentTypeNameListKey]; if (String.IsNullOrEmpty(contentTypeNames)) contentTypeNames = DefaultContentTypeName; var list = contentTypeNames.Split(','); var validCtdNames = new List<string>(); foreach (var c in list) if (IsValidContentType(c.Trim())) validCtdNames.Add(c.Trim()); var expressionList = new ExpressionList(ChainOperator.Or); var query = new NodeQuery(); foreach (var ctd in validCtdNames) { var stringExpressionValue = RepositoryPath.Combine(Repository.ContentTypesFolderPath, String.Concat(ActiveSchema.NodeTypes[ctd].NodeTypePath, "/")); expressionList.Add(new StringExpression(StringAttribute.Path, StringOperator.StartsWith, stringExpressionValue)); } if (validCtdNames.Count == 0) { var stringExpressionValue = RepositoryPath.Combine(Repository.ContentTypesFolderPath, String.Concat(ActiveSchema.NodeTypes[DefaultContentTypeName].NodeTypePath, "/")); expressionList.Add(new StringExpression(StringAttribute.Path, StringOperator.StartsWith, stringExpressionValue)); } query.Add(expressionList); return query.Execute(); }
private void LoadWorkspaceList() { var query = new NodeQuery(); var path = ActiveSchema.NodeTypes["Workspace"].NodeTypePath; var s = String.Concat(Repository.ContentTypesFolderPath, RepositoryPath.PathSeparator, path, RepositoryPath.PathSeparator); query.Add(new StringExpression(StringAttribute.Path, StringOperator.StartsWith, s)); var nodes = query.Execute().Nodes; FillWorkspaceListControl(WorkspaceListControl, nodes); }
private ActionResult SearchNodeQuery(string searchStr, string searchRoot, string contentTypes) { if (!string.IsNullOrEmpty(searchStr)) { // simple nodequery var query = new NodeQuery(); query.Add(new SearchExpression(searchStr)); var nodes = query.Execute().Nodes; // filter with path if (!string.IsNullOrEmpty(searchRoot)) nodes = nodes.Where(n => n.Path.StartsWith(searchRoot)); // filter with contenttypes if (!string.IsNullOrEmpty(contentTypes)) { var contentTypesArr = GetContentTypes(contentTypes); nodes = nodes.Where(n => contentTypesArr.Contains(n.NodeType.Name)); } var contents = nodes.Where(n => n != null).Select(n => new Content(n, true, false, false, false, 0, 0)); return Json(contents.ToArray(), JsonRequestBehavior.AllowGet); } else { if (string.IsNullOrEmpty(searchRoot) && string.IsNullOrEmpty(contentTypes)) return Json(null, JsonRequestBehavior.AllowGet); var query = new NodeQuery(); var andExpression = new ExpressionList(ChainOperator.And); query.Add(andExpression); // filter with path if (!string.IsNullOrEmpty(searchRoot)) andExpression.Add(new StringExpression(StringAttribute.Path, StringOperator.StartsWith, searchRoot)); // filter with contenttypes if (!string.IsNullOrEmpty(contentTypes)) { var contentTypesArr = GetContentTypes(contentTypes); var orExpression = new ExpressionList(ChainOperator.Or); foreach (var contentType in contentTypesArr) { orExpression.Add(new TypeExpression(NodeType.GetByName(contentType), true)); } andExpression.Add(orExpression); } var nodes = query.Execute().Nodes; var contents = nodes.Select(n => new Content(n, true, false, false, false, 0, 0)); return Json(contents.ToArray(), JsonRequestBehavior.AllowGet); } }
public static LucQuery Create(NodeQuery nodeQuery) { NodeQueryParameter[] parameters; var result = new LucQuery(); result.TraceInfo.BeginCrossCompilingTime(); SortField[] sortFields; string oldQueryText; try { var compiler = new SnLucCompiler(); var compiledQueryText = compiler.Compile(nodeQuery, out parameters); sortFields = (from order in nodeQuery.Orders select new SortField( GetFieldNameByPropertyName(order.PropertyName), GetSortType(order.PropertyName), //SortField.STRING, order.Direction == OrderDirection.Desc)).ToArray(); oldQueryText = compiler.CompiledQuery.ToString(); oldQueryText = oldQueryText.Replace("[*", "[ ").Replace("*]", " ]").Replace("{*", "{ ").Replace("*}", " }"); result.TraceInfo.InputText = oldQueryText; } finally { result.TraceInfo.FinishCrossCompilingTime(); } result.TraceInfo.BeginParsingTime(); Query newQuery; try { newQuery = new SnLucParser().Parse(oldQueryText); } finally { result.TraceInfo.FinishParsingTime(); } result.Query = newQuery; // compiler.CompiledQuery, result.User = nodeQuery.User; result.SortFields = sortFields; result.StartIndex = nodeQuery.Skip; result.PageSize = nodeQuery.PageSize; result.Top = nodeQuery.Top; result.EnableAutofilters = false; result.EnableLifespanFilter = false; return result; }
public void FieldSetting_Analyzer() { var start = ContentTypeManager.Current; var globalAnalyzersBefore = StorageContext.Search.SearchEngine.GetAnalyzers(); string ctd = @"<?xml version='1.0' encoding='utf-8'?> <ContentType name='FieldSetting_Analyzer' parentType='GenericContent' handler='SenseNet.ContentRepository.GenericContent' xmlns='http://schemas.sensenet.com/SenseNet/ContentRepository/ContentTypeDefinition'> <Fields> <Field name='TestString1' type='ShortText'> <Indexing> <Analyzer>Lucene.Net.Analysis.Standard.StandardAnalyzer</Analyzer> </Indexing> </Field> <Field name='TestString2' type='ShortText'> <Indexing> <Analyzer>Lucene.Net.Analysis.WhitespaceAnalyzer</Analyzer> </Indexing> </Field> </Fields> </ContentType>"; ContentTypeInstaller.InstallContentType(ctd); var restart = ContentTypeManager.Current; var globalAnalyzersAfter = StorageContext.Search.SearchEngine.GetAnalyzers(); var contentType = ContentType.GetByName("FieldSetting_Analyzer"); var analyzer0 = contentType.GetFieldSettingByName("TestString1").IndexingInfo.Analyzer; var analyzer1 = contentType.GetFieldSettingByName("TestString2").IndexingInfo.Analyzer; Assert.IsTrue(analyzer0 == "Lucene.Net.Analysis.Standard.StandardAnalyzer", "#01"); Assert.IsTrue(analyzer1 == "Lucene.Net.Analysis.WhitespaceAnalyzer", "#02"); var analyzerInfo = StorageContext.Search.SearchEngine.GetAnalyzers(); Assert.IsTrue(analyzerInfo.ContainsKey("TestString1"), "#03"); Assert.IsTrue(analyzerInfo["TestString1"].FullName == "Lucene.Net.Analysis.Standard.StandardAnalyzer", "#04"); Assert.IsTrue(analyzerInfo.ContainsKey("TestString2"), "#05"); Assert.IsTrue(analyzerInfo["TestString2"].FullName == "Lucene.Net.Analysis.WhitespaceAnalyzer", "#06"); var content = Content.CreateNew("FieldSetting_Analyzer", _testRoot, "test"); content["TestString1"] = "asdf,qwer,zxcv"; content.Save(); var query = new NodeQuery(new StringExpression(ActiveSchema.PropertyTypes["TestString1"], StringOperator.Equal, "qwer")); var result = query.Execute(); Assert.IsTrue(result.Count > 0, "#11"); }
public IEnumerable<int> Execute(NodeQuery nodeQuery) { throw new NotSupportedException(); }
private string GetCSV(Form form) { StringBuilder sb = new StringBuilder(); DateTime? fromDate = GetDate(tbFrom.Text); DateTime? toDate = GetDate(tbTo.Text); if (fromDate == null || toDate == null) { throw new Exception(HttpContext.GetGlobalResourceObject("FormPortlet", "IncorrectDateFormat") as string); } SenseNet.ContentRepository.Storage.Security.AccessProvider.ChangeToSystemAccount(); NodeQuery query = new NodeQuery(); query.Add(new StringExpression(StringAttribute.Path, StringOperator.StartsWith, string.Concat(form.Path, "/"))); query.Add(new TypeExpression(ActiveSchema.NodeTypes["FormItem"])); query.Add(new DateTimeExpression(DateTimeAttribute.CreationDate, ValueOperator.GreaterThanOrEqual, fromDate)); query.Add(new DateTimeExpression(DateTimeAttribute.CreationDate, ValueOperator.LessThan, toDate)); var result = query.Execute(); SenseNet.ContentRepository.Storage.Security.AccessProvider.RestoreOriginalUser(); if (result != null && result.Count > 0) { bool first = true; foreach (Node node in result.Nodes) { if (node is FormItem) { FormItem fi = node as FormItem; if (first) { CreateHeader(fi, sb); first = false; } CreateLine(fi, sb); } } } return sb.ToString(); }
private IEnumerable<Node> GetPageList(string pagePath, bool isRecursive) { var query = new NodeQuery(); query.Add(new StringExpression(StringAttribute.Path, StringOperator.StartsWith, pagePath)); if (isRecursive) query.Add(new TypeExpression(ActiveSchema.NodeTypes["Page"])); else query.Add(new TypeExpression(ActiveSchema.NodeTypes["Page"], true)); return query.Execute().Nodes; }
private void ResetEvents() { var q = new NodeQuery( new StringExpression(StringAttribute.Path, StringOperator.StartsWith, TestRoot.Path + "/"), new StringExpression(StringAttribute.Name, StringOperator.Equal, "Events")); q.Orders.Add(new SearchOrder(StringAttribute.Path, OrderDirection.Desc)); foreach (var node in q.Execute().Nodes) node.ForceDelete(); }
public void ProcessRequest(HttpContext context) { // requested page path without the handled extension string requestPath = PortalContext.Current.RepositoryPath; string sitemapNodePath = requestPath.Substring(0, requestPath.LastIndexOf(".map")); requestPath = requestPath.Substring(0, requestPath.LastIndexOf('/')); NodeQuery query; bool listHidden = false; string siteUrl = ""; // get sitemap configuration node at requested path Node sitemapNode = Node.LoadNode(sitemapNodePath); if (sitemapNode == null) { context.Response.StatusCode = 404; throw new HttpException(404, "Sitemap configuration node not found"); } var propQuery = "Query"; var propListHidden = "ListHidden"; var propHidden = "Hidden"; var propSiteUrl = "SiteUrl"; // invalid sitemap configuration node if(!(sitemapNode.HasProperty(propQuery) && sitemapNode.HasProperty(propListHidden) && sitemapNode.HasProperty(propSiteUrl))) { context.Response.StatusCode = 400; throw new HttpException(400, "Invalid sitemap configuration node (Query, ListHidden or SiteUrl properties missing, update CTD)"); } var queryString = sitemapNode.GetProperty<string>(propQuery); if ((queryString == null) || (queryString == "")) { // default query query = new NodeQuery(); query.Add(new StringExpression(StringAttribute.Path, StringOperator.StartsWith, requestPath)); query.Add(new TypeExpression(ActiveSchema.NodeTypes["Page"])); } else { try { query = NodeQuery.Parse(queryString); } catch (Exception) //rethrow { context.Response.StatusCode = 400; throw new HttpException(400, "Invalid query string"); } } listHidden = sitemapNode.GetProperty<int>(propListHidden) == 1; siteUrl = sitemapNode.GetProperty<string>(propSiteUrl); if (String.IsNullOrEmpty(siteUrl)) siteUrl = PortalContext.Current.SiteUrl; // query nodes of "Page" type under the requested page var pages = query.Execute().Nodes; Node[] goodPages; // exclude pages under hidden pages from list if (!listHidden) { string[] InvalidPaths = pages.Where(page => page.GetProperty<int>(propHidden) == 1). Select(page => page.Path).ToArray(); goodPages = pages.Where(page => InvalidPaths.Where(ip => page.Path.StartsWith(ip)).Count() == 0). Select(page => page).ToArray(); } else { goodPages = pages.ToArray(); } // set up object model for sitemap Urlset urlset = new Urlset(); urlset.Urls = goodPages.Select(page => new Urlset.Url() { loc = getPageUrl(page, siteUrl) }).ToList(); // output sitemap XML to http response context.Response.ContentType = "text/xml"; XmlSerializer ser = new XmlSerializer(typeof(Urlset)); ser.Serialize(context.Response.OutputStream, urlset); context.Response.OutputStream.Flush(); }
public void ActionFramework_AppStorageLoad() { var nt = ActiveSchema.NodeTypes["Application"]; var nq = new NodeQuery(); nq.Add(new TypeExpression(nt)); nq.Add(new StringExpression(StringAttribute.Path, StringOperator.Contains, string.Format("/{0}/", "(apps)"))); nq.Orders.Add(new SearchOrder(StringAttribute.Path, OrderDirection.Desc)); var result1 = nq.Execute(ExecutionHint.ForceRelationalEngine); var result2 = nq.Execute(ExecutionHint.ForceIndexedEngine); var paths1 = String.Join(Environment.NewLine, result1.Nodes.Select(n => n.Path).ToArray()); var paths2 = String.Join(Environment.NewLine, result2.Nodes.Select(n => n.Path).ToArray()); Assert.IsTrue(paths1 == paths2); // /Root/TestSiteForActionFramework/Sample/SubFolder/(apps)/This/App24 // /Root/TestSiteForActionFramework/Sample/(apps)/This/App12 // /Root/TestSiteForActionFramework/Sample/(apps)/Folder/App25 // /Root/TestSiteForActionFramework/Sample/(apps)/Folder/App24 // /Root/TestSiteForActionFramework/Sample/(apps)/Folder/App23 // /Root/TestSiteForActionFramework/Sample/(apps)/Folder/App22 // /Root/TestSiteForActionFramework/Sample/(apps)/Folder/App21 // /Root/TestSiteForActionFramework/(apps)/Folder/App6 // /Root/TestSiteForActionFramework/(apps)/Folder/App5 // /Root/TestSiteForActionFramework/(apps)/Folder/App4 // /Root/TestSiteForActionFramework/(apps)/Folder/App3 // /Root/TestSiteForActionFramework/(apps)/Folder/App25 // /Root/TestSiteForActionFramework/(apps)/Folder/App24 // /Root/TestSiteForActionFramework/(apps)/Folder/App23 // /Root/TestSiteForActionFramework/(apps)/Folder/App22 // /Root/TestSiteForActionFramework/(apps)/Folder/App21 // /Root/TestSiteForActionFramework/(apps)/Folder/App2 // /Root/TestSiteForActionFramework/(apps)/Folder/App12 // /Root/TestSiteForActionFramework/(apps)/Folder/App1 // /Root/TestSiteForActionFramework/(apps)/ContentList/ContentListApp3 // /Root/TestSiteForActionFramework/(apps)/ContentList/ContentListApp2 // /Root/TestSiteForActionFramework/(apps)/ContentList/ContentListApp1 // /Root/TestSiteForActionFramework/(apps)/ContentList/App6 // /Root/TestSiteForActionFramework/(apps)/ContentList/App1 }
private void Load() { // search for all Resource content NodeQuery query = new NodeQuery(); query.Add(new StringExpression(StringAttribute.Path, StringOperator.StartsWith, String.Concat(Repository.ResourceFolderPath, RepositoryPath.PathSeparator))); query.Add(new TypeExpression(ActiveSchema.NodeTypes["Resource"])); IEnumerable<Node> nodes = null; if (StorageContext.Search.IsOuterEngineEnabled && StorageContext.Search.SearchEngine != InternalSearchEngine.Instance) { nodes = query.Execute().Nodes.OrderBy(i => i.Index); } else { var r = NodeQuery.QueryNodesByTypeAndPath(ActiveSchema.NodeTypes["Resource"] , false , String.Concat(Repository.ResourceFolderPath, RepositoryPath.PathSeparator) , true); nodes = r.Nodes.OrderBy(i => i.Index); } ParseAll(nodes); ////-- sort by index //NodeComparer<Node> resourceComparer = new NodeComparer<Node>(); //result.Sort(resourceComparer); }
public void Content_CreateList() { string contentTypeName = "Automobile"; if (ContentTypeManager.Current.GetContentTypeByName(contentTypeName) == null) ContentTypeInstaller.InstallContentType(AutomobileHandler.ExtendedCTD); var idList = new List<int>(); for (int i = 1; i <= 5; i++) { string contentName = "AutoListItem" + i; SNC.Content auto = SNC.Content.Load(RepositoryPath.Combine(_testRoot.Path, contentName)); if (auto == null) auto = SNC.Content.CreateNew(contentTypeName, _testRoot, contentName); auto["Manufacturer"] = "Manuf" + i; auto.Save(); idList.Add(auto.Id); } //---- NodeQuery query = new NodeQuery(); query.Add(new TypeExpression(ActiveSchema.NodeTypes[contentTypeName])); query.Add(new StringExpression(StringAttribute.Name, StringOperator.StartsWith, "AutoListItem")); IEnumerable<SNC.Content> contentList = SNC.Content.Query(query); var contentListCount = contentList.ToList().Count; //---- foreach (var id in idList) Node.ForceDelete(id); //---- Assert.IsTrue(contentListCount == 5); }
void DeleteButton_Click(object sender, EventArgs e) { foreach (var view in ViewManager.GetViewsForContainer(this.FieldSettingNode.ContentList)) { var iv = view as IView; if (iv == null) continue; iv.RemoveColumn(this.FieldSettingNode.FieldSetting.FullName); ((SenseNet.Portal.UI.ContentListViews.Handlers.ViewBase) iv).Save(); } //TEMP: if this is a reference field, remove all the values before deleting //The problem with this method is that it changes the 'modified by' and 'modified on' //values of _all_ the contents... if (FieldSettingNode.FieldSetting is ReferenceFieldSetting) { var contentList = GetContextNode() as ContentList; if (contentList != null) { try { using (new SystemAccount()) { var fn = contentList.GetPropertySingleId(this.FieldName); var pt = contentList.PropertyTypes[fn]; var nq = new NodeQuery(); nq.Add(new StringExpression(StringAttribute.Path, StringOperator.StartsWith, contentList.Path + RepositoryPath.PathSeparator)); //TODO: check while this doesn't work //nq.Add(new ReferenceExpression(pt)); foreach (var node in nq.Execute().Nodes) { if (!node.HasProperty(fn)) continue; node.ClearReference(fn); node.Save(); } } } catch (Exception ex) { Logger.WriteException(ex); } } } try { this.FieldSettingNode.Delete(); CallDone(); } catch (Exception ex) { Logger.WriteException(ex); this.Controls.Add(new LiteralControl(ex.ToString())); } }
public IEnumerable<ForumEntry> GetReplies() { var q = new NodeQuery(); q.Add(new IntExpression(IntAttribute.ParentId, ValueOperator.Equal, this.ParentId)); q.Add(new ReferenceExpression(PropertyType.GetByName("ReplyTo"), new IntExpression(IntAttribute.Id, ValueOperator.Equal, this.Id))); var res = q.Execute(); if (res.Count == 0) return new List<ForumEntry>(); return res.Nodes.OfType<ForumEntry>(); }