Exemplo n.º 1
0
        public Web Setup()
        {
            using (var ctx = TestCommon.CreateClientContext())
            {
                var name = "WebExtensions";
                ctx.ExecuteQuery();

                ExceptionHandlingScope scope = new ExceptionHandlingScope(ctx);

                Web web;

                using (scope.StartScope())
                {
                    using (scope.StartTry())
                    {
                        web = ctx.Site.OpenWeb(name);
                        web.DeleteObject();
                    }
                    using (scope.StartCatch())
                    {
                        web = ctx.Web.Webs.Add(new WebCreationInformation
                        {
                            Title = name,
			    WebTemplate = "STS#0",
                            Url = name
                        });
                    }
                    using (scope.StartFinally())
                    {
                        return web;
                    }
                }
            }
        }
Exemplo n.º 2
0
        public Web Setup()
        {
            using (var ctx = TestCommon.CreateClientContext())
            {
                var name = "WebExtensions";
                ctx.ExecuteQuery();

                ExceptionHandlingScope scope = new ExceptionHandlingScope(ctx);

                Web web;

                using (scope.StartScope())
                {
                    using (scope.StartTry())
                    {
                        web = ctx.Site.OpenWeb(name);
                        web.DeleteObject();
                    }
                    using (scope.StartCatch())
                    {
                        web = ctx.Web.Webs.Add(new WebCreationInformation
                        {
                            Title       = name,
                            WebTemplate = "STS#0",
                            Url         = name
                        });
                    }
                    using (scope.StartFinally())
                    {
                        return(web);
                    }
                }
            }
        }
Exemplo n.º 3
0
        private void button9_Click(object sender, EventArgs e)
        {
            using (var context = new ClientContext("https://thethread-qa.carpetright.co.uk/Facilities/"))
            {
                try
                {
                    var  web  = context.Web;
                    List list = null;
                    ListItemCollection items = null;
                    var scope = new ExceptionHandlingScope(context);
                    using (scope.StartScope())
                    {
                        using (scope.StartTry())
                        {
                            list = web.Lists.GetByTitle("Test Tasks");
                            var query = new CamlQuery();
                            query.ViewXml = "<View><RowLimit>1</RowLimit></View>";
                            items         = list.GetItems(query);


                            context.Load(items);
                        }
                        using (scope.StartCatch())
                        {
                            var lci = new ListCreationInformation();
                            lci.Title             = "Test Tasks";
                            lci.QuickLaunchOption = QuickLaunchOptions.On;
                            lci.TemplateType      = (int)ListTemplateType.Tasks;
                            list = web.Lists.Add(lci);
                        }

                        using (scope.StartFinally())
                        {
                            // list = web.Lists.GetByTitle("Test Tasks");
                            // context.Load(list);
                        }
                    }


                    //context.Load(web);

                    context.ExecuteQuery();
                    var item = items.FirstOrDefault();
                    if (item != null)
                    {
                        item["Status"]          = "In Progress";
                        item["PercentComplete"] = 0.1;
                        item.Update();
                    }
                    context.ExecuteQuery();
                    // var status = scope.HasException ? "Not Created" : "Created";
                    ResultsListBox.Items.Add("Item updated");
                }
                catch (Exception ex)
                {
                    ResultsListBox.Items.Add(ex.Message);
                }
            }
        }
Exemplo n.º 4
0
        private void button8_Click(object sender, EventArgs e)
        {
            using (var context = new ClientContext("https://thethread-qa.carpetright.co.uk/Facilities/"))
            {
                try
                {
                    var  web   = context.Web;
                    List list  = null;
                    var  scope = new ExceptionHandlingScope(context);
                    using (scope.StartScope())
                    {
                        using (scope.StartTry())
                        {
                            list = web.Lists.GetByTitle("Test Tasks");
                            var ici  = new ListItemCreationInformation();
                            var item = list.AddItem(ici);
                            item["Title"]      = "Sample Task";
                            item["AssignedTo"] = web.CurrentUser;
                            item["DueDate"]    = DateTime.Now.AddDays(7);
                            item.Update();
                            //context.Load(list);
                        }
                        using (scope.StartCatch())
                        {
                            var lci = new ListCreationInformation();
                            lci.Title             = "Test Tasks";
                            lci.QuickLaunchOption = QuickLaunchOptions.On;
                            lci.TemplateType      = (int)ListTemplateType.Tasks;
                            list = web.Lists.Add(lci);
                        }

                        using (scope.StartFinally())
                        {
                            // list = web.Lists.GetByTitle("Test Tasks");
                            // context.Load(list);
                        }
                    }


                    //context.Load(web);

                    context.ExecuteQuery();

                    var status = scope.HasException ? "Not Created" : "Created";
                    ResultsListBox.Items.Add("Item " + status);
                }
                catch (Exception ex)
                {
                    ResultsListBox.Items.Add(ex.Message);
                }
            }
        }
