/// <summary> /// Execute the cmdlet /// </summary> public override void ExecuteCmdlet() { base.ExecuteCmdlet(); if (!RecycleBinType.HasValue) { RecycleBinType = RecycleBinItemType.Folder; } if (!RecycleBinOrder.HasValue) { RecycleBinOrder = RecycleBinOrderBy.DeletedBy; } if (!RowLimit.HasValue) { RowLimit = 200; } var results = new Collection <SPRecycleBinElement>(); var failedrestores = new Collection <SPRecycleBinElement>(); var restorepath = new Collection <SPRecycleBinRestoreModel>(); // this should be valid based on pre authentication checks var _currentUserInProcess = CurrentUserName; LogVerbose("Started-QueryRecycleBin: User:{0} at {1}", _currentUserInProcess, DateTime.Now); var collSite = this.ClientContext.Site; var collWeb = this.ClientContext.Web; this.ClientContext.Load(collSite); this.ClientContext.Load(collWeb); this.ClientContext.ExecuteQueryRetry(); if (this.SitePathUrl.IndexOf("/", StringComparison.CurrentCultureIgnoreCase) == 0) { SitePathUrl = SitePathUrl.Substring(1); } var rbiQueryCount = 0; var rbiCollectionCount = 0; var pagingLimit = RowLimit.Value; var paging = true; string pagingInfo = null; try { while (paging) { LogVerbose("Paging Recycle bin {0} with paging sequence [{1}]", SitePathUrl, pagingInfo); RecycleBinItemCollection recycleBinCollection = collSite.GetRecycleBinItems(pagingInfo, pagingLimit, false, RecycleBinOrder.Value, RecycleBinItemState.FirstStageRecycleBin); this.ClientContext.Load(recycleBinCollection); this.ClientContext.ExecuteQueryRetry(); paging = false; if (recycleBinCollection != null && recycleBinCollection.Count > 0) { var rbiQuery = recycleBinCollection.Where(w => w.DirName.StartsWith(this.SitePathUrl, StringComparison.CurrentCultureIgnoreCase) && w.ItemType == RecycleBinType).OrderBy(ob => ob.DirName); rbiQueryCount = rbiQuery.Count(); rbiCollectionCount = recycleBinCollection.Count(); LogVerbose("Query resulted in {0} items", rbiQueryCount); foreach (var rbiItem in rbiQuery) { var newitem = new SPRecycleBinRestoreModel() { Title = rbiItem.Title, Id = rbiItem.Id, FileSize = rbiItem.Size, LeafName = rbiItem.LeafName, DirName = rbiItem.DirName, FileType = rbiItem.ItemType, FileState = rbiItem.ItemState, Author = rbiItem.AuthorName, AuthorEmail = rbiItem.AuthorEmail, DeletedBy = rbiItem.DeletedByName, DeletedByEmail = rbiItem.DeletedByEmail, Deleted = rbiItem.DeletedDate, PagingInfo = pagingInfo }; restorepath.Add(newitem); } if (rbiCollectionCount >= pagingLimit) { var pageItem = recycleBinCollection[recycleBinCollection.Count() - 1]; var leafNameEncoded = HttpUtility.UrlPathEncode(pageItem.Title, true).Replace(".", "%2E"); var searchEncoded = HttpUtility.UrlPathEncode(pageItem.DirName, true); pagingInfo = string.Format("id={0}&title={1}&searchValue={2}", pageItem.Id, leafNameEncoded, searchEncoded); paging = true; } } else { LogVerbose("The Recycle Bin is empty."); } } if (restorepath.Count() > 0) { var orderedrestore = restorepath.OrderBy(ob => ob.DirName); LogVerbose("Restoring: {0} items for {1}", restorepath.Count, SitePathUrl); foreach (var newitem in orderedrestore) { if (this.ShouldProcess(string.Format("Restoring {0} from recycle bin", newitem.LeafName))) { try { var rbiItem = collSite.RecycleBin.GetById(newitem.Id); this.ClientContext.Load(rbiItem); this.ClientContext.ExecuteQueryRetry(); rbiItem.Restore(); this.ClientContext.ExecuteQueryRetry(); results.Add(newitem); LogVerbose("Restored: {0}|{1}, Deleted By:{2}", newitem.DirName, newitem.LeafName, newitem.DeletedByEmail); } catch (Exception ex) { rbiQueryCount--; failedrestores.Add(newitem); LogWarning("Failed: {0}|{1} MSG:{2}", newitem.DirName, newitem.LeafName, ex.Message); } } } } } catch (Exception ex) { LogError(ex, "Failed to retrieve recycle bin collection"); } WriteObject(results); LogVerbose("Completed: {0} from UserID {1}", DateTime.Now, _currentUserInProcess); }
private void RestoreList(String title, SPRemoteEventProperties properties) { using (ClientContext clientContext = TokenHelper.CreateAppEventClientContext(properties, useAppWeb: false)) { if (clientContext != null) { // Check to see that a user hasn't manually deleted the list from the Recycle Bin RecycleBinItemCollection bin = clientContext.Web.RecycleBin; IEnumerable <RecycleBinItem> matchingItems = clientContext.LoadQuery(bin.Where(item => item.Title == title)); clientContext.ExecuteQuery(); RecycleBinItem recycledList = matchingItems.FirstOrDefault(); // If it is there, restore it. if (recycledList != null) { recycledList.Restore(); clientContext.ExecuteQuery(); } } } }
private string TryRecycleList(String listTitle, SPRemoteEventProperties properties) { string errorMessage = String.Empty; using (ClientContext clientContext = TokenHelper.CreateAppEventClientContext(properties, useAppWeb: false)) { if (clientContext != null) { // Get references to all the objects you are going to need. ListCollection allLists = clientContext.Web.Lists; IEnumerable <List> matchingLists = clientContext.LoadQuery(allLists.Where(list => list.Title == listTitle)); RecycleBinItemCollection bin = clientContext.Web.RecycleBin; IEnumerable <RecycleBinItem> matchingRecycleBinItems = clientContext.LoadQuery(bin.Where(item => item.Title == listTitle)); clientContext.ExecuteQuery(); List foundList = matchingLists.FirstOrDefault(); RecycleBinItem recycledList = matchingRecycleBinItems.FirstOrDefault(); // Delegate the rollback logic to the SharePoint server. ExceptionHandlingScope scope = new ExceptionHandlingScope(clientContext); using (scope.StartScope()) { using (scope.StartTry()) { // Check to see that a user hasn't already recycled the list in the SharePoint UI. // If it is still there, recycle it. ConditionalScope condScope = new ConditionalScope(clientContext, () => foundList.ServerObjectIsNull.Value == false, true); using (condScope.StartScope()) { // Looks crazy to test for nullity inside a test for nullity, // but without this inner test, foundList.Recycle() throws a null reference // exception when the client side runtime is creating the XML to // send to the server. if (foundList != null) { foundList.Recycle(); } } // To test that your StartCatch block runs, uncomment the following two lines // and put them somewhere in the StartTry block. //List fakeList = clientContext.Web.Lists.GetByTitle("NoSuchList"); //clientContext.Load(fakeList); } using (scope.StartCatch()) { // Check to see that the list is in the Recycle Bin. // A user might have manually deleted the list from the Recycle Bin, // or StartTry block may have errored before it recycled the list. // If it is in the Recycle Bin, restore it. ConditionalScope condScope = new ConditionalScope(clientContext, () => recycledList.ServerObjectIsNull.Value == false, true); using (condScope.StartScope()) { // Another test within a test to avoid a null reference. if (recycledList != null) { recycledList.Restore(); } } } using (scope.StartFinally()) { } } clientContext.ExecuteQuery(); if (scope.HasException) { errorMessage = String.Format("{0}: {1}; {2}; {3}; {4}; {5}", scope.ServerErrorTypeName, scope.ErrorMessage, scope.ServerErrorDetails, scope.ServerErrorValue, scope.ServerStackTrace, scope.ServerErrorCode); } } } return(errorMessage); }