/// <summary> /// Retrieves comments for a given Post/Content /// </summary> /// <param name="postid">Id of Post.</param> /// <returns></returns> public static QueryResult GetComments(int parentId) { var parent = NodeHead.Get(parentId); if (parent == null) { return(null); } var commentFolderPath = RepositoryPath.Combine(parent.Path, "Comments"); var settings = new QuerySettings { EnableAutofilters = FilterStatus.Disabled, Sort = new SortInfo[] { new SortInfo { FieldName = "CreationDate", Reverse = false } } }; var result = ContentQuery.Query("+InFolder:@0 +Type:Comment", settings, commentFolderPath); return(result); }
/// <summary> /// Get the search result. /// </summary> /// <param name="from">value of searching from</param> /// <param name="to">value of searching to</param> /// <returns>List of nodes which matches the search.</returns> private IEnumerable GetResult(string from, string to) { if (from == string.Empty || to == string.Empty) { return(null); } decimal.TryParse(from, out var fromD); decimal.TryParse(to, out var toD); fromD -= (decimal)0.01; toD += (decimal)0.01; var results = ContentQuery.Query("Rate:{" + $"{fromD:F2} TO {toD:F2}" + "}"); var contentsId = results.Identifiers.ToList(); var result = new NodeList <Node>(contentsId); return(result); }
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 = ParseQuery(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); }
public void ContentQueryTemplateReplacer_RecursiveQueryIntegration() { Test( true, builder => { builder.UseTraceCategories("Query"); }, () => { AddRootAccessibilityToAdmin(); var queryEngine = (InMemoryQueryEngine)Providers.Instance.SearchManager.SearchEngine.QueryEngine; queryEngine.ClearLog(); var expected = $"ExecuteQueryAndProject: Id:{User.Current.Id} .AUTOFILTERS:OFF"; ContentQuery.Query("Id:{{Id:@@CurrentUser.Id@@}}", QuerySettings.AdminSettings); var actual = queryEngine.GetLog().Split('\r', '\n').First(); Assert.AreEqual(expected, actual); }); }
private static void PreloadXslt() { try { QueryResult queryResult; var cc = 0; var timer = new Stopwatch(); timer.Start(); using (new SystemAccount()) { queryResult = ContentQuery.Query(SafeQueries.PreloadXslt); foreach (var nodeId in queryResult.Identifiers) { var head = NodeHead.Get(nodeId); try { if (head != null) { UI.PortletFramework.Xslt.GetXslt(head.Path, true); } } catch (Exception ex) { SnLog.WriteException(ex, "Error during xlst load: " + (head == null ? nodeId.ToString() : head.Path)); } cc++; } } timer.Stop(); SnLog.WriteInformation(string.Format("***** XSLT preload time: {0} ******* Count: {1} ({2})", timer.Elapsed, cc, queryResult.Count)); } catch (Exception ex) { SnLog.WriteException(ex); } }
public static void RetryAllFailedActions() { using (new SystemAccount()) { var qs = new QuerySettings { EnableLifespanFilter = false, EnableAutofilters = false }; var queryText = string.Format("TypeIs:File AND InTree:\"{0}\" .SORT:CreationDate", _actionPath); var q = ContentQuery.CreateQuery(queryText, qs); var result = q.Execute(); foreach (Node node in result.Nodes) { var failFile = node as File; if (failFile == null) { continue; } // restore ADAction object var stream = failFile.Binary.GetStream(); var serializer = new XmlSerializer(typeof(ADAction)); var adAction = serializer.Deserialize(stream) as ADAction; if (adAction == null) { continue; } try { adAction.Execute(); failFile.Delete(); } catch (Exception ex) //TODO: catch block { // re-execution failed again, save exception adAction.LastException = GetExceptionMsg(ex); SaveAction(adAction, failFile); } } } }
public ActionResult Index(SearchPage currentPage, string q) { var viewmodel = new SearchPageViewModel(currentPage); if (!string.IsNullOrWhiteSpace(q)) { // 1. only pages var onlyPages = new ContentQuery <SitePageData>(); // 2. free-text query var freeText = new FieldQuery(q); // 3. only what the current user can read var readAccess = new AccessControlListQuery(); readAccess.AddAclForUser(PrincipalInfo.Current, HttpContext); // 4. only under the Start page (to exclude Wastebasket, for example) var underStart = new VirtualPathQuery(); underStart.AddContentNodes(ContentReference.StartPage); // build the query from the expressions var query = new GroupQuery(LuceneOperator.AND); query.QueryExpressions.Add(freeText); query.QueryExpressions.Add(onlyPages); query.QueryExpressions.Add(readAccess); query.QueryExpressions.Add(underStart); // get the first page of ten results SearchResults results = searchHandler.GetSearchResults(query, 1, 10); viewmodel.SearchText = q; viewmodel.SearchResults = results.IndexResponseItems .Select(x => new Result { Title = x.Title, Description = x.DisplayText.TruncateAtWord(20), Url = GetExternalUrl(x).ToString() }).ToList(); } return(View(viewmodel)); }
public override QueryResult GetChildren(string text, QuerySettings settings, bool getAllChildren) { if (!string.IsNullOrEmpty(Query) || !string.IsNullOrEmpty(text)) { var cq = ContentQuery.CreateQuery(Query); if (EnableAutofilters != FilterStatus.Default) { cq.Settings.EnableAutofilters = (EnableAutofilters == FilterStatus.Enabled); } if (EnableLifespanFilter != FilterStatus.Default) { cq.Settings.EnableLifespanFilter = (EnableLifespanFilter == FilterStatus.Enabled); } if (settings != null) { cq.Settings = settings; } if ((cq.IsContentQuery || string.IsNullOrEmpty(this.Query)) && !string.IsNullOrEmpty(text)) { cq.AddClause(text); } if (cq.IsContentQuery) { //add SmartFolder's own children (with an Or clause) var excapedPath = this.Path.Replace("(", "\\(").Replace(")", "\\)"); cq.AddClause((getAllChildren ? string.Format("InTree:\"{0}\"", excapedPath) : string.Format("InFolder:\"{0}\"", excapedPath)), ChainOperator.Or); } else { cq.AddClause(new IntExpression(IntAttribute.ParentId, ValueOperator.Equal, this.Id), ChainOperator.Or); } var result = cq.Execute(); return(result); } return(QueryResult.Empty); }
protected override void OnDeletingPhysically(object sender, CancellableNodeEventArgs e) { base.OnDeletingPhysically(sender, e); if (!Path.StartsWith(RepositoryStructure.ImsFolderPath + RepositoryPath.PathSeparator)) { return; } // If we are deleting a container under the security folder, we have to check whether // we would delete users from protected groups. If any of the protected groups would // become empty, this will throw an exception. using (new SystemAccount()) { var userInSubtree = ContentQuery.Query(SafeQueries.UsersInSubtree, QuerySettings.AdminSettings, Path).Identifiers.ToArray(); User.AssertEnabledParentGroupMembers(userInSubtree); } }
//===================================================================================== Method protected override IEnumerable <Node> GetChildren() { if (!string.IsNullOrEmpty(Query)) { var cq = ContentQuery.CreateQuery(Query); if (EnableAutofilters != FilterStatus.Default) { cq.Settings.EnableAutofilters = (EnableAutofilters == FilterStatus.Enabled); } if (EnableLifespanFilter != FilterStatus.Default) { cq.Settings.EnableLifespanFilter = (EnableLifespanFilter == FilterStatus.Enabled); } var result = cq.Execute(); return(result.Nodes); } return(base.GetChildren()); }
public virtual async Task <IReadOnlyList <IEnrichedContentEntity> > GetReferencedContentsAsync(IEnumerable <DomainId> ids, CancellationToken ct) { Guard.NotNull(ids); return(await ContentCache.CacheOrQueryAsync(ids, async pendingIds => { await maxRequests.WaitAsync(ct); try { var q = Q.Empty.WithIds(pendingIds).WithoutTotal(); return await ContentQuery.QueryAsync(Context, q, ct); } finally { maxRequests.Release(); } })); }
public static IEnumerable <PostInfo> GetPostsForUser(User user, string profilePath) { if (user == null) { return(new PostInfo[0]); } // 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 settings = new QuerySettings { EnableAutofilters = FilterStatus.Disabled, Sort = new[] { new SortInfo("CreationDate", true) } }; var posts = ContentQuery.Query("(+CreatedById:@0 +Type:Post -PostType:@1) (+InTree:@2 +Type:Post)", settings, user.Id, (int)PostType.BigPost, profilePath).Nodes.Select(n => new PostInfo(n)); return(posts.OrderByDescending(p => p.CreationDate)); }
/// <summary> /// Determines whether [is user already subscribed]. /// </summary> /// <param name="item">The CalendarEvent item.</param> /// <param name="registeredItem">The registered item (output value).</param> /// <returns> /// <c>true</c> if [is user already subscribed]; otherwise, <c>false</c>. /// </returns> private static bool IsUserAlreadySubscribed(Node item, out string registeredItem) { var regForm = item.GetReference <Node>("RegistrationForm"); registeredItem = String.Empty; if (regForm != null) { var qt = string.Format("+Type:eventregistrationformitem +ParentId:{0} +CreatedById:{1} .AUTOFILTERS:OFF .LIFESPAN:OFF", regForm.Id, User.Current.Id); var result = ContentQuery.Query(qt); if (result.Count > 0) { registeredItem = NodeHead.Get(result.Identifiers.First()).Path; return(true); } } return(false); }
public void ContentQuery_RecursiveQuery_Empty() { ContentQuery q; IEnumerable <int> r; int id; q = new ContentQuery { Text = "+Members:{{Name:NOBODY42}} +Name:Administrators .AUTOFILTERS:OFF" }; r = q.ExecuteToIds(ExecutionHint.ForceIndexedEngine); Assert.IsTrue(r.Count() == 0, "#05"); q = new ContentQuery { Text = "Members:{{Name:NOBODY42}} Name:Administrators .AUTOFILTERS:OFF" }; r = q.ExecuteToIds(ExecutionHint.ForceIndexedEngine); Assert.IsTrue(r.Count() > 0, "#07"); id = r.First(); Assert.IsTrue(id == Group.Administrators.Id, "#08"); }
public virtual async Task <IResultList <IEnrichedContentEntity> > QueryContentsAsync(string schemaIdOrName, Q q, CancellationToken ct) { IResultList <IEnrichedContentEntity> contents; await maxRequests.WaitAsync(ct); try { contents = await ContentQuery.QueryAsync(Context, schemaIdOrName, q, ct); } finally { maxRequests.Release(); } ContentCache.SetMany(contents.Select(x => (x.Id, x)) !); return(contents); }
protected override NodeQueryResult QueryChildrenFromLucene(int thisId) { if (string.IsNullOrEmpty(_childrenFilter)) { return(base.QueryChildrenFromLucene(thisId)); } else { //We need to apply a query filter. Execute a content //query and create a node query result on-the-fly. var query = ContentQuery.CreateQuery("+ParentId:@0", null, thisId); if (!string.IsNullOrEmpty(_childrenFilter)) { query.AddClause(_childrenFilter); } return(new NodeQueryResult(query.ExecuteToIds(ExecutionHint.ForceIndexedEngine))); } }
public async Task <FeaturesDto> GetFeaturesAsync(int version = 0) { var result = new FeaturesDto { Features = new List <FeatureDto>(), Version = FeatureVersion }; if (client != null && version < FeatureVersion) { var query = new ContentQuery { Filter = $"data/version/iv ge {FeatureVersion}" }; var features = await client.GetAsync(query, flatten); result.Features.AddRange(features.Items.Select(x => x.Data)); } return(result); }
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)) { var queryText = (string)temp; if (queryText != null) { _query = ParseQuery(queryText); } } if (_selectionRoots != null) { 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)); } } } } }
public void Add_Content_Return_Same_Content() { //Arrange var createCommand = new ContentCommand { ContentName = "Foo:Posts", ContentFields = new Dictionary <string, string> { { "Article", "Hello World" }, { "Body", "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor" } } }; var readQuery = new ContentQuery { ContentName = "Foo:Posts" }; var expectedContent = new ContentDto { ContentName = "Foo:Posts", ContentFields = new Dictionary <string, string> { { "Article", "Hello World" }, { "Body", "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor" } } }; var contentService = GetContentService(); var compareLogic = new CompareLogic(); //Act contentService.CreateContentAsync(createCommand).Wait(); var retrievedContent = contentService.GetContentAsync(readQuery).Result; //Assert var compareResult = compareLogic.Compare(expectedContent, retrievedContent); Assert.IsTrue(compareResult.AreEqual, $"Added and retrieved roles aren't identical differences are {string.Join(",", compareResult.Differences)}"); }
public static void RetryAllFailedActions() { using (new SystemAccount()) { var qs = new QuerySettings { EnableLifespanFilter = FilterStatus.Disabled, EnableAutofilters = FilterStatus.Disabled }; var q = ContentQuery.CreateQuery(SafeQueries.FilesInTree, qs, _actionPath); var result = q.Execute(); foreach (Node node in result.Nodes) { var failFile = node as File; if (failFile == null) { continue; } // restore ADAction object var stream = failFile.Binary.GetStream(); var serializer = new XmlSerializer(typeof(ADAction)); var adAction = serializer.Deserialize(stream) as ADAction; if (adAction == null) { continue; } try { adAction.Execute(); failFile.Delete(true); } catch (Exception ex) //TODO: catch block { // re-execution failed again, save exception adAction.LastException = GetExceptionMsg(ex); SaveAction(adAction, failFile); } } } }
public static IEnumerable <Node> GetWebContentTypeList() { var contentTypeNames = WebApplication.WebContentNameList; if (string.IsNullOrEmpty(contentTypeNames)) { contentTypeNames = DefaultContentTypeName; } var validCtdNames = contentTypeNames.Split(',').Select(c => c.Trim()).Where(IsValidContentType).ToArray(); if (validCtdNames.Length == 0) { return(new Node[0]); } var namesClause = string.Join(" ", validCtdNames); var cql = $"+TypeIs:ContentType +Name:({namesClause})"; return(ContentQuery.Query(cql, QuerySettings.AdminSettings).Nodes); }
public List <SueetieBlogComment> GetRecentComments(int numRecords, int userID, int applicationID, bool isRestricted) { ContentQuery contentQuery = new ContentQuery { NumRecords = numRecords, UserID = userID, ContentTypeID = (int)SueetieContentType.BlogComment, GroupID = -1, ApplicationID = applicationID, IsRestricted = isRestricted, TruncateText = true }; List <SueetieBlogComment> _sueetieBlogComments = SueetieBlogs.GetSueetieBlogCommentList(contentQuery); foreach (SueetieBlogComment msg in _sueetieBlogComments) { msg.Comment = DataHelper.TruncateText(msg.Comment, SueetieConfiguration.Get().Core.TruncateTextCount); } return(_sueetieBlogComments); }
public List <SueetieForumMessage> GetRecentForumMessages(int numRecords, int userID, int applicationID, bool isRestricted) { ContentQuery contentQuery = new ContentQuery { NumRecords = numRecords, UserID = userID, ContentTypeID = (int)SueetieContentType.ForumMessage, GroupID = -1, ApplicationID = applicationID, IsRestricted = isRestricted, TruncateText = true }; List <SueetieForumMessage> _sueetieForumMessages = SueetieForums.GetSueetieForumMessageList(contentQuery); foreach (SueetieForumMessage msg in _sueetieForumMessages) { msg.Message = DataHelper.TruncateText(msg.Message, SueetieConfiguration.Get().Core.TruncateTextCount); } return(_sueetieForumMessages); }
/// <summary> /// Gets the groups. /// </summary> /// <returns>List of group nodes.</returns> private List <Node> GetGroups() { var groups = new List <Node>(); if (!String.IsNullOrEmpty(GroupQuery)) { var sort = new[] { new SortInfo { FieldName = "Name" } }; var settings = new QuerySettings { EnableAutofilters = false, EnableLifespanFilter = false, Sort = sort }; var query = new ContentQuery { Text = GroupQuery, Settings = settings }; query.AddClause(string.Format("-Name:({0})", string.Join(" ", RepositoryConfiguration.SpecialGroupNames))); var results = query.Execute(); groups.AddRange(results.Nodes); } return(groups); }
protected override void OnCreating(object sender, SenseNet.ContentRepository.Storage.Events.CancellableNodeEventArgs e) { base.OnCreating(sender, e); this.PostedBy = this.CreatedBy; if (StorageContext.Search.IsOuterEngineEnabled && StorageContext.Search.SearchEngine != InternalSearchEngine.Instance) { try { var querystring = string.Format("+InTree:'{0}' +Type:'ForumEntry' +CreationDate:<'{1}' .COUNTONLY", this.ParentPath, this.CreationDate.ToString("yyyy-MM-dd HH:mm:ss.fff")); var q = ContentQuery.Query(querystring, new QuerySettings { Top = int.MaxValue }); this.SerialNo = q.Count; } catch { Trace.Write("Lucene query failed on node " + this.Path); } } }
/// <summary> /// Retrieves comments for a given Post/Content /// </summary> /// <param name="postid">Id of Post.</param> /// <returns></returns> public static QueryResult GetComments(int parentId) { //var queryText = string.Format("+ParentId:\"{0}\" +Type:Comment", postid); var parent = NodeHead.Get(parentId); if (parent == null) { return(null); } var commentFolderPath = RepositoryPath.Combine(parent.Path, "Comments"); var queryText = string.Format("+InFolder:\"{0}\" +Type:Comment", commentFolderPath); var settings = new QuerySettings { EnableAutofilters = false, Sort = new SortInfo[] { new SortInfo { FieldName = "CreationDate", Reverse = false } } }; var result = ContentQuery.Query(queryText, settings); return(result); }
/// <summary> /// Gets the employees. /// </summary> /// <param name="manager">The manager.</param> /// <param name="container">The container.</param> /// <param name="depth">The depth.</param> private void GetEmployees(Content manager, XmlNode container, int depth) { if (depth > DepthLimit) { return; } var employeesNode = container.OwnerDocument.CreateElement("Employees"); container.AppendChild(employeesNode); foreach (var employee in ContentQuery.Query("+Manager:@0 +Type:User", null, manager.Id).Nodes.Select(Content.Create)) { if (!_usedNodeId.Contains(employee.Id)) { _usedNodeId.Add(employee.Id); } else { throw new NotSupportedException(ResourceManager.Current.GetString("OrganizationChart", "CircularReferenceError")); } var employeeStream = employee.GetXml(); var employeeXml = new XmlDocument(); employeeXml.Load(employeeStream); if (employeeXml.DocumentElement == null) { continue; } var employeeXmlNode = employeesNode.OwnerDocument.ImportNode(employeeXml.DocumentElement, true); employeesNode.AppendChild(employeeXmlNode); // reload the xml node employeeXmlNode = employeesNode.SelectSingleNode(string.Format("Content[SelfLink='{0}']", employee.Path)); GetEmployees(employee, employeeXmlNode, depth + 1); } }
public void Indexing_ExecutingUnprocessedDoesNotDuplicate() { var contentName = "Indexing_ExecutingUnprocessedDoesNotDuplicate"; var query = ContentQuery.CreateQuery(".COUNTONLY Name:" + contentName, new QuerySettings { EnableAutofilters = false, EnableLifespanFilter = false }); var count = query.Execute().Count; if (count > 0) { Assert.Inconclusive(); } var lastActivityId = MissingActivityHandler.MaxActivityId; var content = Content.CreateNew("Car", TestRoot, contentName); content.Save(); content.ContentHandler.Index++; content.Save(); content.ContentHandler.Index++; content.Save(); count = query.Execute().Count; Assert.IsTrue(count == 1, String.Format("Before executing unprocessed activities found {0}, expected: 1.", count)); MissingActivityHandler.MaxActivityId -= 3; LuceneManager.ExecuteUnprocessedIndexingActivities(null); count = query.Execute().Count; Assert.IsTrue(count == 1, String.Format("After executing unprocessed activities #1 found {0}, expected: 1.", count)); count = ContentQuery.Query(".COUNTONLY +Index:2 +Name:" + contentName, new QuerySettings { EnableAutofilters = false, EnableLifespanFilter = false }).Count; Assert.IsTrue(count == 1, String.Format("After executing unprocessed activities #2 found {0}, expected: 1.", count)); }
private static bool IsInstallationMode() { LogWriteLine("========================================"); LogWriteLine("Indexing: " + (StorageContext.Search.IsOuterEngineEnabled ? "enabled" : "disabled")); var startupMode = false; if (StorageContext.Search.IsOuterEngineEnabled) { try { startupMode = ContentQuery.Query("Type:PortalRoot").Count == 0; } catch (Exception e) { var s = e.Message; } LogWriteLine("Startup mode: " + (startupMode ? "ON" : "off")); LogWriteLine("========================================"); } return(startupMode); }
public async Task <FeaturesDto> GetFeaturesAsync(int version = 0, CancellationToken ct = default) { var result = new FeaturesDto { Version = version }; if (client != null && version < FeatureVersion) { try { var query = new ContentQuery(); if (version == 0) { query.Filter = $"data/version/iv eq {FeatureVersion}"; } else { query.Filter = $"data/version/iv le {FeatureVersion} and data/version/iv gt {version}"; } var features = await client.GetAsync(query, flatten, ct); result.Features.AddRange(features.Items.Select(x => x.Data).ToList()); if (features.Items.Count > 0) { result.Version = features.Items.Max(x => x.Version); } } catch { } } return(result); }
public ActionResult Archives(string list_name, int year, int month, ContentQuery query) { return _InternalView(list_name); }
public ContentQueryResult GetItems(ContentQuery query = null) { return this.Items(query); }
public ContentQueryResult GetItems(Action<ContentQuery> builder) { var query = new ContentQuery(); if (builder != null) builder.Invoke(query); return this.GetItems(query); }
public ActionResult Items(string name, string slug, ContentQuery query, string parentID = "", string format = "json") { if (string.IsNullOrEmpty(name)) throw new ArgumentNullException("name"); //if (string.IsNullOrEmpty(slug)) // throw new ArgumentNullException("slug"); var list = App.Get().CurrentWeb.Lists[name]; //ViewBag.List = list; ContentViewDecorator view; if (string.IsNullOrEmpty(slug)) view = list.Views.FirstOrDefault(); else view = list.Views[slug]; if (!string.IsNullOrEmpty(query.Filter)) query.Filter = query.GetFilterExpression(); if (!string.IsNullOrEmpty(parentID)) { if (string.IsNullOrEmpty(query.Filter)) query.Filter = "parentId='" + parentID + "'"; else { query.Filter = " AND parentId='" + parentID + "'"; } } if (view == null) throw new ContentViewNotFoundException(); if (!view.IsAuthorized(HttpContext)) return new HttpUnauthorizedResult(); var results = view.Items(query); if (format == "xml") return Content(results.Element().OuterXml(), "text/xml", Encoding.UTF8); var model = results.Items.Select(i => list.GetItem(i.ID).ToObject()).ToList(); var jsonModel = new { Model = model, Total = query.Total }; var jstr = JsonConvert.SerializeObject(jsonModel, new JsonSerializerSettings() { DateFormatHandling = DateFormatHandling.MicrosoftDateFormat }); return Content(jstr, "application/json", Encoding.UTF8); }
public ContentQueryResult Items(ContentQuery query = null) { var dt = GetDataTable(); var dataView = dt.DefaultView; dataView.AllowDelete = false; dataView.AllowEdit = false; dataView.AllowNew = false; dataView.ApplyDefaultSort = false; if (query != null) { if (!string.IsNullOrEmpty(query.Sort)) dataView.Sort = query.Sort; if (!string.IsNullOrEmpty(query.Filter)) dataView.RowFilter = FormatFilter(query.Filter); } else { query = this.DefaultQuery; dataView.Sort = query.Sort; } query.Total = dataView.Count; var resultItems = new List<ContentQueryResultItem>(); if (query.Size == 0 && this.AllowPaging) query.Size = this.PageSize; var counter = dataView.Count; #region groupby //dataView.AsQueryable() //var selQuery=from r in dataView // group r by r.f #endregion if (query.Size > 0) counter = query.Index <= 1 ? query.Size : ((query.Index - 1) * query.Size + query.Size); var skip = query.Index <= 1 ? 0 : (query.Index - 1) * query.Size; for (int i = skip; i < counter; i++) { if (i >= dataView.Count) break; var rowView = dataView[i]; dynamic rowData = new ExpandoObject(); for (int j = 0; j < dt.Columns.Count; j++) { var col = dt.Columns[j]; ((IDictionary<String, Object>)rowData).Add(col.ColumnName, rowView[col.ColumnName]); } resultItems.Add(new ContentQueryResultItem(this, rowData)); } return new ContentQueryResult() { List = this.Parent, Items = resultItems, View = this, Query = query }; }
public ContentQueryResult Items(HttpContextBase context) { var request = context.Request; var list = this.Parent; var _query = new ContentQuery(request); var _filter = ""; var routeData = request.RequestContext.RouteData.Values; if (routeData.ContainsKey("tags") || routeData.ContainsKey("achrives")) { if (routeData.ContainsKey("achrives")) { var year = (int)routeData["year"]; var month = (int)routeData["month"]; _filter = string.Format("published >=#{0}-{1}-01# AND Published <=#{0}-{1}-30#", year, month); } else { var tag = routeData["tag"]; _filter = "tags LIKE '%" + tag + "%'"; } } else { if (list.IsModerated) { var ext = ""; if (Parent.IsHierarchy && string.IsNullOrEmpty(context.Request.QueryString["parentId"])) ext = " AND parentId='" + Guid.Empty.ToString() + "'"; if (list.IsOwner(context) || (request.IsAuthenticated && list.IsModerator(context.User.Identity.Name))) //Here is Moderator _filter = "(" + DataNames.IsPublished + "=True And " + DataNames.Owner + "<>'" + context.User.Identity.Name + "')" + " Or " + DataNames.Owner + "='" + context.User.Identity.Name + "'"; else _filter = "(" + DataNames.IsPublished + "=True" + " And " + DataNames.State + "=" + ((int)ModerateStates.Approved).ToString() + ") Or " + DataNames.Owner + "='" + context.User.Identity.Name + "'"; if (!string.IsNullOrEmpty(ext)) _filter = "(" + _filter + ") " + ext; } else { if (Parent.IsHierarchy && string.IsNullOrEmpty(context.Request.QueryString["parentId"])) _filter = DataNames.IsPublished + "=True" + " AND parentId='" + Guid.Empty.ToString() + "'"; else _filter = DataNames.IsPublished + "=True"; } } if (string.IsNullOrEmpty(_query.Filter) && !string.IsNullOrEmpty(_filter)) _query.Filter = _filter; if (string.IsNullOrEmpty(_query.Sort) && !string.IsNullOrEmpty(this.DefaultQuery.Sort)) _query.Sort = this.DefaultQuery.Sort; return Items(_query); }
/// <summary> /// Renders the data items that returns by a content query. /// </summary> /// <param name="html">The html helper object.</param> /// <param name="view">The content view object that use to execute query.</param> /// <param name="query">The content query object.</param> public static void RenderQueryResults(this HtmlHelper html, ContentViewDecorator view, ContentQuery query) { RenderQueryResults(html, view.GetItems(query)); }
public ActionResult Feed(string list_name, string slug, ContentQuery query, string format = "rss") { if (string.IsNullOrEmpty(list_name)) throw new ArgumentNullException("name"); if (string.IsNullOrEmpty(slug)) throw new ArgumentNullException("slug"); var list = App.Get().CurrentWeb.Lists[list_name]; if (list == null) return HttpNotFound(); var view = list.Views[slug]; if (view == null) throw new ContentViewNotFoundException(); if (format == "rss") return Content(view.ToRss(), "text/xml", Encoding.UTF8); else return Content(view.ToAtom(), "text/xml", Encoding.UTF8); }
public ContentQueryResult GetUserItems(string userName = "") { if (string.IsNullOrEmpty(userName)) userName = HttpContext.Current.User.Identity.Name; var query = new ContentQuery(); query.Eq(query.SysFieldNames.Owner, userName); return Items(query); }
public ActionResult Tags(string list_name, string tag, ContentQuery query) { if (string.IsNullOrEmpty(tag)) throw new ArgumentNullException("tag"); return _InternalView(list_name); }
public ActionResult Views(string list_name, string slug, ContentQuery query) { if (string.IsNullOrEmpty(list_name)) throw new ArgumentNullException("name"); if (string.IsNullOrEmpty(slug)) throw new ArgumentNullException("slug"); var view = App.Get().Context.View; if (view == null) { var list = App.Get().CurrentWeb.Lists[list_name]; if (list == null) return HttpNotFound(); App.Get().Context.List = list; view = list.Views[slug]; if (view == null) throw new ContentViewNotFoundException(); App.Get().Context.View = view; } return View("~/views/dynamicui/index.cshtml"); }