Exemplo n.º 5
0
        private static void EnsureFolder(Web web, string filePath, string fileFolder)
        {
            if (string.IsNullOrEmpty(fileFolder))
            {
                return;
            }

            var lists = web.Lists;

            web.Context.Load(web);
            web.Context.Load(lists, l => l.Include(ll => ll.DefaultViewUrl));
            web.Context.ExecuteQuery();

            ExceptionHandlingScope scope = new ExceptionHandlingScope(web.Context);

            using (scope.StartScope())
            {
                using (scope.StartTry())
                {
                    var folder = web.GetFolderByServerRelativeUrl(string.Concat(filePath, fileFolder));
                    web.Context.Load(folder);
                }

                using (scope.StartCatch())
                {
                    var list = lists.Where(l => l.DefaultViewUrl.IndexOf(filePath, StringComparison.CurrentCultureIgnoreCase) >= 0).FirstOrDefault();

                    ListItemCreationInformation newFolder = new ListItemCreationInformation();
                    newFolder.UnderlyingObjectType = FileSystemObjectType.Folder;
                    newFolder.FolderUrl            = filePath.TrimEnd(Program.trimChars);
                    newFolder.LeafName             = fileFolder;

                    ListItem item = list.AddItem(newFolder);
                    web.Context.Load(item);
                    item.Update();
                }

                using (scope.StartFinally())
                {
                    var folder = web.GetFolderByServerRelativeUrl(string.Concat(filePath, fileFolder));
                    web.Context.Load(folder);
                }
            }

            web.Context.ExecuteQuery();
        }
