Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- private void Purge()
- {
- try
- {
- using (ClientContext ctx = new ClientContext(sharePointSiteUrl))
- {
- ctx.Credentials = new SharePointOnlineCredentials(userName, password);
- var web = ctx.Web;
- ctx.Load(web, w => w.Title);
- ctx.ExecuteQuery();
- this.statusLabel.Text = string.Format("Purge '{0}'...", web.Title);
- var listsToPurge = <Ensemble des listes à purger>;
- int totalItemCount = this.spListsList.CheckedItems.Cast<MyListItem>().Sum(i => i.ItemCount);
- this.progressBar.Value = 0;
- this.progressBar.Maximum = totalItemCount;
- foreach (MyListItem listToPurge in listsToPurge)
- {
- this.PurgeList(ctx, listToPurge);
- }
- var lists = web.Lists;
- ctx.Load(lists, ls => ls.Include(l => l.Title), ls => ls.Include(l => l.ItemCount));
- ctx.ExecuteQuery();
- this.spListsList.Items.Clear();
- foreach (List list in lists)
- {
- this.spListsList.Items.Add(new MyListItem() { Title = list.Title, ItemCount = list.ItemCount });
- }
- }
- }
- catch (Exception e)
- {
- MessageBox.Show(string.Format("Exception has occured : {0}", e), "Exception in purging", MessageBoxButtons.OK, MessageBoxIcon.Error);
- }
- }
- private void PurgeList(ClientContext ctx, MyListItem listToPurge)
- {
- try
- {
- List spList = ctx.Web.Lists.GetByTitle(listToPurge.Title);
- ctx.Load(spList);
- CamlQuery itemsIdQuery = CamlQuery.CreateAllItemsQuery(50, new string[] { "Id" });
- int lastIdWithException = -1;
- int maxBatchNumber = 1000;
- while (--maxBatchNumber > 0)
- {
- var itemBatch = spList.GetItems(itemsIdQuery);
- ctx.Load(itemBatch);
- ctx.ExecuteQuery();
- if (itemBatch.Count == 0)
- {
- return;
- }
- foreach (var item in itemBatch)
- {
- try
- {
- this.DeleteItemAndAttachments(ctx, spList, item.Id);
- }
- catch (Exception)
- {
- if (item.Id == lastIdWithException)
- {
- throw;
- }
- lastIdWithException = item.Id;
- }
- progressBar.PerformStep();
- Application.DoEvents();
- }
- }
- //ctx.ExecuteQuery();
- }
- catch (Exception e)
- {
- MessageBox.Show(string.Format("Exception has occured : {0}", e), "Exception in purging list", MessageBoxButtons.OK, MessageBoxIcon.Error);
- }
- }
- private void DeleteItemAndAttachments(ClientContext ctx, List spList, int id)
- {
- ListItem itemToDelete = spList.GetItemById(id);
- ctx.Load(itemToDelete, i => i.AttachmentFiles);
- ctx.ExecuteQuery();
- for (int attachmentIndex = itemToDelete.AttachmentFiles.Count - 1; attachmentIndex >= 0; attachmentIndex--)
- {
- itemToDelete.AttachmentFiles[attachmentIndex].DeleteObject();
- }
- itemToDelete.DeleteObject();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement