public void DeleteAllItems() { var itemCount = _list.ItemCount; ListItemCollectionPosition licp = null; while (true) { var query = new CamlQuery(); query.ViewXml = "<View><ViewFields><FieldRef Name='Id'/></ViewFields><RowLimit>250</RowLimit></View>"; query.ListItemCollectionPosition = licp; var items = _list.GetItems(query); _ctx.Load(items); _ctx.ExecuteQuery(); Console.WriteLine("Deleting {0} of {1} items", items.Count, itemCount); itemCount -= items.Count; foreach (var item in items.ToList()) { item.DeleteObject(); } _ctx.ExecuteQuery(); if (licp == null) { Console.WriteLine("Finished clearing list"); break; } } }
private static void FillLocalList(ClientContext context, List list, LocalList localList) { //Create a itempos ListItemCollectionPosition itemPosition = null; while (true) { // This creates a CamlQuery that has a RowLimit of 100, and also specifies Scope="RecursiveAll" // so that it grabs all list items, regardless of the folder they are in. CamlQuery query = CamlQuery.CreateAllItemsQuery(100); query.ListItemCollectionPosition = itemPosition; ListItemCollection items = list.GetItems(query); // Retrieve all items in the ListItemCollection from List.GetItems(Query). context.Load(items, itema => itema.Include(i => i.FieldValuesAsText), itemb => itemb.ListItemCollectionPosition); context.ExecuteQuery(); itemPosition = items.ListItemCollectionPosition; foreach (ListItem listItem in items) { localList.Items.AddLast(new LocalListItem(listItem.FieldValuesAsText.FieldValues)); } if (itemPosition == null) { break; } } }
/// <summary> /// Query the list to retreive the last ID /// </summary> /// <param name="onlineLibrary">The List we will query</param> /// <param name="lastItemModifiedDate">The date of the last modified list item</param> /// <returns></returns> public static int QueryLastItemId(this List onlineLibrary, Nullable <DateTime> lastItemModifiedDate = null) { var returnId = 0; var camlFieldRefs = new string[] { "ID", "Created", "Modified", }; var camlViewClause = CAML.ViewFields(camlFieldRefs.Select(s => CAML.FieldRef(s)).ToArray()); var camlQuery = new CamlQuery() { ViewXml = CAML.ViewQuery( ViewScope.RecursiveAll, string.Empty, CAML.OrderBy(new OrderByField("ID", false)), camlViewClause, 1) }; ListItemCollectionPosition itemPosition = null; while (true) { camlQuery.ListItemCollectionPosition = itemPosition; var spListItems = onlineLibrary.GetItems(camlQuery); onlineLibrary.Context.Load(spListItems, lti => lti.ListItemCollectionPosition); onlineLibrary.Context.ExecuteQueryRetry(); itemPosition = spListItems.ListItemCollectionPosition; if (spListItems.Any()) { if (lastItemModifiedDate.HasValue) { foreach (var item in spListItems) { var itemModified = item.RetrieveListItemValue("Modified").ToNullableDatetime(); if (itemModified == lastItemModifiedDate) { returnId = item.Id; break; } } } else { returnId = spListItems.OrderByDescending(ob => ob.Id).FirstOrDefault().Id; } if (returnId > 0) { // Found the item ID that matches the specified date - return it break; } } if (itemPosition == null) { break; } } return(returnId); }
/// <summary> /// Retrieve all listitems in a library /// </summary> /// <returns></returns> public List <ListItem> GetAllDocumentsInaLibrary(string libName) { List <ListItem> items = new List <ListItem>(); ClientContext ctx = this.Context; //ctx.Credentials = Your Credentials ctx.Load(ctx.Web, a => a.Lists); ctx.ExecuteQuery(); List list = ctx.Web.Lists.GetByTitle(libName); ListItemCollectionPosition position = null; // Page Size: 100 int rowLimit = 100; var camlQuery = new CamlQuery(); camlQuery.ViewXml = @"<View Scope='RecursiveAll'> <Query> <OrderBy Override='TRUE'><FieldRef Name='ID'/></OrderBy> </Query> <ViewFields> <FieldRef Name='Title'/><FieldRef Name='Modified' /><FieldRef Name='Editor' /><FieldRef Name='FileLeafRef' /><FieldRef Name='FileRef' /><FieldRef Name='" + this.hashColumn + "' /></ViewFields><RowLimit Paged='TRUE'>" + rowLimit + "</RowLimit></View>"; do { ListItemCollection listItems = null; camlQuery.ListItemCollectionPosition = position; listItems = list.GetItems(camlQuery); ctx.Load(listItems); ctx.ExecuteQuery(); position = listItems.ListItemCollectionPosition; items.AddRange(listItems.ToList()); }while (position != null); return(items); }
/// <summary> /// Retrieve all listitems in a list /// </summary> /// <param name="libName">The list</param> /// <param name="Context">The ClientContext</param> /// <returns></returns> public static List <ListItem> GetAllListItem(string listName, ClientContext Context, int Rows) { /* * List<ListItem> items = new List<ListItem>(); * Context.Load(Context.Web, a => a.Lists); * Context.ExecuteQuery(); */ List list = Context.Web.Lists.GetByTitle(listName); ListItemCollectionPosition position = null; var camlQuery = new CamlQuery(); camlQuery.ViewXml = @"<View Scope='RecursiveAll'> <Query> <OrderBy Override='TRUE'><FieldRef Name='ID'/></OrderBy> </Query> <ViewFields> <FieldRef Name='Title'/><FieldRef Name='Modified' /><FieldRef Name='Editor' /><FieldRef Name='FileLeafRef' /><FieldRef Name='FileRef' /></ViewFields><RowLimit Paged='TRUE'>" + Rows + "</RowLimit></View>"; do { ListItemCollection listItems = null; camlQuery.ListItemCollectionPosition = position; listItems = list.GetItems(camlQuery); Context.Load(listItems); Context.ExecuteQuery(); position = listItems.ListItemCollectionPosition; items.AddRange(listItems.ToList()); }while (position != null); return(items); }
// Token: 0x0600223D RID: 8765 RVA: 0x0007E938 File Offset: 0x0007CB38 private OneDriveProItemsPage UpdatePageCache(IClientContext clientContext, UserContext userContext, IList list, string listName, string location, IndexedPageView requestedData, AttachmentItemsSort sort, DataProviderCallLogEvent logEvent) { string changeToken; bool flag; this.GetListItemChangesSinceToken(clientContext, userContext.LogonIdentity, listName, location, out changeToken, out flag, logEvent); this.ChangeToken = changeToken; if (flag) { this.PageMap.Clear(); } int num = this.ComputeStartPageIndex(requestedData); OneDriveProItemsPage nearestPage = this.GetNearestPage(num); int num2 = (nearestPage != null) ? nearestPage.PageIndex : -1; if (nearestPage == null || num != nearestPage.PageIndex) { ListItemCollectionPosition listItemCollectionPosition = this.GetListItemCollectionPosition(nearestPage); CamlQuery query = OneDriveProUtilities.CreatePagedCamlPageQuery(location, sort, listItemCollectionPosition, Math.Abs(num - num2) * 200 + 200); IListItemCollection items = list.GetItems(query); items.Load(clientContext, new Expression <Func <ListItemCollection, object> > [0]); OneDriveProUtilities.ExecuteQueryWithTraces(userContext, clientContext, logEvent, "UpdatePageCache"); this.UpdateCache(items, nearestPage); } OneDriveProItemsPage result; this.PageMap.TryGetValue(num, out result); return(result); }
private static void ReadExistingWikiPages(ClientContext context, List <string> existingPages) { CamlQuery camlQuery = new CamlQuery(); camlQuery.ViewXml = @"<View><Query><Where><IsNotNull><FieldRef Name='FileLeafRef' /></IsNotNull></Where></Query></View>"; ListItemCollectionPosition position = null; do { camlQuery.ListItemCollectionPosition = position; ListItemCollection listItems = context.Web.Lists.GetByTitle(wikiListName).GetItems(camlQuery); context.Load(listItems); context.ExecuteQuery(); context.Load(listItems, lic => lic.Include( item => item.Id, item => item["FileLeafRef"] )); context.ExecuteQuery(); position = listItems.ListItemCollectionPosition; foreach (ListItem listItem in listItems) { existingPages.Add(listItem["FileLeafRef"].ToString()); } } while (position != null); }
public override void LoadMockData() { string text = string.IsNullOrEmpty(this.relativePath) ? this.listTitle : this.relativePath; string path = Path.Combine(MockClientContext.MockAttachmentDataProviderFilePath, text); DirectoryInfo directoryInfo = new DirectoryInfo(path); List <string> list = new List <string>(this.viewFields); foreach (KeyValuePair <string, bool> keyValuePair in this.orderBy) { list.Add(keyValuePair.Key); } List <MockListItem> list2 = new List <MockListItem>(); foreach (DirectoryInfo dirInfo in directoryInfo.GetDirectories()) { list2.Add(new MockListItem(dirInfo, text, this.context)); } foreach (FileInfo fileInfo in directoryInfo.GetFiles()) { list2.Add(new MockListItem(fileInfo, text, this.context)); } if (this.orderBy != null && this.orderBy.Count > 0) { list2.Sort((MockListItem item1, MockListItem item2) => this.Compare(item1, item2, 0)); } ListItemCollectionPosition listItemCollectionPosition = this.listItemCollectionPosition; if (this.rowLimit > 0 && this.rowLimit < list2.Count) { MockListItem[] array = new MockListItem[this.rowLimit]; list2.CopyTo(0, array, 0, this.rowLimit); list2 = new List <MockListItem>(array); } this.interalList = list2; }
/// <summary> /// Get items Paged /// </summary> /// <param name="ctx"></param> /// <param name="camlQuery"></param> public static void GetItemsPaged(ClientContext ctx, string libraryTitle, CamlQuery camlQuery) { Web oWebsite = ctx.Web; ListItemCollectionPosition position = null; List list = oWebsite.Lists.GetByTitle(libraryTitle); var itemPageLimit = 10; string query = $@"<View><OrderBy> <FieldRef Name='Id' /> </OrderBy> <Query/> <RowLimit>" + itemPageLimit + @"</RowLimit></View>"; do { var items = list.GetItems(camlQuery); ctx.Load(items); ctx.ExecuteQueryWithIncrementalRetry(); position = items.ListItemCollectionPosition; foreach (ListItem item in items) { Console.WriteLine("Item id is {0} and title is {1}", item.Id, item["Title"]); } }while (position != null); }
public ListItem[] GetItems(out ListItemCollectionPosition position) { if (_items != null && _items.AreItemsAvailable) { position = _items.ListItemCollectionPosition; return _items.ToArray(); } throw new SPAccessException("List Item collection is not available."); }
/// <summary> /// Process ListItem one by one /// </summary> /// <param name="listName">ListName</param> /// <param name="camlQuery">CamlQuery</param> /// <param name="itemProcessor">itemprocessor delegate</param> /// <param name="errorCallout">error delegate</param> public void ProcessListItem(string listName, CamlQuery camlQuery, ItemProcessor itemProcessor, ItemProcessorErrorCallout errorCallout) { List list = _context.Web.Lists.GetByTitle(listName); CamlQuery query = camlQuery; ListItemCollectionPosition position = null; query.ListItemCollectionPosition = position; while (true) { ListItemCollection listItems = list.GetItems(query); _context.Load(listItems, items => items.ListItemCollectionPosition); _context.ExecuteQuery(); for (int i = 0; i < listItems.Count; i++) { try { itemProcessor(listItems[i]); } catch (System.Exception ex) { if (errorCallout == null || errorCallout(listItems[i], ex)) { throw; } } } if (listItems.ListItemCollectionPosition == null) { return; } else { /*if query contains lookup column filter last batch returns null * by removing the lookup column in paginginfo query will return next records */ string pagingInfo = listItems.ListItemCollectionPosition.PagingInfo; string[] parameters = pagingInfo.Split(new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries); List <string> requiredParameters = new List <string>(); foreach (string str in parameters) { if (str.Contains("Paged=") || str.Contains("p_ID=")) { requiredParameters.Add(str); } } pagingInfo = string.Join("&", requiredParameters.ToArray()); listItems.ListItemCollectionPosition.PagingInfo = pagingInfo; query.ListItemCollectionPosition = listItems.ListItemCollectionPosition; } } }
/// <summary> /// Execute the cmdlet /// </summary> public override void ExecuteCmdlet() { base.ExecuteCmdlet(); Collection <SPListItemDefinition> results = new Collection <SPListItemDefinition>(); var _listSites = this.ClientContext.Web.Lists.GetByTitle(ListTitle); this.ClientContext.Load(_listSites); this.ClientContext.ExecuteQuery(); ListItemCollectionPosition itemPosition = null; try { while (true) { CamlQuery camlQuery = new CamlQuery(); camlQuery.ListItemCollectionPosition = itemPosition; camlQuery.ViewXml = @"<View><Query> <ViewFields> <FieldRef Name='Title'/> </ViewFields> <RowLimit>50</RowLimit> </Query></View>"; ListItemCollection listItems = _listSites.GetItems(camlQuery); this.ClientContext.Load(listItems); this.ClientContext.ExecuteQuery(); itemPosition = listItems.ListItemCollectionPosition; foreach (var rbiItem in listItems) { LogVerbose("Title: {0}; Item ID: {1}", rbiItem["Title"], rbiItem.Id); var newitem = new SPListItemDefinition() { Title = rbiItem.RetrieveListItemValue("Title"), Id = rbiItem.Id }; results.Add(newitem); } if (itemPosition == null) { break; } } } catch (Exception ex) { LogError(ex, "Failed to retrieve recycle bin collection"); } WriteObject(results, true); }
static void Main(string[] args) { string siteUrl = "https://bookon.dkbs.dk/"; ClientContext clientContext = new ClientContext(siteUrl); clientContext.AuthenticationMode = ClientAuthenticationMode.FormsAuthentication; clientContext.FormsAuthenticationLoginInfo = new FormsAuthenticationLoginInfo("CRM Automation", "9LEkTny4"); clientContext.ExecuteQuery(); // string contentTypeName = "Bookinger"; Console.WriteLine(" Successfully Connected"); List oList = clientContext.Web.Lists.GetByTitle("Bookinger"); ListItemCollectionPosition itemPosition = null; ContentTypeCollection ctColl = oList.ContentTypes; clientContext.Load(ctColl); clientContext.ExecuteQuery(); foreach (ContentType ct in ctColl) { if (ct.Name == "Bookinger" || ct.Name == "Gamle sager") { Console.WriteLine(ct.Name); Console.WriteLine("---Please wait while list item is displaying.---"); try { { string contentTypeName = "Bookinger"; var query = new CamlQuery() { ViewXml = String.Format("<View Scope='RecursiveAll'><Query><Where><Eq><FieldRef Name='ContentType' /><Value Type='Computed'>{0}</Value></Eq></Where></Query></View>", contentTypeName) // ViewXml = String.Format("<View Scope='RecursiveAll'><RowLimit>5000</RowLimit></View>") }; ListItemCollection collListItem = oList.GetItems(query); clientContext.Load(collListItem); clientContext.ExecuteQuery(); itemPosition = collListItem.ListItemCollectionPosition; Console.WriteLine(itemPosition); foreach (ListItem oListItem in collListItem) { Console.WriteLine("ID: {0} \nTitle: {1} ", oListItem.Id, oListItem["Title"]); } } } catch (Exception ex) { Console.WriteLine(ex); } } } }
public SPClientView IncludeItems(ListItemCollectionPosition position = null, bool datesInUtc = false, string folderServerRelativeUrl = null, params Expression<Func<ListItemCollection, object>>[] retrievals) { _items = ClientList.List.GetItems(new CamlQuery { ListItemCollectionPosition = position, ViewXml = View.ListViewXml }); View.Context.Load(_items, retrievals); _executeQuery = true; return this; }
internal void GetListItemCollection(List list, CamlQuery query, Action <ListItemCollection> GetItems) { int _items = 0; ListItemCollectionPosition position = GetListItemCollectionPage(list, query, x => { ListItemCollection _ret = x; _items += _ret.Count; GetItems(x); }); while (position != null) { query.ListItemCollectionPosition = position; position = GetListItemCollectionPage(list, query, x => { ListItemCollection _ret = x; _items += _ret.Count; GetItems(x); }); } ; Trace(new ProgressChangedEventArgs(1, String.Format("Loaded Items = {0}.", _items))); }
public ListItemCollection GetItems(Caml.View spView, ListItemCollectionPosition position, bool countOnly, bool fieldValuesAsText) { if (_args == null || spView == null) { return(null); } string folderUrl = string.IsNullOrWhiteSpace(this._args.FolderUrl) ? null : new Uri(string.Concat(this._args.Context.SiteUrl.TrimEnd('/'), "/", string.IsNullOrEmpty(_args.ListUrl) ? "" : $"{_args.ListUrl.Trim('/')}/", (!string.IsNullOrEmpty(_args.ListUrl) ? this._args.FolderUrl.Replace(_args.ListUrl, "") : this._args.FolderUrl).TrimStart('/'))).LocalPath; var list = GetList(); //if (list == null) //{ // Check.NotNull(list, nameof(List)); //} //if (spView == null) //{ // Check.NotNull(spView, nameof(Caml.View)); //} if (list != null && spView != null) { var items = list.GetItems(new CamlQuery() { DatesInUtc = true, FolderServerRelativeUrl = folderUrl, ViewXml = spView.ToString(true), ListItemCollectionPosition = position }); if (countOnly) { items.Context.Load(items, item => item.ListItemCollectionPosition, item => item.Include(i => i.Id)); return(items); } else { if (_args.IncludeItemPermissions) { items.Context.Load(items, item => item.Include(i => i.EffectiveBasePermissions)); } if (/*fieldValuesAsText*/ false) { //BUG: NOT working! items.Context.Load(items, item => item.ListItemCollectionPosition, item => item.Include(i => i.FieldValuesAsText)); } else { items.Context.Load(items, item => item.ListItemCollectionPosition); } return(items); } } return(null); }
// Token: 0x06000217 RID: 535 RVA: 0x00008724 File Offset: 0x00006924 private static CamlQuery CreateCamlQuery(string location, ListItemCollectionPosition listItemCollectionPosition, string viewXml) { CamlQuery camlQuery = new CamlQuery { ViewXml = viewXml }; if (!string.IsNullOrEmpty(location)) { camlQuery.FolderServerRelativeUrl = location; } camlQuery.ListItemCollectionPosition = listItemCollectionPosition; return(camlQuery); }
/// <summary> /// Execute the cmdlet /// </summary> public override void ExecuteCmdlet() { base.ExecuteCmdlet(); Collection <PSObject> results = new Collection <PSObject>(); var _listSites = LibraryName.GetList(this.ClientContext.Web); ListItemCollectionPosition itemPosition = null; try { while (true) { CamlQuery camlQuery = new CamlQuery { ListItemCollectionPosition = itemPosition, ViewXml = CAML.ViewQuery(ViewScope.RecursiveAll, string.Empty, string.Empty, CAML.ViewFields(CAML.FieldRef("Title")), 50) }; ListItemCollection listItems = _listSites.GetItems(camlQuery); this.ClientContext.Load(listItems); this.ClientContext.ExecuteQueryRetry(); itemPosition = listItems.ListItemCollectionPosition; foreach (var rbiItem in listItems) { LogVerbose("Title: {0}; Item ID: {1}", rbiItem["Title"], rbiItem.Id); var newitem = new { Title = rbiItem["Title"], Id = rbiItem.Id }; var ps = PSObject.AsPSObject(newitem); results.Add(ps); } if (itemPosition == null) { break; } } } catch (Exception ex) { LogError(ex, "Failed to retrieve recycle bin collection"); } WriteObject(results, true); }
public async Task <IEnumerable <TEntity> > GetEntitiesAsync(Type type, Caml.View spView) { CheckEntityType(type); ListItemCollectionPosition position = null; var entities = Enumerable.Empty <TEntity>(); if (_args == null || spView == null) { return(entities); } var rowLimit = spView.Limit; int itemCount = 0; do { if (_args.BatchSize > 0) { if (rowLimit > 0) { spView.Limit = Math.Min(rowLimit - itemCount, _args.BatchSize); } else { spView.Limit = _args.BatchSize; } if (spView.Limit == 0) { break; } } var items = GetItems(spView, position); if (items != null) { await items.Context.ExecuteQueryAsync(); if (_args.BatchSize > 0) { position = items.ListItemCollectionPosition; } itemCount += items.Count; entities = entities.Concat(MapEntities(items, type)); } }while (position != null); spView.Limit = rowLimit; return(entities); }
public ListItemCollection GetItems(Caml.View spView, ListItemCollectionPosition position) { var list = GetList(); if (list != null) { var items = list.GetItems(new CamlQuery() { ViewXml = spView.ToString(true), ListItemCollectionPosition = position }); items.Context.Load(items, item => item.Include(i => i.EffectiveBasePermissions)); items.Context.Load(items, item => item.ListItemCollectionPosition); return(items); } return(null); }
/// <summary> /// Query the list to retreive the last ID /// </summary> /// <param name="onlineLibrary">The List we will query</param> /// <param name="lastItemModifiedDate">The date of the last modified list item</param> /// <returns></returns> public static int QueryLastItemId(this List onlineLibrary, Nullable <DateTime> lastItemModifiedDate = null) { var returnId = 0; var camlFieldRefs = new string[] { "ID", "Created", "Modified", }; var camlViewClause = CAML.ViewFields(camlFieldRefs.Select(s => CAML.FieldRef(s)).ToArray()); var camlQuery = new CamlQuery() { ViewXml = CAML.ViewQuery(string.Empty, CAML.OrderBy(new OrderByField("Modified", false)), 10) }; if (!lastItemModifiedDate.HasValue) { onlineLibrary.EnsureProperties(olp => olp.LastItemModifiedDate, olp => olp.LastItemUserModifiedDate); lastItemModifiedDate = onlineLibrary.LastItemModifiedDate; } ListItemCollectionPosition ListItemCollectionPosition = null; while (true) { camlQuery.ListItemCollectionPosition = ListItemCollectionPosition; var spListItems = onlineLibrary.GetItems(camlQuery); onlineLibrary.Context.Load(spListItems, lti => lti.ListItemCollectionPosition); onlineLibrary.Context.ExecuteQueryRetry(); ListItemCollectionPosition = spListItems.ListItemCollectionPosition; if (spListItems.Any()) { foreach (var item in spListItems) { var itemModified = item.RetrieveListItemValue("Modified").ToDateTime(); System.Diagnostics.Trace.TraceInformation("Item {0} Modified {1} IS MATCH:{2}", item.Id, itemModified, (itemModified == lastItemModifiedDate)); } returnId = spListItems.OrderByDescending(ob => ob.Id).FirstOrDefault().Id; break; } if (ListItemCollectionPosition == null) { break; } } return(returnId); }
static void Main(string[] args) { string rootURL = "https://bajajelect.sharepoint.com/sites/ItemCodePreProDev/"; using (ClientContext clientContext = BELDataAccessLayer.Instance.CreateClientContext(rootURL)) { Web web = BELDataAccessLayer.Instance.CreateWeb(clientContext); List approverList = web.Lists.GetByTitle("ItemCodeApprovalMatrix"); ListItemCollectionPosition position = null; var page = 1; do { CamlQuery query = new CamlQuery(); DateTime? yesterDayDate = null; int actionStatus = 1; int id = 358; query.ViewXml = @"<View> <Query> <Where> <Eq> <FieldRef Name='RequestID' /> <Value Type='Lookup'>" + id + @"</Value> </Eq> </Where> </Query> <RowLimit>5000</RowLimit> </View>"; query.ListItemCollectionPosition = position; ListItemCollection approverDetails = approverList.GetItems(query); clientContext.Load(approverDetails); clientContext.ExecuteQuery(); position = approverDetails.ListItemCollectionPosition; if (approverDetails != null && approverDetails.Count > 0) { for (int i = 0; i < approverDetails.Count; i++) { } page++; } } while (position != null); } }
public async Task ProcessItemsAsync(Caml.View spView, bool countOnly, bool fieldValuesAsText, Action <ListItemCollection> action) { if (_args == null || spView == null) { return; } if (action != null) { var rowLimit = spView.Limit; int itemCount = 0; ListItemCollectionPosition position = null; do { if (_args.BatchSize > 0) { if (rowLimit > 0) { spView.Limit = Math.Min(rowLimit - itemCount, _args.BatchSize); } else { spView.Limit = _args.BatchSize; } if (spView.Limit == 0) { break; } } var items = GetItems(spView, position, countOnly, fieldValuesAsText); if (items != null) { await items.Context.ExecuteQueryAsync(); if (_args.BatchSize > 0) { position = items.ListItemCollectionPosition; } itemCount += items.Count; action(items); } }while (position != null); spView.Limit = rowLimit; } }
// (Compare with ContentIterator for Server OM) static void ProcessListItems(List list, IList <string> fieldNames, Action <ListItem> action) { CamlQuery camlQuery = CamlQuery.CreateAllItemsQuery(5, fieldNames.ToArray()); var retrievalsList = new List <Expression <Func <ListItem, object> > >(); foreach (string fieldName in fieldNames) { retrievalsList.Add(listItemArg => listItemArg[fieldName]); } var retrievals = retrievalsList.ToArray(); ListItemCollectionPosition itemPosition = null; int itemCount = 0; for (; ;) { camlQuery.ListItemCollectionPosition = itemPosition; ListItemCollection listItems = list.GetItems(camlQuery); clientContext.Load(listItems, listItemsArg => listItemsArg.ListItemCollectionPosition, listItemsArg => listItemsArg.Include(retrievals) ); clientContext.ExecuteQuery(); itemPosition = listItems.ListItemCollectionPosition; foreach (ListItem listItem in listItems) { action(listItem); ++itemCount; } Log("Processed batch: " + itemCount); if (itemPosition == null) { break; } } }
public MonitorViewModel(MainViewModel instance, SqlViewModel sqlViewModel, ConnectViewModel connectViewModel, SPListViewModel spListViewModel) { _mainViewModel = instance; IsBusy = false; _sqlViewModel = sqlViewModel; _connectViewModel = connectViewModel; _spListViewModel = spListViewModel; position = null; _worker = new BackgroundWorker { WorkerSupportsCancellation = true, WorkerReportsProgress = true }; _worker.DoWork += _worker_DoWork; _worker.RunWorkerCompleted += _worker_RunWorkerCompleted; CancelTransferCommand = new Command(CancelTransfer); _transferCommand = new Command(TransferCommandFunc); }
public IList <NameSourcePair> GetFilenamesWithSource() { EnsureInitialized(); using (var context = CreateContext()) { var result = new List <NameSourcePair>(); var list = context.Web.Lists.GetByTitle(m_settings.DocumentLibrary); ListItemCollectionPosition itemPosition = null; while (true) { var q = new CamlQuery { ViewXml = "<View><RowLimit>5000</RowLimit></View>", ListItemCollectionPosition = itemPosition }; var items = list.GetItems(q); context.Load(list); context.Load(items, foo => foo.ListItemCollectionPosition, i => i.Include( item => item["FileLeafRef"], item => item["_Source"] ) ); context.ExecuteQuery(); itemPosition = items.ListItemCollectionPosition; result.AddRange(items.ToList().Select(i => new NameSourcePair { Name = i["FileLeafRef"].ToString(), Source = i["_Source"] == null ? string.Empty : i["_Source"].ToString() }) .ToList()); if (itemPosition == null) { break; } } return(result); } }
/// <summary> /// Adding OneNote items (Notebooks, SectionGroups and Sections) Logs to the collection /// </summary> /// <param name="list"> SharePoint list object</param> /// <returns> task object</returns> private async Task AddOneNoteItemsInfo(List list) { ListItemCollectionPosition pagePosition = null; int notebooksCount = 0; int foldersCount = 0; int sectionsCount = 0; do { CamlQuery camlQuery = new CamlQuery(); camlQuery.ListItemCollectionPosition = pagePosition; camlQuery.ViewXml = Query; ListItemCollection items = list.GetItems(camlQuery); context.Load(items); await ExecuteQuery(); pagePosition = items.ListItemCollectionPosition; foreach (var item in items) { object returnValue; if (item.FieldValues.TryGetValue("File_x0020_Type", out returnValue) && returnValue != null && returnValue.ToString().Equals("one", StringComparison.OrdinalIgnoreCase)) { sectionsCount++; } if (item.FieldValues.TryGetValue("ContentTypeId", out returnValue) && returnValue != null && returnValue.ToString().StartsWith("0x0120", StringComparison.OrdinalIgnoreCase)) { foldersCount++; } if (item.FieldValues.TryGetValue("HTML_x0020_File_x0020_Type", out returnValue) && returnValue != null && returnValue.ToString().Equals("OneNote.Notebook", StringComparison.OrdinalIgnoreCase)) { notebooksCount++; } } } while (pagePosition != null); Logs.Add("Notebooks Count:" + notebooksCount); Logs.Add("Folders Count:" + foldersCount); Logs.Add("Sections Count:" + sectionsCount); }
private List <SPDGListItem> loadListItems() { List <SPDGListItem> retVal = new List <SPDGListItem>(); ListItemCollectionPosition itemPosition = null; do { CamlQuery query = CamlQuery.CreateAllItemsQuery(5000); query.ListItemCollectionPosition = itemPosition; var itemBatch = _list.GetItems(query); _context.Load(itemBatch, collection => collection.Include(SPDGClientListItem.IncludeExpression), collection => collection.ListItemCollectionPosition); _context.ExecuteQuery(); itemPosition = itemBatch.ListItemCollectionPosition; foreach (var item in itemBatch) { retVal.Add(new SPDGClientListItem(item, _context)); } } while (itemPosition != null); return(retVal); }
public List <ListItem> GetListData(Guid listId, ref ListItemCollectionPosition position) { ClientContext clientContext = _connect.GetClientContextSp; List oList = clientContext.Web.Lists.GetById(listId); List <ListItem> items = new List <ListItem>(); CamlQuery camlQuery = new CamlQuery { ViewXml = "<View><Query><OrderBy><FieldRef Name=\"Created\" Ascending=\"false\" /></OrderBy></Query><RowLimit>100</RowLimit></View>" }; //do //{ ListItemCollection listItems = null; if (position != null) { camlQuery.ListItemCollectionPosition = position; } listItems = oList.GetItems(camlQuery); clientContext.Load(listItems); clientContext.ExecuteQuery(); position = listItems.ListItemCollectionPosition; items.AddRange(listItems.ToList()); //} //while (position != null); return(items); //foreach (ListItem oListItem in collListItem) //{ // Console.WriteLine("ID: {0} \nTitle: {1} \nBody: {2}", oListItem.Id, oListItem["Title"], oListItem["Body"]); //} }
public IEnumerable <ListItem> GetItems(Caml.View spView, bool fieldValuesAsText, out string pagingInfo) { var listItems = Enumerable.Empty <ListItem>(); pagingInfo = null; if (_args == null || spView == null) { return(listItems); } ListItemCollectionPosition position = null; ProcessItems(spView, false, fieldValuesAsText, (items) => { listItems = listItems.Concat(items.Cast <ListItem>()); position = items.ListItemCollectionPosition; }); if (position != null) { pagingInfo = position.PagingInfo; } _args.OnAfterEvent?.Invoke(pagingInfo); return(listItems); }
void WritePermissionsForListItems(ClientContext clientContext, User user, List list) { ListItemCollectionPosition itemPosition = null; while (true) { CamlQuery camlQuery = new CamlQuery(); camlQuery.ListItemCollectionPosition = itemPosition; camlQuery.ViewXml = "<View><ViewFields>" + "<FieldRef Name='ID'/>" + "<FieldRef Name='Title'/>" + "</ViewFields><RowLimit>50</RowLimit></View>"; ListItemCollection collListItem = list.GetItems(camlQuery); clientContext.Load(collListItem, items => items.Where(item => item.HasUniqueRoleAssignments == true).Include( item => item.DisplayName, item => item.FileSystemObjectType, item => item.HasUniqueRoleAssignments)); clientContext.Load(collListItem, item => item.ListItemCollectionPosition); clientContext.ExecuteQuery(); itemPosition = collListItem.ListItemCollectionPosition; foreach (ListItem item in collListItem) { WritePermissionsForObject(clientContext, user, item); } if (itemPosition == null) { break; } } }
/// <summary> /// Esclates the requests. /// </summary> /// <param name="siteContext">The site context.</param> /// <param name="siteWeb">The site web.</param> /// <param name="mainListName">Name of the main list.</param> /// <param name="approverMatrixListName">Name of the approver matrix list.</param> /// <param name="activityLogListName">Name of the activity log list.</param> public static DataTable EsclateRequests(ClientContext siteContext, Web siteWeb, string mainListName, string approverMatrixListName, string activityLogListName, DataTable tblEscalation, int actionStatus) { List approverList = siteWeb.Lists.GetByTitle(approverMatrixListName); List mainList = siteWeb.Lists.GetByTitle(mainListName); List activityLogList = siteWeb.Lists.GetByTitle(activityLogListName); // Check why we are getting this. CamlQuery query = new CamlQuery(); string qry = string.Empty; //DateTime? yesterDayDate = null; string yesterDayDate = string.Empty; switch (Convert.ToInt32(actionStatus)) { case 1: //Escalation only //yesterDayDate = DateTime.Now.AddDays(-3); yesterDayDate = DateTime.Now.AddDays(-3).ToString("yyyy-MM-dd"); //yesterDayDate = DateTime.Now.AddDays(-3).ToString("yyyy-MM-ddTHH:mm:ssZ"); // qry = @"<And> // <IsNotNull> // <FieldRef Name='Approver' /> // </IsNotNull> // <And> // <Eq> // <FieldRef Name='DueDate' /> // <Value Type='DateTime' IncludeTimeValue='FALSE'>" + yesterDayDate + @"</Value> // </Eq> // <And> // <Eq> // <FieldRef Name='Status' /> // <Value Type='Text'>" + ApproverStatus.PENDING + @"</Value> // </Eq> // <Eq> // <FieldRef Name='IsEscalate' /> // <Value Type='Boolean'>1</Value> // </Eq> // </And> // </And></And>"; break; case 2: //Reminder only //yesterDayDate = DateTime.Now.AddDays(-1); yesterDayDate = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd"); //yesterDayDate = DateTime.Now.AddDays(-1).ToString("yyyy-MM-ddTHH:mm:ssZ"); // qry = @"<And> // <IsNotNull> // <FieldRef Name='Approver' /> // </IsNotNull> // <And> // <Eq> // <FieldRef Name='DueDate' /> // <Value Type='DateTime' IncludeTimeValue='FALSE'>" + yesterDayDate + @"</Value> // </Eq> // <And> // <Eq> // <FieldRef Name='Status' /> // <Value Type='Text'>" + ApproverStatus.PENDING + @"</Value> // </Eq> // <Eq> // <FieldRef Name='IsReminder' /> // <Value Type='Boolean'>1</Value> // </Eq> // </And> // </And></And>"; break; default: break; } // query.ViewXml = @"<View> // <Query> // <Where> // " + qry + @" // </Where> // </Query> // </View>"; ListItemCollectionPosition position = null; var page = 1; do { query.ViewXml = @"<View> <Query> <OrderBy> <FieldRef Name='ID' Ascending='False' /> </OrderBy> </Query> <RowLimit>5000</RowLimit> </View>"; query.ListItemCollectionPosition = position; ListItemCollection approverDetails = approverList.GetItems(query); siteContext.Load(approverDetails); siteContext.ExecuteQuery(); position = approverDetails.ListItemCollectionPosition; if (approverDetails != null) { for (int i = 0; i < approverDetails.Count; i++) { string status = Convert.ToString(approverDetails[i]["Status"]); //DateTime? date = null; string date = string.Empty; if (status == "Pending" && approverDetails[i]["Approver"] != null && approverDetails[i]["DueDate"] != null) { date = Convert.ToDateTime(approverDetails[i]["DueDate"]).ToString("yyyy-MM-dd"); //date = Convert.ToDateTime(approverDetails[i]["DueDate"]); //if (actionStatus == 1 && Convert.ToBoolean(approverDetails[i]["IsEscalate"]) && date.HasValue && yesterDayDate.HasValue && date == yesterDayDate) //Escalation only if (actionStatus == 1 && Convert.ToBoolean(approverDetails[i]["IsEscalate"]) && !string.IsNullOrWhiteSpace(date) && !string.IsNullOrWhiteSpace(yesterDayDate) && date == yesterDayDate) //Escalation only { string esclationTo = string.Empty; ////not required tblEscalation = EsclateRequest(siteContext, siteWeb, approverDetails[i], mainListName, approverMatrixListName, tblEscalation, ref esclationTo, actionStatus); } if (actionStatus == 2 && Convert.ToBoolean(approverDetails[i]["IsReminder"]) && !string.IsNullOrWhiteSpace(date) && !string.IsNullOrWhiteSpace(yesterDayDate) && date == yesterDayDate) //Reminder only { string esclationTo = string.Empty; ////not required tblEscalation = EsclateRequest(siteContext, siteWeb, approverDetails[i], mainListName, approverMatrixListName, tblEscalation, ref esclationTo, actionStatus); } } //string esclationTo = string.Empty; ////not required //tblEscalation = EsclateRequest(siteContext, siteWeb, approverDetails[i], mainListName, approverMatrixListName, tblEscalation, ref esclationTo, actionStatus); } page++; } } while (position != null); return(tblEscalation); }
public CamlQryIntegrationMetadata GetCamlQueryIntegratedMetadata() { if (!CheckValidArguments()) { return null; } var result = new CamlQryIntegrationMetadata { Query = new CamlQuery {ViewXml = GetCamlQueryXml()} }; var itemsPosition = new ListItemCollectionPosition { PagingInfo = CurrentPageInformation.Query }; result.Query.ListItemCollectionPosition = itemsPosition; result.PagingIntegrationMetadata = CurrentPagingIntegrationMetadata; result.IntegrateToCamlQrExAction = IntegrateToCamlQrEx; return result; }
public ActionResult Index(string lastPosition) { var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext); List<Employee> employees = new List<Employee>(); using (var clientContext = spContext.CreateUserClientContextForSPAppWeb()) { List list = clientContext.Web.Lists.GetByTitle("Employees"); CamlQuery camlQuery = new CamlQuery(); if (lastPosition != null) { ListItemCollectionPosition position = new ListItemCollectionPosition(); position.PagingInfo = string.Format("Paged=TRUE&p_ID={0}", lastPosition); camlQuery.ListItemCollectionPosition = position; lastPosition = (int.Parse(lastPosition) + 20).ToString(); } else { lastPosition = "20"; } camlQuery.ViewXml=@"<View> <Query> <OrderBy> <FieldRef Name='LastName'/> </OrderBy> </Query> <ViewFields> <FieldRef Name='EmployeeID'/> <FieldRef Name='LastName'/> <FieldRef Name='FirstName'/> <FieldRef Name='HireDate'/> <FieldRef Name='HomePhone'/> </ViewFields> <RowLimit>100</RowLimit> </View>"; ListItemCollection listItems = list.GetItems(camlQuery); clientContext.Load( listItems, items => items .Include( item => item["EmployeeID"], item => item["LastName"], item => item["FirstName"], item => item["HireDate"], item => item["HomePhone"])); clientContext.ExecuteQuery(); foreach (ListItem listItem in listItems) { Employee employee = new Employee(); employee.EmployeeID = listItem["EmployeeID"] == null ? -1 : (int)listItem["EmployeeID"]; employee.FirstName = listItem["FirstName"] == null ? string.Empty : listItem["FirstName"].ToString(); employee.LastName = listItem["LastName"] == null ? string.Empty : listItem["LastName"].ToString(); employee.HomePhone = listItem["HomePhone"] == null ? string.Empty : listItem["HomePhone"].ToString(); employee.HireDate = listItem["HireDate"] == null ? DateTime.Today : (DateTime)listItem["HireDate"]; employees.Add(employee); } } ViewBag.LastPosition = lastPosition; return View(employees); }