Exemplo n.º 6
0
        private void button7_Click(object sender, EventArgs e)
        {
            using (var context = new ClientContext("https://thethread-qa.carpetright.co.uk/Facilities/"))
            {
                try
                {
                    var  web   = context.Web;
                    List list  = null;
                    var  scope = new ExceptionHandlingScope(context);
                    using (scope.StartScope())
                    {
                        using (scope.StartTry())
                        {
                            list = web.Lists.GetByTitle("Test Tasks");
                            context.Load(list);
                        }
                        using (scope.StartCatch())
                        {
                            var lci = new ListCreationInformation();
                            lci.Title             = "Test Tasks";
                            lci.QuickLaunchOption = QuickLaunchOptions.On;
                            lci.TemplateType      = (int)ListTemplateType.Tasks;
                            list = web.Lists.Add(lci);
                        }

                        using (scope.StartFinally())
                        {
                            list = web.Lists.GetByTitle("Test Tasks");
                            context.Load(list);
                        }
                    }


                    //context.Load(web);

                    context.ExecuteQuery();

                    var status = scope.HasException ? "Created" : "Loaded";
                    ResultsListBox.Items.Add(list.Title + status);
                }
                catch (Exception ex)
                {
                    ResultsListBox.Items.Add(ex.Message);
                }
            }
        }
        /// <summary>
        /// Makes sure a folder exists in SharePoint. The folder will be added if it does not exist.
        /// </summary>
        /// <param name="web">Web where the folder exists.</param>
        /// <param name="listUrl">Path of the item.</param>
        /// <param name="folderUrl">URL of the folder that should exist.</param>
        /// <param name="parentFolder">Parent of the folder.</param>
        /// <returns></returns>
        private static Folder EnsureFolder(this Web web, string listUrl, string folderUrl, Folder parentFolder)
        {
            Folder folder = null;
            var    folderServerRelativeUrl = parentFolder == null?listUrl.TrimEnd(Program._TrimChars) + "/" + folderUrl : parentFolder.ServerRelativeUrl.TrimEnd(Program._TrimChars) + "/" + folderUrl;

            if (string.IsNullOrEmpty(folderUrl))
            {
                return(null);
            }

            var lists = web.Lists;

            web.Context.Load(web);
            web.Context.Load(lists, l => l.Include(ll => ll.DefaultViewUrl));
            web.Context.ExecuteQueryRetry();

            ExceptionHandlingScope scope = new ExceptionHandlingScope(web.Context);

            using (scope.StartScope()) {
                using (scope.StartTry()) {
                    folder = web.GetFolderByServerRelativeUrl(folderServerRelativeUrl);
                    web.Context.Load(folder);
                }

                using (scope.StartCatch()) {
                    var list = lists.Where(l => l.DefaultViewUrl.IndexOf(listUrl, StringComparison.CurrentCultureIgnoreCase) >= 0).FirstOrDefault();

                    if (parentFolder == null)
                    {
                        parentFolder = list.RootFolder;
                    }


                    folder = parentFolder.Folders.Add(folderUrl);
                    web.Context.Load(folder);
                }

                using (scope.StartFinally()) {
                    folder = web.GetFolderByServerRelativeUrl(folderServerRelativeUrl);
                    web.Context.Load(folder);
                }
            }

            web.Context.ExecuteQueryRetry();
            return(folder);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Ensures the folder asynchronous.
        /// </summary>
        /// <param name="listUrl">The list URL.</param>
        /// <param name="folderUrl">The folder URL.</param>
        /// <param name="parentFolder">The parent folder.</param>
        /// <param name="retrievals">The retrievals.</param>
        /// <returns></returns>
        public async Task <Folder> EnsureFolderAsync(string listUrl, string folderUrl, Folder parentFolder = null, params Expression <Func <Folder, object> >[] retrievals)
        {
            if (string.IsNullOrEmpty(listUrl))
            {
                throw new ArgumentNullException(nameof(listUrl));
            }
            if (string.IsNullOrEmpty(folderUrl))
            {
                throw new ArgumentNullException(nameof(folderUrl));
            }
            listUrl   = listUrl.Replace("\\", "/");
            folderUrl = folderUrl.Replace("\\", "/");
            Folder folder;
            var    list = await GetListFromUrlAsync(listUrl);

            var scope = new ExceptionHandlingScope(_web.Context);

            using (scope.StartScope())
            {
                using (scope.StartTry())
                    GetExistingFolder(listUrl, folderUrl, parentFolder, null);
                using (scope.StartCatch())
                    CreateFolder(list, folderUrl, parentFolder);
                using (scope.StartFinally())
                    folder = GetExistingFolder(listUrl, folderUrl, parentFolder, retrievals);
            }
            var attempt = 0;

            while (true)
            {
                try
                {
                    await _web.Context.ExecuteQueryAsync();

                    return(folder);
                }
                catch (ServerException e) when(e.Message == "File Not Found." && attempt++ <= 2)
                {
                    _log?.LogInformation($"Retry{attempt}: {e.Message}");
                    Thread.Sleep(100);
                }
            }
        }
Exemplo n.º 9
0
        public Web Setup(string webTemplate = "STS#0", bool enablePublishingInfrastructure = false)
        {
            using (var ctx = TestCommon.CreateClientContext())
            {
                var name = "WebExtensions";
                ctx.ExecuteQueryRetry();

                ExceptionHandlingScope scope = new ExceptionHandlingScope(ctx);

                Web web;
                Site site;
                site = ctx.Site;
                if (enablePublishingInfrastructure && !site.IsFeatureActive(publishingSiteFeatureId))
                {
                    site.ActivateFeature(publishingSiteFeatureId);
                    deactivatePublishingOnTearDown = true;
                }
                using (scope.StartScope())
                {                    
                    using (scope.StartTry())
                    {
                        web = ctx.Site.OpenWeb(name);
                        web.DeleteObject();
                    }
                    using (scope.StartCatch())
                    {
                        
                        web = ctx.Web.Webs.Add(new WebCreationInformation
                        {
                            Title = name,
                            WebTemplate = webTemplate,
                            Url = name
                        });                        
                    }
                    using (scope.StartFinally())
                    {                        
                        return web;
                    }
                }
            }
        }
Exemplo n.º 10
0
        public Web Setup(string webTemplate = "STS#0", bool enablePublishingInfrastructure = false)
        {
            using (var ctx = TestCommon.CreateClientContext())
            {
                var name = "WebExtensions";
                ctx.ExecuteQuery();

                ExceptionHandlingScope scope = new ExceptionHandlingScope(ctx);

                Web  web;
                Site site;
                site = ctx.Site;
                if (enablePublishingInfrastructure && !site.IsFeatureActive(publishingSiteFeatureId))
                {
                    site.ActivateFeature(publishingSiteFeatureId);
                    deactivatePublishingOnTearDown = true;
                }
                using (scope.StartScope())
                {
                    using (scope.StartTry())
                    {
                        web = ctx.Site.OpenWeb(name);
                        web.DeleteObject();
                    }
                    using (scope.StartCatch())
                    {
                        web = ctx.Web.Webs.Add(new WebCreationInformation
                        {
                            Title       = name,
                            WebTemplate = webTemplate,
                            Url         = name
                        });
                    }
                    using (scope.StartFinally())
                    {
                        return(web);
                    }
                }
            }
        }
Exemplo n.º 11
0
        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);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Ensures all folders asynchronous.
        /// </summary>
        /// <param name="listUrl">The list URL.</param>
        /// <param name="folderUrls">The folder urls.</param>
        /// <param name="batchSize">Size of the batch.</param>
        /// <returns></returns>
        /// <exception cref="Dictionary<string, Folder>"></exception>
        public async Task EnsureAllFoldersAsync(string listUrl, IEnumerable <string> folderUrls, int batchSize = 50)
        {
            if (string.IsNullOrEmpty(listUrl))
            {
                throw new ArgumentNullException(nameof(listUrl));
            }
            if (folderUrls == null)
            {
                return;
            }
            var levels = folderUrls.SelectMany(s =>
            {
                var ss = s.Replace("\\", "/").Split(new[] { "/" }, StringSplitOptions.RemoveEmptyEntries);
                return(ss.Select((_, level) => (level, path: $"{listUrl}/{string.Join("/", ss.Take(level + 1))}")));
            }).Distinct().ToLookup(s => s.level, s => s.path).ToList();
            var list = await GetListFromUrlAsync(listUrl);

            var folders = new Dictionary <string, Folder> {
                { listUrl, null }
            };

            foreach (var level in levels)
            {
                foreach (var batch in level.GroupAt(batchSize))
                {
                    foreach (var path in batch)
                    {
                        var scope = new ExceptionHandlingScope(_web.Context);
                        using (scope.StartScope())
                        {
                            var folderPath = Path.GetDirectoryName(path).Replace("\\", "/");
                            if (!folders.TryGetValue(folderPath, out var parentFolder))
                            {
                                throw new InvalidOperationException(folderPath);
                            }
                            var folderUrl = Path.GetFileName(path);
                            using (scope.StartTry())
                                GetExistingFolder(listUrl, folderUrl, parentFolder, null);
                            using (scope.StartCatch())
                                CreateFolder(list, folderUrl, parentFolder);
                            using (scope.StartFinally())
                                folders[path] = GetExistingFolder(listUrl, folderUrl, parentFolder, null);
                        }
                    }
                    var attempt = 0;
                    while (true)
                    {
                        try
                        {
                            await _web.Context.ExecuteQueryAsync();

                            break;
                        }
                        catch (ServerException e) when(e.Message == "File Not Found." && attempt++ <= 3)
                        {
                            _log?.LogInformation($"Retry{attempt}: {e.Message}");
                            Thread.Sleep(500);
                        }
                    }
                }
            }
        }
Exemplo n.º 13
0
        private static Folder EnsureFolder(Web web, string listUrl, string folderUrl, Folder parentFolder) {
            Folder folder = null;
            var folderServerRelativeUrl = parentFolder == null ? listUrl.TrimEnd(Program.trimChars) + "/" + folderUrl : parentFolder.ServerRelativeUrl.TrimEnd(Program.trimChars) + "/" + folderUrl;

            if (string.IsNullOrEmpty(folderUrl)) {
                return null;
            }

            var lists = web.Lists;
            web.Context.Load(web);
            web.Context.Load(lists, l => l.Include(ll => ll.DefaultViewUrl));
            web.Context.ExecuteQuery();

            ExceptionHandlingScope scope = new ExceptionHandlingScope(web.Context);
            using (scope.StartScope()) {
                using (scope.StartTry()) {
                    folder = web.GetFolderByServerRelativeUrl(folderServerRelativeUrl);
                    web.Context.Load(folder);
                }

                using (scope.StartCatch()) {
                    var list = lists.Where(l => l.DefaultViewUrl.IndexOf(listUrl, StringComparison.CurrentCultureIgnoreCase) >= 0).FirstOrDefault();

                    if (parentFolder == null) {
                        parentFolder = list.RootFolder;
                    }


                    folder = parentFolder.Folders.Add(folderUrl);
                    web.Context.Load(folder);
                }

                using (scope.StartFinally()) {
                    folder = web.GetFolderByServerRelativeUrl(folderServerRelativeUrl);
                    web.Context.Load(folder);
                }
            }

            web.Context.ExecuteQuery();
            return folder;
        }
Exemplo n.º 14
0
        private string TryCreateList(String listTitle, SPRemoteEventProperties properties)
        {
            string errorMessage = String.Empty;

            using (ClientContext clientContext = TokenHelper.CreateAppEventClientContext(properties, useAppWeb: false))
            {
                if (clientContext != null)
                {
                    // Get references to the objects needed later.
                    ListCollection allLists = clientContext.Web.Lists;
                    IEnumerable<List> matchingLists = clientContext.LoadQuery(allLists.Where(list => list.Title == listTitle));

                    clientContext.ExecuteQuery();

                    var foundList = matchingLists.FirstOrDefault();
                    List createdList = null;

                    // Delegate the rollback logic to the SharePoint server.
                    ExceptionHandlingScope scope = new ExceptionHandlingScope(clientContext);
                    using (scope.StartScope())
                    {

                        using (scope.StartTry())
                        {
                            // SharePoint might be retrying the event after a time-out, so
                            // check to see if there's already a list with that name. 
                            // If there isn't, create it.                             
                            ConditionalScope condScope = new ConditionalScope(clientContext, () => foundList.ServerObjectIsNull.Value == true, true);
                            using (condScope.StartScope())
                            {
                                ListCreationInformation listInfo = new ListCreationInformation();
                                listInfo.Title = listTitle;
                                listInfo.TemplateType = (int)ListTemplateType.GenericList;
                                listInfo.Url = listTitle;
                                createdList = clientContext.Web.Lists.Add(listInfo);
                            }
                            // 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 if the try code got far enough to create the list before it errored.
                            // If it did, roll this change back by deleting the list.
                            ConditionalScope condScope = new ConditionalScope(clientContext, () => createdList.ServerObjectIsNull.Value != true, true);
                            using (condScope.StartScope())
                            {
                                createdList.DeleteObject();
                            }
                        }
                        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;
        }
Exemplo n.º 15
0
        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;
        }
Exemplo n.º 16
0
        private static void EnsureFolder(Web web, string filePath, string fileFolder)
        {
            if (string.IsNullOrEmpty(fileFolder))
            {
                return;
            }

            var lists = web.Lists;
            web.Context.Load(web);
            web.Context.Load(lists, l => l.Include(ll => ll.DefaultViewUrl));
            web.Context.ExecuteQuery();

            ExceptionHandlingScope scope = new ExceptionHandlingScope(web.Context);
            using (scope.StartScope())
            {
                using (scope.StartTry())
                {
                    var folder = web.GetFolderByServerRelativeUrl(string.Concat(filePath, fileFolder));
                    web.Context.Load(folder);
                }

                using (scope.StartCatch())
                {
                    var list = lists.Where(l => l.DefaultViewUrl.IndexOf(filePath, StringComparison.CurrentCultureIgnoreCase) >= 0).FirstOrDefault();

                    ListItemCreationInformation newFolder = new ListItemCreationInformation();
                    newFolder.UnderlyingObjectType = FileSystemObjectType.Folder;
                    newFolder.FolderUrl = filePath.TrimEnd(Program.trimChars);
                    newFolder.LeafName = fileFolder;

                    ListItem item = list.AddItem(newFolder);
                    web.Context.Load(item);
                    item.Update();
                }

                using (scope.StartFinally())
                {
                    var folder = web.GetFolderByServerRelativeUrl(string.Concat(filePath, fileFolder));
                    web.Context.Load(folder);
                }
            }

            web.Context.ExecuteQuery();
        }
Exemplo n.º 17
0
        private string TryCreateList(String listTitle, SPRemoteEventProperties properties)
        {
            string errorMessage = String.Empty;

            using (ClientContext clientContext = TokenHelper.CreateAppEventClientContext(properties, useAppWeb: false))
            {
                if (clientContext != null)
                {
                    // Get references to the objects needed later.
                    ListCollection     allLists      = clientContext.Web.Lists;
                    IEnumerable <List> matchingLists = clientContext.LoadQuery(allLists.Where(list => list.Title == listTitle));

                    clientContext.ExecuteQuery();

                    var  foundList   = matchingLists.FirstOrDefault();
                    List createdList = null;

                    // Delegate the rollback logic to the SharePoint server.
                    ExceptionHandlingScope scope = new ExceptionHandlingScope(clientContext);
                    using (scope.StartScope())
                    {
                        using (scope.StartTry())
                        {
                            // SharePoint might be retrying the event after a time-out, so
                            // check to see if there's already a list with that name.
                            // If there isn't, create it.
                            ConditionalScope condScope = new ConditionalScope(clientContext, () => foundList.ServerObjectIsNull.Value == true, true);
                            using (condScope.StartScope())
                            {
                                ListCreationInformation listInfo = new ListCreationInformation();
                                listInfo.Title        = listTitle;
                                listInfo.TemplateType = (int)ListTemplateType.GenericList;
                                listInfo.Url          = listTitle;
                                createdList           = clientContext.Web.Lists.Add(listInfo);
                            }
                            // 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 if the try code got far enough to create the list before it errored.
                            // If it did, roll this change back by deleting the list.
                            ConditionalScope condScope = new ConditionalScope(clientContext, () => createdList.ServerObjectIsNull.Value != true, true);
                            using (condScope.StartScope())
                            {
                                createdList.DeleteObject();
                            }
                        }
                        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);
        }
Exemplo n.º 18
0
            public static void DetectTermStore()
            {
                if (SampleData.termStoreId != null)
                {
                    return;
                }

                var clientContext   = new ClientContext(TestConfiguration.SharePointSiteUrl);
                var taxonomySession = TaxonomySession.GetTaxonomySession(clientContext);

                clientContext.Load(taxonomySession, x => x.OfflineTermStoreNames);

                if (TestConfiguration.TestTermStoreId != null)
                {
                    // Check that the configured ID is valid
                    TermStore termStore = null;
                    var       scope     = new ExceptionHandlingScope(clientContext);
                    using (scope.StartScope())
                    {
                        using (scope.StartTry())
                        {
                            termStore = taxonomySession.TermStores.GetById(TestConfiguration.TestTermStoreId.Value);
                            clientContext.Load(termStore, x => x.Id);
                        }
                        using (scope.StartFinally())
                        {
                        }
                    }
                    clientContext.ExecuteQuery();

                    if (termStore.ServerObjectIsNull != false)
                    {
                        if (taxonomySession.OfflineTermStoreNames.Count() > 0)
                        {
                            throw new InvalidOperationException("The term store is offline");
                        }
                        else
                        {
                            throw new InvalidOperationException("A term store was not found with ID="
                                                                + TestConfiguration.TestTermStoreId.Value);
                        }
                    }
                    SampleData.termStoreId = termStore.Id;
                }
                else
                {
                    // Use the default term store ID
                    TermStore termStore = taxonomySession.GetDefaultSiteCollectionTermStore();
                    clientContext.Load(termStore, x => x.Id);
                    clientContext.ExecuteQuery();

                    if (termStore.ServerObjectIsNull == true)
                    {
                        if (taxonomySession.OfflineTermStoreNames.Count() > 0)
                        {
                            throw new InvalidOperationException("The term store is offline");
                        }
                        else
                        {
                            throw new InvalidOperationException("A default term store is not configured");
                        }
                    }
                    SampleData.termStoreId = termStore.Id;
                }
            }