Exemplo n.º 1
0
        static void EnsureCustomPagesLibrary()
        {
            string libraryTitle = "Custom Pages";
            string libraryUrl   = "CustomPages";

            // delete document library if it already exists
            ExceptionHandlingScope scope = new ExceptionHandlingScope(clientContext);

            using (scope.StartScope()) {
                using (scope.StartTry()) {
                    site.Lists.GetByTitle(libraryTitle).DeleteObject();
                }
                using (scope.StartCatch()) { }
            }

            ListCreationInformation lci = new ListCreationInformation();

            lci.Title          = libraryTitle;
            lci.Url            = libraryUrl;
            lci.TemplateType   = (int)ListTemplateType.DocumentLibrary;
            CustomPagesLibrary = site.Lists.Add(lci);
            CustomPagesLibrary.OnQuickLaunch = true;
            CustomPagesLibrary.Update();
            CustomPagesLibrary.RootFolder.Folders.Add("content");
            CustomPagesLibrary.RootFolder.Folders.Add("scripts");
            clientContext.Load(CustomPagesLibrary);
            clientContext.ExecuteQuery();

            CustomPagesLibraryRelativeUrl = "~site/" + libraryUrl + "/";
            CustomPagesLibraryAbsoluteUrl = site.Url + "/" + libraryUrl + "/";
        }
Exemplo n.º 2
0
    static void EnsureCustomPagesLibrary() {

      string libraryTitle = "Custom Pages";
      string libraryUrl = "CustomPages";

      // delete document library if it already exists
      ExceptionHandlingScope scope = new ExceptionHandlingScope(clientContext);
      using (scope.StartScope()) {
        using (scope.StartTry()) {
          site.Lists.GetByTitle(libraryTitle).DeleteObject();
        }
        using (scope.StartCatch()) { }
      }

      ListCreationInformation lci = new ListCreationInformation();
      lci.Title = libraryTitle;
      lci.Url = libraryUrl;
      lci.TemplateType = (int)ListTemplateType.DocumentLibrary;
      CustomPagesLibrary = site.Lists.Add(lci);
      CustomPagesLibrary.OnQuickLaunch = true;
      CustomPagesLibrary.Update();
      CustomPagesLibrary.RootFolder.Folders.Add("content");
      CustomPagesLibrary.RootFolder.Folders.Add("scripts");
      clientContext.Load(CustomPagesLibrary);
      clientContext.ExecuteQuery();

      CustomPagesLibraryRelativeUrl = "~site/" + libraryUrl + "/";
      CustomPagesLibraryAbsoluteUrl = site.Url + "/" + libraryUrl + "/";

    }
Exemplo n.º 3
0
        static void CreateExpensesList()
        {
            string listTitle = "Expenses";
            string listUrl   = "Lists/Expenses";

            // delete document library if it already exists
            ExceptionHandlingScope scope = new ExceptionHandlingScope(clientContext);

            using (scope.StartScope()) {
                using (scope.StartTry()) {
                    site.Lists.GetByTitle(listTitle).DeleteObject();
                }
                using (scope.StartCatch()) { }
            }

            ListCreationInformation lci = new ListCreationInformation();

            lci.Title                         = listTitle;
            lci.Url                           = listUrl;
            lci.TemplateType                  = (int)ListTemplateType.GenericList;
            listExpenses                      = site.Lists.Add(lci);
            listExpenses.OnQuickLaunch        = true;
            listExpenses.EnableFolderCreation = false;
            listExpenses.Update();


            // attach JSLink script to default view for client-side rendering
            //listExpenses.DefaultView.JSLink = AppRootFolderRelativeUrl + "scripts/CustomersListCSR.js";
            listExpenses.DefaultView.Update();
            listExpenses.Update();
            clientContext.Load(listExpenses);
            clientContext.Load(listExpenses.Fields);
            var titleField = listExpenses.Fields.GetByInternalNameOrTitle("Title");

            titleField.Title = "Expense Description";
            titleField.Update();
            clientContext.ExecuteQuery();

            listExpenses.ContentTypesEnabled = true;
            listExpenses.ContentTypes.AddExistingContentType(ctypeExpense);
            listExpenses.Update();
            clientContext.Load(listExpenses.ContentTypes);
            clientContext.ExecuteQuery();

            ContentType existing = listExpenses.ContentTypes[0];

            existing.DeleteObject();
            clientContext.ExecuteQuery();

            View viewProducts = listExpenses.DefaultView;

            viewProducts.ViewFields.Add("ExpenseCategory");
            viewProducts.ViewFields.Add("ExpenseDate");
            viewProducts.ViewFields.Add("ExpenseAmount");
            viewProducts.Update();

            clientContext.ExecuteQuery();

            PopulateExpensesList();
        }
Exemplo n.º 4
0
        public static void ExceptionTestError(string listName)
        {
            ClientContext clientContext = GetClientContext();
            Web           web           = clientContext.Web;

            ExceptionHandlingScope ehs = new ExceptionHandlingScope(clientContext);

            using (ehs.StartScope())
            {
                using (ehs.StartTry())
                {
                    List list = web.Lists.GetByTitle(listName);
                    list.Description = "List get";
                    list.Update();
                }
                using (ehs.StartCatch())
                {
                    ListCreationInformation create = new ListCreationInformation();
                    create.Title        = listName;
                    create.TemplateType = (int)ListTemplateType.DocumentLibrary;
                    create.Description  = "List create";
                    web.Lists.Add(create);
                }
            }
            List result = web.Lists.GetByTitle(listName);

            clientContext.Load(result);
            clientContext.ExecuteQuery();//执行查询,不会出异常
            Console.WriteLine("Exception" + ehs.HasException);
            Console.WriteLine("Message" + ehs.ErrorMessage);
        }
Exemplo n.º 5
0
        public TermStore FetchClientTermStore(Guid termStoreId)
        {
            TaxonomySession taxonomySession = this.GetTaxonomySession();

            TermStore clientTermStore    = null;
            ExceptionHandlingScope scope = new ExceptionHandlingScope(this.ClientContext);

            using (scope.StartScope())
            {
                using (scope.StartTry())
                {
                    clientTermStore = taxonomySession.TermStores.GetById(termStoreId);
                }
                using (scope.StartCatch())
                {
                }
            }

            this.ExecuteQuery();

            if (scope.HasException || clientTermStore.ServerObjectIsNull.Value)
            {
                throw new InvalidOperationException(string.Format("The term store was not found with ID={0}",
                                                                  termStoreId));
            }
            return(clientTermStore);
        }
Exemplo n.º 6
0
        private Field FindExistingSiteField(Web rootWeb, Guid id)
        {
            var context = rootWeb.Context;
            var scope   = new ExceptionHandlingScope(context);

            Field field = null;

            using (scope.StartScope())
            {
                using (scope.StartTry())
                {
                    rootWeb.AvailableFields.GetById(id);
                }

                using (scope.StartCatch())
                {
                }
            }

            context.ExecuteQueryWithTrace();

            if (!scope.HasException)
            {
                field = rootWeb.AvailableFields.GetById(id);
                context.Load(field);
                context.ExecuteQueryWithTrace();
            }

            return(field);
        }
Exemplo n.º 7
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.º 8
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.º 9
0
        public static bool CheckListExist(ClientContext context, string listUrl)
        {
            var file = context.Web.GetFileByServerRelativePath(ResourcePath.FromDecodedUrl("/sites/Test5/Shared Documents/20200611142343.txt"));

            context.Load(file);
            context.ExecuteQuery();
            bool siteAssetsExist         = false;
            List list                    = null;
            ExceptionHandlingScope scope = new ExceptionHandlingScope(context);

            using (scope.StartScope())
            {
                using (scope.StartTry())
                {
                    list = context.Web.GetList(listUrl);
                    context.Load(list, l => l.Title, l => l.IsSiteAssetsLibrary);
                }
                using (scope.StartCatch())
                { }
            }
            context.ExecuteQuery();
            if (scope.HasException)
            {
            }
            else if (list.ServerObjectIsNull.HasValue && !list.ServerObjectIsNull.Value)
            {
                siteAssetsExist = true;//list.IsSiteAssetsLibrary;
            }
            return(siteAssetsExist);
        }
Exemplo n.º 10
0
        protected TermGroup FindGroup(TermStoreModelHost storeModelHost, TaxonomyTermGroupDefinition groupModel)
        {
            var termStore = storeModelHost.HostTermStore;
            var context   = termStore.Context;

            TermGroup currentGroup = null;

            if (groupModel.IsSiteCollectionGroup)
            {
                currentGroup = FindSiteCollectionGroup(storeModelHost, groupModel);
                return(currentGroup);
            }

            if (groupModel.Id.HasValue)
            {
                var scope = new ExceptionHandlingScope(context);
                using (scope.StartScope())
                {
                    using (scope.StartTry())
                    {
                        currentGroup = termStore.Groups.GetById(groupModel.Id.Value);
                        context.Load(currentGroup);
                    }

                    using (scope.StartCatch())
                    {
                    }
                }
            }
            else if (!string.IsNullOrEmpty(groupModel.Name))
            {
                var scope = new ExceptionHandlingScope(context);
                using (scope.StartScope())
                {
                    using (scope.StartTry())
                    {
                        currentGroup = termStore.Groups.GetByName(groupModel.Name);
                        context.Load(currentGroup);
                    }

                    using (scope.StartCatch())
                    {
                    }
                }
            }

            context.ExecuteQueryWithTrace();

            if (currentGroup != null && currentGroup.ServerObjectIsNull == false)
            {
                context.Load(currentGroup, g => g.Id);
                context.Load(currentGroup, g => g.Name);

                context.ExecuteQueryWithTrace();

                return(currentGroup);
            }

            return(null);
        }
Exemplo n.º 11
0
        public SPOTermGroup CreateGroup(string name, Guid id, string description)
        {
            var       ctx   = _termStore.Context;
            TermGroup group = null;
            ExceptionHandlingScope scope = new ExceptionHandlingScope(ctx);

            using (scope.StartScope())
            {
                using (scope.StartTry())
                {
                    group = _termStore.Groups.GetByName(name);
                    ctx.Load(group);
                }
                using (scope.StartCatch())
                {
                }
            }
            ctx.ExecuteQuery();

            if (group == null || group.ServerObjectIsNull == null || group.ServerObjectIsNull.Value)
            {
                group             = _termStore.CreateGroup(name, id);
                group.Description = description;
                ctx.ExecuteQuery();
                ctx.Load(group);
                ctx.ExecuteQuery();
                return(new SPOTermGroup(group));
            }
            else
            {
                throw new Exception("The specified term group already exists.");
            }
        }
Exemplo n.º 12
0
        protected void cmdCreateCustomersList_Click(object sender, EventArgs e)
        {
            SharePointContext spContext = SharePointContextProvider.Current.GetSharePointContext(Context);

              using (ClientContext clientContext = spContext.CreateUserClientContextForSPHost()) {

            clientContext.Load(clientContext.Web);
            clientContext.ExecuteQuery();
            string listTitle = "Customers";

            // delete list if it exists
            ExceptionHandlingScope scope = new ExceptionHandlingScope(clientContext);
            using (scope.StartScope()) {
              using (scope.StartTry()) {
            clientContext.Web.Lists.GetByTitle(listTitle).DeleteObject();
              }
              using (scope.StartCatch()) { }
            }

            // create and initialize ListCreationInformation object
            ListCreationInformation listInformation = new ListCreationInformation();
            listInformation.Title = listTitle;
            listInformation.Url = "Lists/Customers";
            listInformation.QuickLaunchOption = QuickLaunchOptions.On;
            listInformation.TemplateType = (int)ListTemplateType.Contacts;

            // Add ListCreationInformation to lists collection and return list object
            List list = clientContext.Web.Lists.Add(listInformation);

            // modify additional list properties and update
            list.OnQuickLaunch = true;
            list.EnableAttachments = false;
            list.Update();

            // send command to server to create list
            clientContext.ExecuteQuery();

            // add an item to the list
            ListItemCreationInformation lici1 = new ListItemCreationInformation();
            var item1 = list.AddItem(lici1);
            item1["Title"] = "Lennon";
            item1["FirstName"] = "John";
            item1.Update();

            // add a second item
            ListItemCreationInformation lici2 = new ListItemCreationInformation();
            var item2 = list.AddItem(lici2);
            item2["Title"] = "McCartney";
            item2["FirstName"] = "Paul";
            item2.Update();

            // send add commands to server
            clientContext.ExecuteQuery();

            // add message to app’s start page
            placeholderMainContent.Text = "New list created";

              }
        }
Exemplo n.º 13
0
        protected TermSet FindTermSet(TermGroup termGroup, TaxonomyTermSetDefinition termSetModel)
        {
            TermSet result = null;

            var context = termGroup.Context;

            context.Load(termGroup.TermSets);
            context.ExecuteQueryWithTrace();

            if (termSetModel.Id.HasValue)
            {
                var scope = new ExceptionHandlingScope(context);
                using (scope.StartScope())
                {
                    using (scope.StartTry())
                    {
                        result = termGroup.TermSets.GetById(termSetModel.Id.Value);
                        context.Load(result);
                    }

                    using (scope.StartCatch())
                    {
                    }
                }
            }
            else if (!string.IsNullOrEmpty(termSetModel.Name))
            {
                var scope = new ExceptionHandlingScope(context);
                using (scope.StartScope())
                {
                    using (scope.StartTry())
                    {
                        result = termGroup.TermSets.GetByName(termSetModel.Name);
                        context.Load(result);
                    }

                    using (scope.StartCatch())
                    {
                    }
                }
            }

            context.ExecuteQueryWithTrace();

            if (result != null &&
                result.ServerObjectIsNull.HasValue &&
                result.ServerObjectIsNull == false)
            {
                context.Load(result);
                //context.Load(result, g => g.Id);
                //context.Load(result, g => g.Name);

                context.ExecuteQueryWithTrace();

                return(result);
            }

            return(null);
        }
        protected TermSet FindTermSet(TermGroup termGroup, TaxonomyTermSetDefinition termSetModel)
        {
            TermSet result = null;

            var context = termGroup.Context;

            context.Load(termGroup.TermSets);
            context.ExecuteQueryWithTrace();

            if (termSetModel.Id.HasValue)
            {
                var scope = new ExceptionHandlingScope(context);
                using (scope.StartScope())
                {
                    using (scope.StartTry())
                    {
                        result = termGroup.TermSets.GetById(termSetModel.Id.Value);
                        context.Load(result);
                    }

                    using (scope.StartCatch())
                    {

                    }
                }
            }
            else if (!string.IsNullOrEmpty(termSetModel.Name))
            {
                var scope = new ExceptionHandlingScope(context);
                using (scope.StartScope())
                {
                    using (scope.StartTry())
                    {
                        result = termGroup.TermSets.GetByName(termSetModel.Name);
                        context.Load(result);
                    }

                    using (scope.StartCatch())
                    {

                    }
                }
            }

            context.ExecuteQueryWithTrace();

            if (result != null && result.ServerObjectIsNull == false)
            {
                context.Load(result);
                //context.Load(result, g => g.Id);
                //context.Load(result, g => g.Name);

                context.ExecuteQueryWithTrace();

                return result;
            }

            return null;
        }
Exemplo n.º 15
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.º 16
0
        static void CreateExpenseBudgetsList()
        {
            string listTitle = "Expense Budgets";
            string listUrl   = "Lists/ExpenseBudgets";

            // delete document library if it already exists
            ExceptionHandlingScope scope = new ExceptionHandlingScope(clientContext);

            using (scope.StartScope()) {
                using (scope.StartTry()) {
                    site.Lists.GetByTitle(listTitle).DeleteObject();
                }
                using (scope.StartCatch()) { }
            }

            ListCreationInformation lci = new ListCreationInformation();

            lci.Title          = listTitle;
            lci.Url            = listUrl;
            lci.TemplateType   = (int)ListTemplateType.GenericList;
            listExpenseBudgets = site.Lists.Add(lci);
            listExpenseBudgets.OnQuickLaunch        = true;
            listExpenseBudgets.EnableFolderCreation = false;
            listExpenseBudgets.Update();

            listExpenseBudgets.DefaultView.Update();
            listExpenseBudgets.Update();
            clientContext.Load(listExpenseBudgets);
            clientContext.Load(listExpenseBudgets.Fields);
            var titleField = listExpenseBudgets.Fields.GetByInternalNameOrTitle("Title");

            titleField.Title = "Expense Budget";
            titleField.Update();
            clientContext.ExecuteQuery();

            listExpenseBudgets.ContentTypesEnabled = true;
            listExpenseBudgets.ContentTypes.AddExistingContentType(ctypeExpenseBudgetItem);
            listExpenseBudgets.Update();
            clientContext.Load(listExpenseBudgets.ContentTypes);
            clientContext.ExecuteQuery();

            ContentType existing = listExpenseBudgets.ContentTypes[0];

            existing.DeleteObject();
            clientContext.ExecuteQuery();

            View viewProducts = listExpenseBudgets.DefaultView;

            viewProducts.ViewFields.Add("ExpenseCategory");
            viewProducts.ViewFields.Add("ExpenseBudgetYear");
            viewProducts.ViewFields.Add("ExpenseBudgetQuarter");
            viewProducts.ViewFields.Add("ExpenseBudgetAmount");
            viewProducts.Update();

            clientContext.ExecuteQuery();

            PopulateExpenseBudgetsList();
        }
Exemplo n.º 17
0
        protected void cmdCreateCustomersList_Click(object sender, EventArgs e)
        {
            SharePointContext spContext = SharePointContextProvider.Current.GetSharePointContext(Context);

            using (ClientContext clientContext = spContext.CreateUserClientContextForSPHost()) {
                clientContext.Load(clientContext.Web);
                clientContext.ExecuteQuery();
                string listTitle = "Customers";

                // delete list if it exists
                ExceptionHandlingScope scope = new ExceptionHandlingScope(clientContext);
                using (scope.StartScope()) {
                    using (scope.StartTry()) {
                        clientContext.Web.Lists.GetByTitle(listTitle).DeleteObject();
                    }
                    using (scope.StartCatch()) { }
                }

                // create and initialize ListCreationInformation object
                ListCreationInformation listInformation = new ListCreationInformation();
                listInformation.Title             = listTitle;
                listInformation.Url               = "Lists/Customers";
                listInformation.QuickLaunchOption = QuickLaunchOptions.On;
                listInformation.TemplateType      = (int)ListTemplateType.Contacts;

                // Add ListCreationInformation to lists collection and return list object
                List list = clientContext.Web.Lists.Add(listInformation);

                // modify additional list properties and update
                list.OnQuickLaunch     = true;
                list.EnableAttachments = false;
                list.Update();

                // send command to server to create list
                clientContext.ExecuteQuery();

                // add an item to the list
                ListItemCreationInformation lici1 = new ListItemCreationInformation();
                var item1 = list.AddItem(lici1);
                item1["Title"]     = "Lennon";
                item1["FirstName"] = "John";
                item1.Update();

                // add a second item
                ListItemCreationInformation lici2 = new ListItemCreationInformation();
                var item2 = list.AddItem(lici2);
                item2["Title"]     = "McCartney";
                item2["FirstName"] = "Paul";
                item2.Update();

                // send add commands to server
                clientContext.ExecuteQuery();

                // add message to app’s start page
                placeholderMainContent.Text = "New list created";
            }
        }
        public IEnumerable <IDictionary <string, byte[]> > DownloadAttachedFileFromListItem(string listName, int itemId)
        {
            var listFiles = new List <IDictionary <string, byte[]> >();
            var dicFiles  = new Dictionary <string, byte[]>();
            var scope     = new ExceptionHandlingScope(_ctx);

            using (scope.StartScope())
            {
                using (scope.StartTry())
                {
                    var oWeb  = _ctx.Web;
                    var oList = oWeb.Lists.GetByTitle(listName);
                    var oItem = oList.GetItemById(itemId);
                    _ctx.Load(oList, l => l.RootFolder.Folders.Where(f => f.Name == "Attachments"));
                    if (oList.RootFolder.Folders.Count > 0)
                    {
                        Folder attachmentFolder = oList.RootFolder.Folders[0];
                        _ctx.Load(attachmentFolder, f => f.Folders);

                        foreach (Folder itemFolder in attachmentFolder.Folders)
                        {
                            FileCollection files = itemFolder.Files;
                            _ctx.Load(files, fls => fls.Include(f => f.ServerRelativeUrl, f => f.Name));

                            if (files.Count > 0)
                            {
                                for (int i = 0; i < files.Count; i++)
                                {
                                    using (var ms = new System.IO.MemoryStream())
                                    {
                                        using (var fileInformation = File.OpenBinaryDirect(_ctx, files[i].ServerRelativeUrl))
                                        {
                                            fileInformation.Stream.CopyTo(ms);
                                            dicFiles.Add(files[i].Name, ms.ToArray());
                                            listFiles.Add(dicFiles);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                using (scope.StartCatch())
                {
                }
            }

            if (scope.HasException)
            {
                string message = string.Format("Um erro ocorreu na lista ({0})\r\nErrorCode:{1}\r\nError:{2}\r\nStackTrace{3}",
                                               listName, scope.ServerErrorCode, scope.ErrorMessage, scope.ServerStackTrace);
                throw new Exception(message);
            }
            _ctx.ExecuteQuery();
            return(listFiles);
        }
Exemplo n.º 19
0
        public SPRemoteEventResult ProcessEvent(SPRemoteEventProperties properties)
        {
            SPRemoteEventResult result = new SPRemoteEventResult();

            using (ClientContext clientContext = TokenHelper.CreateAppEventClientContext(properties, useAppWeb: false)) {
                if (clientContext != null)
                {
                    clientContext.Load(clientContext.Web);
                    string listTitle = "Customers";

                    // delete list if it exists
                    ExceptionHandlingScope scope = new ExceptionHandlingScope(clientContext);
                    using (scope.StartScope()) {
                        using (scope.StartTry()) {
                            clientContext.Web.Lists.GetByTitle(listTitle).DeleteObject();
                        }
                        using (scope.StartCatch()) { }
                    }

                    // create and initialize ListCreationInformation object
                    ListCreationInformation listInformation = new ListCreationInformation();
                    listInformation.Title             = listTitle;
                    listInformation.Url               = "Lists/Customers";
                    listInformation.QuickLaunchOption = QuickLaunchOptions.On;
                    listInformation.TemplateType      = (int)ListTemplateType.Contacts;

                    // Add ListCreationInformation to lists collection and return list object
                    List list = clientContext.Web.Lists.Add(listInformation);

                    // modify additional list properties and update
                    list.OnQuickLaunch     = true;
                    list.EnableAttachments = false;
                    list.Update();

                    // send command to server to create list
                    clientContext.ExecuteQuery();

                    // create a sample item in the list
                    var customer1 = list.AddItem(new ListItemCreationInformation());
                    customer1["FirstName"] = "Mike";
                    customer1["Title"]     = "Fitzmaurice";
                    customer1["Company"]   = "Wingtip Toys";
                    customer1["WorkPhone"] = "(111)111-1111";
                    customer1["HomePhone"] = "(222)222-2222";
                    customer1["Email"]     = "*****@*****.**";
                    customer1.Update();

                    // send command to server to create item
                    clientContext.ExecuteQuery();
                }
            }
            return(result);
        }
Exemplo n.º 20
0
        protected Web GetExistingWeb(Site site, Web parentWeb, string currentWebUrl)
        {
            TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Entering GetExistingWeb()");

            var result = false;
            var srcUrl = currentWebUrl.ToLower().Trim('/').Trim('\\');

            // for self-hosting and '/'
            if (parentWeb.Url.ToLower().Trim('/').Trim('\\').EndsWith(srcUrl))
            {
                return(parentWeb);
            }

            var context = parentWeb.Context;

            Web web = null;

            var scope = new ExceptionHandlingScope(context);

            using (scope.StartScope())
            {
                using (scope.StartTry())
                {
                    web = site.OpenWeb(currentWebUrl);
                }

                using (scope.StartCatch())
                {
                }
            }

            TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "ExecuteQuery()");
            context.ExecuteQueryWithTrace();

            if (!scope.HasException && web != null && web.ServerObjectIsNull == false)
            {
                TraceService.InformationFormat((int)LogEventId.ModelProvisionCoreCall, "Found web with URL: [{0}]", currentWebUrl);

                context.Load(web);

                TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "ExecuteQuery()");
                context.ExecuteQueryWithTrace();

                TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Exciting GetExistingWeb()");

                return(web);
            }

            TraceService.InformationFormat((int)LogEventId.ModelProvisionCoreCall, "Can't find web with URL: [{0}]. Returning NULL.", currentWebUrl);
            TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Exciting GetExistingWeb()");

            return(null);
        }
Exemplo n.º 21
0
        protected Term FindTermInTermSet(TermSet termSet, TaxonomyTermDefinition termModel)
        {
            Term result = null;

            var context = termSet.Context;

            if (termModel.Id.HasValue)
            {
                var scope = new ExceptionHandlingScope(context);
                using (scope.StartScope())
                {
                    using (scope.StartTry())
                    {
                        result = termSet.Terms.GetById(termModel.Id.Value);
                        context.Load(result);
                    }

                    using (scope.StartCatch())
                    {
                    }
                }

                context.ExecuteQueryWithTrace();
            }
            else if (!string.IsNullOrEmpty(termModel.Name))
            {
                var termName = NormalizeTermName(termModel.Name);

                var terms = termSet.GetTerms(new LabelMatchInformation(context)
                {
                    Lcid            = termModel.LCID,
                    TermLabel       = termName,
                    TrimUnavailable = false
                });

                context.Load(terms);
                context.ExecuteQueryWithTrace();

                result = terms.FirstOrDefault();
            }

            if (result != null &&
                result.ServerObjectIsNull.HasValue &&
                result.ServerObjectIsNull == false)
            {
                context.Load(result);
                context.ExecuteQueryWithTrace();

                return(result);
            }

            return(null);
        }
Exemplo n.º 22
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);
                }
            }
        }
    public SPRemoteEventResult ProcessEvent(SPRemoteEventProperties properties) {
     
      SPRemoteEventResult result = new SPRemoteEventResult();
      using (ClientContext clientContext = TokenHelper.CreateAppEventClientContext(properties, useAppWeb: false)) {
        if (clientContext != null) {
          clientContext.Load(clientContext.Web);
          string listTitle = "Customers";

          // delete list if it exists
          ExceptionHandlingScope scope = new ExceptionHandlingScope(clientContext);
          using (scope.StartScope()) {
            using (scope.StartTry()) {
              clientContext.Web.Lists.GetByTitle(listTitle).DeleteObject();
            }
            using (scope.StartCatch()) { }
          }

          // create and initialize ListCreationInformation object
          ListCreationInformation listInformation = new ListCreationInformation();
          listInformation.Title = listTitle;
          listInformation.Url = "Lists/Customers";
          listInformation.QuickLaunchOption = QuickLaunchOptions.On;
          listInformation.TemplateType = (int)ListTemplateType.Contacts;

          // Add ListCreationInformation to lists collection and return list object
          List list = clientContext.Web.Lists.Add(listInformation);

          // modify additional list properties and update
          list.OnQuickLaunch = true;
          list.EnableAttachments = false;
          list.Update();

          // send command to server to create list
          clientContext.ExecuteQuery();

          // create a sample item in the list
          var customer1 = list.AddItem(new ListItemCreationInformation());
          customer1["FirstName"] = "Mike";
          customer1["Title"] = "Fitzmaurice";
          customer1["Company"] = "Wingtip Toys";
          customer1["WorkPhone"] = "(111)111-1111";
          customer1["HomePhone"] = "(222)222-2222";
          customer1["Email"] = "*****@*****.**";
          customer1.Update();

          // send command to server to create item
          clientContext.ExecuteQuery();
        }
      }
      return result;
    }
Exemplo n.º 24
0
        public SPOTermSet CreateTermSet(string name, Guid id, int lcid, string contact, string description, string customSortOrder, bool isAvailableForTagging, string owner, bool isOpenForTermCreation)
        {
            var ctx = _termGroup.Context;
            TermSet termSet = null;
            ExceptionHandlingScope scope = new ExceptionHandlingScope(ctx);
            using (scope.StartScope())
            {
                using (scope.StartTry())
                {
                    termSet = _termGroup.TermSets.GetByName(name);
                    ctx.Load(termSet);
                }
                using (scope.StartCatch())
                {
                }
            }
            ctx.ExecuteQuery();

            if (termSet == null || termSet.ServerObjectIsNull == null || termSet.ServerObjectIsNull.Value)
            {
                if (lcid == 0)
                {
                    lcid = GetWorkingLanguage(_termGroup.TermStore);
                }
                if (string.IsNullOrEmpty(owner))
                {

                    var web = SPOSiteContext.CurrentSiteContext.Context.Web;
                    ctx.Load(web, w => w.CurrentUser);
                    ctx.ExecuteQuery();
                    owner = web.CurrentUser.LoginName;
                }

                termSet = _termGroup.CreateTermSet(name, id, lcid);

                termSet.Contact = contact;
                termSet.Description = description;
                termSet.CustomSortOrder = customSortOrder;
                termSet.IsAvailableForTagging = isAvailableForTagging;
                termSet.Owner = owner;
                termSet.IsOpenForTermCreation = isOpenForTermCreation;

                ctx.Load(termSet);
                ctx.ExecuteQuery();
                return new SPOTermSet(termSet);
            }
            else
            {
                throw new Exception("The specified term set already exists.");
            }
        }
        public SPOTermSet CreateTermSet(string name, Guid id, int lcid, string contact, string description, string customSortOrder, bool isAvailableForTagging, string owner, bool isOpenForTermCreation)
        {
            var     ctx     = _termGroup.Context;
            TermSet termSet = null;
            ExceptionHandlingScope scope = new ExceptionHandlingScope(ctx);

            using (scope.StartScope())
            {
                using (scope.StartTry())
                {
                    termSet = _termGroup.TermSets.GetByName(name);
                    ctx.Load(termSet);
                }
                using (scope.StartCatch())
                {
                }
            }
            ctx.ExecuteQuery();

            if (termSet == null || termSet.ServerObjectIsNull == null || termSet.ServerObjectIsNull.Value)
            {
                if (lcid == 0)
                {
                    lcid = GetWorkingLanguage(_termGroup.TermStore);
                }
                if (string.IsNullOrEmpty(owner))
                {
                    var web = SPOSiteContext.CurrentSiteContext.Context.Web;
                    ctx.Load(web, w => w.CurrentUser);
                    ctx.ExecuteQuery();
                    owner = web.CurrentUser.LoginName;
                }

                termSet = _termGroup.CreateTermSet(name, id, lcid);

                termSet.Contact               = contact;
                termSet.Description           = description;
                termSet.CustomSortOrder       = customSortOrder;
                termSet.IsAvailableForTagging = isAvailableForTagging;
                termSet.Owner = owner;
                termSet.IsOpenForTermCreation = isOpenForTermCreation;

                ctx.Load(termSet);
                ctx.ExecuteQuery();
                return(new SPOTermSet(termSet));
            }
            else
            {
                throw new Exception("The specified term set already exists.");
            }
        }
Exemplo n.º 26
0
        public static Term LookupTerm(SiteModelHost currentSiteModelHost, TermStore termStore, TaxonomyFieldDefinition termModel)
        {
            var  context = currentSiteModelHost.HostClientContext;
            Term result  = null;

            if (termModel.TermId.HasValue)
            {
                var scope = new ExceptionHandlingScope(context);
                using (scope.StartScope())
                {
                    using (scope.StartTry())
                    {
                        result = termStore.GetTerm(termModel.TermId.Value);
                        context.Load(result);
                    }

                    using (scope.StartCatch())
                    {
                    }
                }

                context.ExecuteQueryWithTrace();
            }
            else if (!string.IsNullOrEmpty(termModel.TermName))
            {
                var terms = termStore.GetTerms(new LabelMatchInformation(context)
                {
                    Lcid            = termModel.TermLCID,
                    TermLabel       = termModel.TermName,
                    TrimUnavailable = false
                });

                context.Load(terms);
                context.ExecuteQueryWithTrace();

                result = terms.FirstOrDefault();
            }

            if (result != null && result.ServerObjectIsNull == false)
            {
                context.Load(result);
                context.ExecuteQueryWithTrace();

                return(result);
            }

            return(null);
        }
Exemplo n.º 27
0
        public void EnsureConfigurationListInTenant(string hostWebUrl)
        {
            //get the base tenant admin urls
            var tenantStr = hostWebUrl.ToLower().Replace("-my", "").Substring(8); //remove my if it exists...

            tenantStr = tenantStr.Substring(0, tenantStr.IndexOf("."));

            //create site collection using the Tenant object
            var    tenantRootUri = new Uri(String.Format("https://{0}.sharepoint.com", tenantStr));
            string realm         = TokenHelper.GetRealmFromTargetUrl(tenantRootUri);
            var    token         = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, tenantRootUri.Authority, realm).AccessToken;

            using (var adminContext = TokenHelper.GetClientContextWithAccessToken(tenantRootUri.ToString(), token))
            {
                //Check if config list exists and if not, create the list and SubSiteAppUrl item.

                //Using ExceptionHandlingScope for this so that only one call is made to the server instead of multiple calls.
                ExceptionHandlingScope scope = new ExceptionHandlingScope(adminContext);

                using (scope.StartScope())
                {
                    using (scope.StartTry())
                    {
                        List configList = adminContext.Web.Lists.GetByTitle(ConfigList);

                        configList.Update();
                    }

                    using (scope.StartCatch())
                    {
                        ListCreationInformation listCreationInfo = new ListCreationInformation();
                        listCreationInfo.Title        = ConfigList;
                        listCreationInfo.TemplateType = (int)ListTemplateType.GenericList;
                        List  configList = adminContext.Web.Lists.Add(listCreationInfo);
                        Field oField     = configList.Fields.AddFieldAsXml("<Field DisplayName='Value' Type='Text' />", true, AddFieldOptions.DefaultValue);

                        ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
                        ListItem item = configList.AddItem(itemCreateInfo);
                        item["Title"] = "SubSiteAppUrl";
                        item["Value"] = "https://localhost:44323";
                        item.Update();
                    }
                }

                adminContext.ExecuteQuery();
            }
        }
Exemplo n.º 28
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);
                }
            }
        }
Exemplo n.º 29
0
        private static string LoadList(ClientContext context, List list)
        {
            ExceptionHandlingScope scope = new ExceptionHandlingScope(context);

            using (scope.StartScope())
            {
                using (scope.StartTry())
                {
                    context.Load(list);
                    context.Load(list, l => l.ValidationFormula,
                                 l => l.ValidationMessage,
                                 l => l.OnQuickLaunch,
                                 //l => l.SchemaXml,
                                 l => l.RootFolder,
                                 l => l.IsSiteAssetsLibrary,
                                 l => l.HasUniqueRoleAssignments,
                                 l => l.DataSource,
                                 l => l.Id,
                                 l => l.ItemCount,
                                 l => l.DefaultDisplayFormUrl,
                                 l => l.DefaultViewUrl);
                }
                using (scope.StartCatch())
                {
                    context.Load(list);
                    context.Load(list, l => l.ValidationFormula,
                                 l => l.ValidationMessage,
                                 l => l.OnQuickLaunch,
                                 //l => l.SchemaXml,
                                 //l => l.RootFolder,
                                 //l => l.IsSiteAssetsLibrary,
                                 l => l.HasUniqueRoleAssignments,
                                 l => l.DataSource,
                                 l => l.Id,
                                 l => l.ItemCount);
                }
            }
            context.ExecuteQuery();
            if (scope.HasException)
            {
                logger.WarnFormat("Has Exception: {0}", scope.ErrorMessage);
                return(scope.ErrorMessage);
            }
            logger.Info("get list info successfully");
            return(null);
        }
Exemplo n.º 30
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();
        }
        /// <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.º 32
0
        private static List LoadCurrentList(Web web, ListDefinition listModel)
        {
            var context = web.Context;

            List currentList = null;

#pragma warning disable 618
            var listUrl = UrlUtility.CombineUrl(web.ServerRelativeUrl, listModel.GetListUrl());
#pragma warning restore 618

            Folder folder = null;

            var scope = new ExceptionHandlingScope(context);

            using (scope.StartScope())
            {
                using (scope.StartTry())
                {
                    folder = web.GetFolderByServerRelativeUrl(listUrl);
                    context.Load(folder);
                }

                using (scope.StartCatch())
                {
                }
            }

            context.ExecuteQueryWithTrace();

            if (!scope.HasException && folder != null && folder.ServerObjectIsNull != true)
            {
                folder = web.GetFolderByServerRelativeUrl(listUrl);
                context.Load(folder.Properties);
                context.ExecuteQueryWithTrace();

                var listId = new Guid(folder.Properties["vti_listname"].ToString());
                var list   = web.Lists.GetById(listId);

                context.Load(list);
                context.ExecuteQueryWithTrace();

                currentList = list;
            }

            return(currentList);
        }
Exemplo n.º 33
0
        public static TermSet LookupTermSet(ClientRuntimeContext context, TermStore termStore,
                                            string termSetName, Guid?termSetId, int termSetLCID)
        {
            var storeContext = context;

            if (!string.IsNullOrEmpty(termSetName))
            {
                var termSets = termStore.GetTermSetsByName(termSetName, termSetLCID);

                storeContext.Load(termSets);
                storeContext.ExecuteQueryWithTrace();

                return(termSets.FirstOrDefault());
            }

            if (termSetId.HasGuidValue())
            {
                TermSet termSet = null;

                var scope = new ExceptionHandlingScope(storeContext);
                using (scope.StartScope())
                {
                    using (scope.StartTry())
                    {
                        termSet = termStore.GetTermSet(termSetId.Value);
                        storeContext.Load(termSet);
                    }

                    using (scope.StartCatch())
                    {
                    }
                }

                storeContext.ExecuteQueryWithTrace();

                if (termSet != null && termSet.ServerObjectIsNull == false)
                {
                    storeContext.Load(termSet, g => g.Id);
                    storeContext.ExecuteQueryWithTrace();

                    return(termSet);
                }
            }

            return(null);
        }
Exemplo n.º 34
0
        public static TermSet LookupTermSet(SiteModelHost currentSiteModelHost, TermStore termStore, TaxonomyFieldDefinition taxFieldModel)
        {
            var storeContext = currentSiteModelHost.HostClientContext;

            if (!string.IsNullOrEmpty(taxFieldModel.TermSetName))
            {
                var termSets = termStore.GetTermSetsByName(taxFieldModel.TermSetName, taxFieldModel.TermSetLCID);

                storeContext.Load(termSets);
                storeContext.ExecuteQueryWithTrace();

                return(termSets.FirstOrDefault());
            }

            if (taxFieldModel.TermSetId.HasValue)
            {
                TermSet termSet = null;

                var scope = new ExceptionHandlingScope(storeContext);
                using (scope.StartScope())
                {
                    using (scope.StartTry())
                    {
                        termSet = termStore.GetTermSet(taxFieldModel.TermSetId.Value);
                        storeContext.Load(termSet);
                    }

                    using (scope.StartCatch())
                    {
                    }
                }

                storeContext.ExecuteQueryWithTrace();

                if (termSet != null && termSet.ServerObjectIsNull == false)
                {
                    storeContext.Load(termSet, g => g.Id);
                    storeContext.ExecuteQueryWithTrace();

                    return(termSet);
                }
            }

            return(null);
        }
Exemplo n.º 35
0
        protected Field FindExistingWebField(WebModelHost siteModelHost, FieldDefinition fieldDefinition)
        {
            var id = fieldDefinition.Id;
            var rootWeb = siteModelHost.HostWeb;

            TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "FindExistingSiteField with Id: [{0}]", id);

            var context = rootWeb.Context;
            var scope = new ExceptionHandlingScope(context);

            Field field = null;

            using (scope.StartScope())
            {
                using (scope.StartTry())
                {
                    rootWeb.Fields.GetById(id);
                }

                using (scope.StartCatch())
                {

                }
            }

            TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "ExecuteQuery()");
            context.ExecuteQueryWithTrace();

            if (!scope.HasException)
            {
                field = rootWeb.Fields.GetById(id);
                context.Load(field);

                TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Found site field with Id: [{0}]", id);
                TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "ExecuteQuery()");

                context.ExecuteQueryWithTrace();
            }
            else
            {
                TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Cannot find site field with Id: [{0}]", id);
            }

            return field;
        }
Exemplo n.º 36
0
        private Field DeployWebField(WebModelHost webModelHost, FieldDefinition fieldDefinition)
        {
            var id  = fieldDefinition.Id;
            var web = webModelHost.HostWeb;

            TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "FindExistingWebField with Id: [{0}]", id);

            var context = web.Context;
            var scope   = new ExceptionHandlingScope(context);

            Field field = null;

            using (scope.StartScope())
            {
                using (scope.StartTry())
                {
                    web.Fields.GetById(id);
                }

                using (scope.StartCatch())
                {
                }
            }

            TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "ExecuteQuery()");
            context.ExecuteQueryWithTrace();

            if (!scope.HasException)
            {
                field = web.Fields.GetById(id);
                context.Load(field);
                PreloadProperties(field);

                TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Found site field with Id: [{0}]", id);
                TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "ExecuteQuery()");

                context.ExecuteQueryWithTrace();
            }
            else
            {
                TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Cannot find site field with Id: [{0}]", id);
            }

            return(EnsureField(context, field, web.Fields, fieldDefinition));
        }
Exemplo n.º 37
0
 public void DeleteAllTopNavNodes()
 {
     // delete all existing nodes
     for (int index = (topNavNodes.Count - 1); index >= 0; index--)
     {
         ExceptionHandlingScope scope = new ExceptionHandlingScope(clientContext);
         using (scope.StartScope()) {
             using (scope.StartTry()) {
                 topNavNodes[index].DeleteObject();
             }
             using (scope.StartCatch()) {
             }
         }
         clientContext.ExecuteQuery();
     }
     clientContext.Load(topNavNodes);
     clientContext.ExecuteQuery();
 }
Exemplo n.º 38
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.º 39
0
        static void CreateCustomersList()
        {
            string listTitle = "Customers";
              string listUrl = "Lists/Customers";

              // delete document library if it already exists
              ExceptionHandlingScope scope = new ExceptionHandlingScope(clientContext);
              using (scope.StartScope()) {
            using (scope.StartTry()) {
              site.Lists.GetByTitle(listTitle).DeleteObject();
            }
            using (scope.StartCatch()) { }
              }

              ListCreationInformation lci = new ListCreationInformation();
              lci.Title = listTitle;
              lci.Url = listUrl;
              lci.TemplateType = (int)ListTemplateType.Contacts;
              listCustomers = site.Lists.Add(lci);
              listCustomers.OnQuickLaunch = true;
              listCustomers.Update();

              // attach JSLink script to default view for client-side rendering
              listCustomers.DefaultView.JSLink = AppRootFolderRelativeUrl + "scripts/CustomersListCSR.js";
              listCustomers.DefaultView.Update();
              listCustomers.Update();
              clientContext.Load(listCustomers);
              clientContext.Load(listCustomers.Fields);
              clientContext.ExecuteQuery();

              string[] UnwantedFields = { "FullName", "JobTitle", "CellPhone", "WorkFax", "WorkCountry", "WebPage", "Comments" };
              foreach (string UnwantedField in UnwantedFields) {
            listCustomers.Fields.GetByInternalNameOrTitle(UnwantedField).DeleteObject();
              }
              clientContext.ExecuteQuery();

              // add some sample data to make things more interesting
              PopulateCustomersList();
        }
Exemplo n.º 40
0
        protected Term FindTermInTermSet(TermSet termSet, TaxonomyTermDefinition termModel)
        {
            Term result = null;

            var context = termSet.Context;

            if (termModel.Id.HasValue)
            {
                var scope = new ExceptionHandlingScope(context);
                using (scope.StartScope())
                {
                    using (scope.StartTry())
                    {
                        result = termSet.Terms.GetById(termModel.Id.Value);
                        context.Load(result);
                    }

                    using (scope.StartCatch())
                    {

                    }
                }

                context.ExecuteQueryWithTrace();
            }
            else if (!string.IsNullOrEmpty(termModel.Name))
            {
                var terms = termSet.GetTerms(new LabelMatchInformation(context)
                {
                    Lcid = termModel.LCID,
                    TermLabel = termModel.Name,
                    TrimUnavailable = false
                });

                context.Load(terms);
                context.ExecuteQueryWithTrace();

                result = terms.FirstOrDefault();
            }

            if (result != null && result.ServerObjectIsNull == false)
            {
                context.Load(result);
                context.ExecuteQueryWithTrace();

                return result;
            }

            return null;
        }
Exemplo n.º 41
0
 static void DeleteAllTopNavNodes() {
   // delete all existing nodes
   for (int index = (TopNavNodes.Count - 1); index >= 0; index--) {
     ExceptionHandlingScope scope = new ExceptionHandlingScope(clientContext);
     using (scope.StartScope()) {
       using (scope.StartTry()) {
         TopNavNodes[index].DeleteObject();
       }
       using (scope.StartCatch()) {
       }
     }
     clientContext.ExecuteQuery();
   }
   clientContext.Load(TopNavNodes);
   clientContext.ExecuteQuery();
 }
Exemplo n.º 42
0
        /// <summary>
        /// Gets a Taxonomy Term by Name
        /// </summary>
        /// <param name="termSetId"></param>
        /// <param name="term"></param>
        /// <param name="clientContext"></param>
        /// <returns></returns>
        public static Term GetTermByName(this Site site, Guid termSetId, string term)
        {
            if (string.IsNullOrEmpty(term))
                throw new ArgumentNullException("term");

            TermCollection termMatches = null;
            ExceptionHandlingScope scope = new ExceptionHandlingScope(site.Context);

            string termId = string.Empty;
            TaxonomySession tSession = TaxonomySession.GetTaxonomySession(site.Context);
            TermStore ts = tSession.GetDefaultSiteCollectionTermStore();
            TermSet tset = ts.GetTermSet(termSetId);

            var lmi = new LabelMatchInformation(site.Context);

            lmi.Lcid = 1033;
            lmi.TrimUnavailable = true;
            lmi.TermLabel = term;

            termMatches = tset.GetTerms(lmi);
            site.Context.Load(tSession);
            site.Context.Load(ts);
            site.Context.Load(tset);
            site.Context.Load(termMatches);

            site.Context.ExecuteQuery();

            if (termMatches.AreItemsAvailable)
            {
                return termMatches.FirstOrDefault();
            }
            else
            {
                return null;
            }
        }
Exemplo n.º 43
0
        private Field DeployListField(ListModelHost modelHost, FieldDefinition fieldModel)
        {
            TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Deploying list field");

            var list = modelHost.HostList;
            var context = list.Context;

            var scope = new ExceptionHandlingScope(context);

            Field field;

            using (scope.StartScope())
            {
                using (scope.StartTry())
                {
                    field = list.Fields.GetById(fieldModel.Id);
                    context.Load(field);
                }

                using (scope.StartCatch())
                {

                }
            }

            TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "ExecuteQuery()");
            context.ExecuteQueryWithTrace();

            if (!scope.HasException)
            {
                field = list.Fields.GetById(fieldModel.Id);
                context.Load(field);

                TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Found site list with Id: [{0}]", fieldModel.Id);
                TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "ExecuteQuery()");

                context.ExecuteQueryWithTrace();

                return EnsureField(context, field, list.Fields, fieldModel);
            }

            TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Cannot find list field with Id: [{0}]", fieldModel.Id);
            return EnsureField(context, null, list.Fields, fieldModel);
        }
Exemplo n.º 44
0
        protected Field FindExistingListField(List list, FieldDefinition fieldModel)
        {
            TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "FindListField with Id: [{0}]", fieldModel.Id);

            var context = list.Context;

            Field field;

            var scope = new ExceptionHandlingScope(context);

            using (scope.StartScope())
            {
                using (scope.StartTry())
                {
                    field = list.Fields.GetById(fieldModel.Id);
                    context.Load(field);
                }
                using (scope.StartCatch())
                {
                    field = null;
                    //context.Load(field);
                }
            }

            context.ExecuteQueryWithTrace();

            if (!scope.HasException)
            {
                field = list.Fields.GetById(fieldModel.Id);
                context.Load(field);

                TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Found list field with Id: [{0}]", fieldModel.Id);
                TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "ExecuteQuery()");

                context.ExecuteQueryWithTrace();
            }
            else
            {
                TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Cannot find list field with Id: [{0}]", fieldModel.Id);
            }

            return field;
        }
Exemplo n.º 45
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();
        }
        private Web Setup()
        {
            using (var ctx = TestCommon.CreateClientContext())
            {
                ExceptionHandlingScope scope = new ExceptionHandlingScope(ctx);

                Web web;
                Site site;
                site = ctx.Site;
                web = ctx.Site.RootWeb;
                if (!site.IsFeatureActive(publishingSiteFeatureId))
                {
                    site.ActivateFeature(publishingSiteFeatureId);
                    deactivateSiteFeatureOnTeardown = true;
                }
                if (!web.IsFeatureActive(publishingWebFeatureId))
                {
                    site.RootWeb.ActivateFeature(publishingWebFeatureId);
                    deactivateWebFeatureOnTeardown = true;
                }
                return web;

            }
        }
Exemplo n.º 47
0
        private object ExecuteObjectSearch(string serverRelativePath, Web web)
        {
            var ctx = web.Context;
            File file;
            Folder folder;
            var scope = new ExceptionHandlingScope(ctx);
            var tryFileFirst = serverRelativePath.Split(PathSeparator.ToCharArray()).Last().Contains(".");

            if (tryFileFirst)
            {
                using (scope.StartScope())
                {
                    using (scope.StartTry())
                    {
                        file = web.GetFileByServerRelativeUrl(serverRelativePath);
                        ctx.Load(file);
                    }
                    using (scope.StartCatch())
                    {
                        folder = web.GetFolderByServerRelativeUrl(serverRelativePath);
                        ctx.Load(folder);
                    }
                }
            }
            else
            {
                using (scope.StartScope())
                {
                    using (scope.StartTry())
                    {
                        folder = web.GetFolderByServerRelativeUrl(serverRelativePath);
                        ctx.Load(folder);
                    }
                    using (scope.StartCatch())
                    {
                        file = web.GetFileByServerRelativeUrl(serverRelativePath);
                        ctx.Load(file);
                    }
                }
            }

            try
            {
                ctx.ExecuteQueryRetry();
            }
            catch (Exception e)
            {
                return e;
            }

            //Check if we got data
            if (IsPropertyAvailable(file, "Name"))
            {
                return file;
            }
            else if (IsPropertyAvailable(folder, "Name"))
            {
                return folder;
            }

            return null;
        }
Exemplo n.º 48
0
        public void EnsureConfigurationListInTenant(string hostWebUrl)
        {
            //get the base tenant admin urls
            var tenantStr = hostWebUrl.ToLower().Replace("-my", "").Substring(8); //remove my if it exists...
            tenantStr = tenantStr.Substring(0, tenantStr.IndexOf("."));

            //create site collection using the Tenant object
            var tenantRootUri = new Uri(String.Format("https://{0}.sharepoint.com", tenantStr));
            string realm = TokenHelper.GetRealmFromTargetUrl(tenantRootUri);
            var token = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, tenantRootUri.Authority, realm).AccessToken;
            using (var adminContext = TokenHelper.GetClientContextWithAccessToken(tenantRootUri.ToString(), token))
            {
                //Check if config list exists and if not, create the list and SubSiteAppUrl item.
                
                //Using ExceptionHandlingScope for this so that only one call is made to the server instead of multiple calls. 
                ExceptionHandlingScope scope = new ExceptionHandlingScope(adminContext);

                using (scope.StartScope())
                {
                    using (scope.StartTry())
                    {
                        List configList = adminContext.Web.Lists.GetByTitle(ConfigList);

                        configList.Update();
                    }

                    using (scope.StartCatch())
                    {
                        ListCreationInformation listCreationInfo = new ListCreationInformation();
                        listCreationInfo.Title = ConfigList;
                        listCreationInfo.TemplateType = (int)ListTemplateType.GenericList;
                        List configList = adminContext.Web.Lists.Add(listCreationInfo);
                        Field oField = configList.Fields.AddFieldAsXml("<Field DisplayName='Value' Type='Text' />", true, AddFieldOptions.DefaultValue);
                        
                        ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
                        ListItem item = configList.AddItem(itemCreateInfo);
                        item["Title"] = "SubSiteAppUrl";
                        item["Value"] = "https://localhost:44323";
                        item.Update();
                    }
                }

                adminContext.ExecuteQuery();
            }
        }
Exemplo n.º 49
0
        protected Web GetExistingWeb(Site site, Web parentWeb, string currentWebUrl)
        {
            TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Entering GetExistingWeb()");

            var result = false;
            var srcUrl = currentWebUrl.ToLower().Trim('/').Trim('\\');

            // for self-hosting and '/'
            if (parentWeb.Url.ToLower().Trim('/').Trim('\\').EndsWith(srcUrl))
                return parentWeb;

            var context = parentWeb.Context;

            Web web = null;

            var scope = new ExceptionHandlingScope(context);

            using (scope.StartScope())
            {
                using (scope.StartTry())
                {
                    web = site.OpenWeb(currentWebUrl);
                }

                using (scope.StartCatch())
                {

                }
            }

            TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "ExecuteQuery()");
            context.ExecuteQueryWithTrace();

            if (!scope.HasException && web != null && web.ServerObjectIsNull == false)
            {
                TraceService.InformationFormat((int)LogEventId.ModelProvisionCoreCall, "Found web with URL: [{0}]", currentWebUrl);

                context.Load(web);

                TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "ExecuteQuery()");
                context.ExecuteQueryWithTrace();

                TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Exciting GetExistingWeb()");

                return web;
            }

            TraceService.InformationFormat((int)LogEventId.ModelProvisionCoreCall, "Can't find web with URL: [{0}]. Returning NULL.", currentWebUrl);
            TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Exciting GetExistingWeb()");

            return null;
        }
Exemplo n.º 50
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.º 51
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.º 52
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;
        }
  static public void CreateAnnouncementsList(ClientContext clientContext) {

    string listTitle = "Announcements";

    // delete list if it exists
    ExceptionHandlingScope scope = new ExceptionHandlingScope(clientContext);
    using (scope.StartScope()) {
      using (scope.StartTry()) {
        clientContext.Web.Lists.GetByTitle(listTitle).DeleteObject();
      }
      using (scope.StartCatch()) { }
    }

    // create and initialize ListCreationInformation object
    ListCreationInformation listInformation = new ListCreationInformation();
    listInformation.Title = listTitle;
    listInformation.Url = "Lists/Announcements";
    listInformation.QuickLaunchOption = QuickLaunchOptions.On;
    listInformation.TemplateType = (int)ListTemplateType.Announcements;

    // Add ListCreationInformation to lists collection and return list object
    List list = clientContext.Web.Lists.Add(listInformation);

    // modify additional list properties and update
    list.OnQuickLaunch = true;
    list.EnableAttachments = false;
    list.Update();

    // send command to server to create list
    clientContext.ExecuteQuery();

    clientContext.Load(list);
    clientContext.ExecuteQuery();

    string urlEventReceiver = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) +
                              @"/Services/AnnouncementsEventReceiver.svc";

    EventReceiverDefinitionCreationInformation erci1 = new EventReceiverDefinitionCreationInformation();
    erci1.ReceiverName = "ItemAdding";
    erci1.EventType = EventReceiverType.ItemAdding;
    erci1.ReceiverUrl = urlEventReceiver;
    erci1.SequenceNumber = 1000;
    EventReceiverDefinition er1 = list.EventReceivers.Add(erci1);
    er1.Update();

    EventReceiverDefinitionCreationInformation erci2 = new EventReceiverDefinitionCreationInformation();
    erci2.ReceiverName = "ItemUpdating";
    erci2.EventType = EventReceiverType.ItemUpdating;
    erci2.ReceiverUrl = urlEventReceiver;
    erci2.SequenceNumber = 1000;
    EventReceiverDefinition er2 = list.EventReceivers.Add(erci2);
    er2.Update();

    clientContext.ExecuteQuery();

    ListItemCreationInformation lici = new ListItemCreationInformation();

    var item1 = list.AddItem(lici);
    item1["Title"] = "SharePoint introduces new app model";
    item1["Body"] = "<div>Developers wonder what happened to solutions.</div>";
    item1["Expires"] = DateTime.Today.AddYears(10);
    item1.Update();

    var item2 = list.AddItem(lici);
    item2["Title"] = "All SharePoint developers must now learn JavaScript";
    item2["Body"] = "<div>Some developers are more excited than others.</div>";
    item2["Expires"] = DateTime.Today.AddYears(1);
    item2.Update();

    var item3 = list.AddItem(lici);
    item3["Title"] = "CSOM programming is super fun";
    item3["Body"] = "<div>Just ask my mom.</div>";
    item3["Expires"] = DateTime.Today.AddDays(7);
    item3.Update();

    clientContext.ExecuteQuery();



  }
Exemplo n.º 54
0
        public static Term LookupTerm(ClientContext clientContext, TermStore termStore,
            TermSet termSet,
            TaxonomyFieldDefinition termModel)
        {
            var context = clientContext;
            var site = clientContext.Site;

            Term result = null;

            TermGroup currenGroup = null;

            var termGroupName = termModel.TermGroupName;
            var termGroupId = termModel.TermGroupId;
            var isSiteCollectionGroup = termModel.IsSiteCollectionGroup;

            if (!string.IsNullOrEmpty(termGroupName))
            {
                currenGroup = termStore.Groups.GetByName(termGroupName);

                context.Load(currenGroup);
                context.ExecuteQueryWithTrace();
            }
            else if (termGroupId != null && termGroupId.HasGuidValue())
            {
                currenGroup = termStore.Groups.GetById(termGroupId.Value);

                context.Load(currenGroup);
                context.ExecuteQueryWithTrace();
            }
            else if (isSiteCollectionGroup == true)
            {
                currenGroup = termStore.GetSiteCollectionGroup(site, false);

                context.Load(currenGroup);
                context.ExecuteQueryWithTrace();
            }

            if (currenGroup != null)
            {
                if (termModel.TermId.HasValue)
                {
                    // by ID, the only one match

                    var scope = new ExceptionHandlingScope(context);
                    using (scope.StartScope())
                    {
                        using (scope.StartTry())
                        {
                            result = termStore.GetTerm(termModel.TermId.Value);
                            context.Load(result);
                        }

                        using (scope.StartCatch())
                        {

                        }
                    }

                    context.ExecuteQueryWithTrace();
                }
                else if (!string.IsNullOrEmpty(termModel.TermName))
                {
                    var terms = termStore.GetTerms(new LabelMatchInformation(context)
                    {
                        Lcid = termModel.TermLCID,
                        TermLabel = termModel.TermName,
                        TrimUnavailable = false
                    });

                    context.Load(terms, t => t.Include(
                                                i => i.Id,
                                                i => i.Name,
                                                i => i.TermSet,
                                                i => i.TermSet.Group,
                                                i => i.TermSet.Group.Name
                                                ));
                    context.ExecuteQueryWithTrace();

                    result = terms.FirstOrDefault(t => t.TermSet.Group.Name == currenGroup.Name);

                    if ( (result == null) && (termSet != null ))
                        // sometimes label match information does not return the term 
                    {
                        var allTerms = termSet.GetAllTerms();
                        context.Load(allTerms, t => t.Include(
                                                    i => i.Id,
                                                    i => i.Name,
                                                    i => i.TermSet,
                                                    i => i.TermSet.Group,
                                                    i => i.TermSet.Group.Name,
                                                    i => i.Labels
                                                    ));
                        context.ExecuteQueryWithTrace();

                        result = allTerms.FirstOrDefault(t => (t.TermSet.Group.Name == currenGroup.Name) && (t.Labels.Any(l=>l.Value == termModel.TermName && l.Language == termModel.TermLCID)));
                    }
                }
            }

            else
            {

                if (termModel.TermId.HasValue)
                {
                    var scope = new ExceptionHandlingScope(context);
                    using (scope.StartScope())
                    {
                        using (scope.StartTry())
                        {
                            result = termStore.GetTerm(termModel.TermId.Value);
                            context.Load(result);
                        }

                        using (scope.StartCatch())
                        {

                        }
                    }

                    context.ExecuteQueryWithTrace();
                }
                else if (!string.IsNullOrEmpty(termModel.TermName))
                {
                    var terms = termStore.GetTerms(new LabelMatchInformation(context)
                    {
                        Lcid = termModel.TermLCID,
                        TermLabel = termModel.TermName,
                        TrimUnavailable = false
                    });

                    context.Load(terms);
                    context.ExecuteQueryWithTrace();

                    result = terms.FirstOrDefault();

                    if ((result == null) && (termSet != null))
                        // sometimes label match information does not return the termset 
                    {
                        var allTerms = termSet.GetAllTerms();
                        context.Load(allTerms, t => t.Include(
                            i => i.Id,
                            i => i.Name,
                            i => i.TermSet,
                            i => i.TermSet.Group,
                            i => i.TermSet.Group.Name,
                            i => i.Labels
                            ));
                        context.ExecuteQueryWithTrace();

                        result =
                            allTerms.FirstOrDefault(
                                t => (t.Labels.Any(l=>l.Value == termModel.TermName && l.Language == termModel.TermLCID)));

                    }

                }
                }

            if (result != null && result.ServerObjectIsNull == false)
            {
                context.Load(result);
                context.ExecuteQueryWithTrace();

                return result;
            }

            return null;
        }
Exemplo n.º 55
0
        public SPOTermGroup CreateGroup(string name, Guid id, string description)
        {
            var ctx = _termStore.Context;
            TermGroup group = null;
            ExceptionHandlingScope scope = new ExceptionHandlingScope(ctx);
            using (scope.StartScope())
            {
                using (scope.StartTry())
                {
                    group = _termStore.Groups.GetByName(name);
                    ctx.Load(group);
                }
                using (scope.StartCatch())
                {
                }
            }
            ctx.ExecuteQuery();

            if (group == null || group.ServerObjectIsNull == null || group.ServerObjectIsNull.Value)
            {
                group = _termStore.CreateGroup(name, id);
                group.Description = description;
                ctx.ExecuteQuery();
                ctx.Load(group);
                ctx.ExecuteQuery();
                return new SPOTermGroup(group);
            }
            else
            {
                throw new Exception("The specified term group already exists.");
            }
        }
Exemplo n.º 56
0
        public static TermSet LookupTermSet(ClientRuntimeContext context, TermStore termStore,
            Site site,
            string termGroupName, Guid? termGroupId, bool? isSiteCollectionGroup,
            string termSetName, Guid? termSetId, int termSetLCID)
        {
            var storeContext = context;

            TermGroup currenGroup = null;

            if (!string.IsNullOrEmpty(termGroupName))
            {
                currenGroup = termStore.Groups.GetByName(termGroupName);

                storeContext.Load(currenGroup);
                storeContext.ExecuteQueryWithTrace();
            }
            else if (termGroupId != null && termGroupId.HasGuidValue())
            {
                currenGroup = termStore.Groups.GetById(termGroupId.Value);

                storeContext.Load(currenGroup);
                storeContext.ExecuteQueryWithTrace();
            }
            else if (isSiteCollectionGroup == true)
            {
                currenGroup = termStore.GetSiteCollectionGroup(site, false);

                storeContext.Load(currenGroup);
                storeContext.ExecuteQueryWithTrace();
            }

            if (!string.IsNullOrEmpty(termSetName))
            {
                if (currenGroup != null && (currenGroup.ServerObjectIsNull == false))
                {
                    TermSet termSet = null;

                    var scope = new ExceptionHandlingScope(storeContext);
                    using (scope.StartScope())
                    {
                        using (scope.StartTry())
                        {
                            termSet = currenGroup.TermSets.GetByName(termSetName);
                            storeContext.Load(termSet);
                        }

                        using (scope.StartCatch())
                        {

                        }
                    }

                    storeContext.ExecuteQueryWithTrace();

                    if (termSet != null && termSet.ServerObjectIsNull == false)
                    {
                        storeContext.Load(termSet, g => g.Id);
                        storeContext.ExecuteQueryWithTrace();

                        return termSet;
                    }
                }
                else
                {
                    var termSets = termStore.GetTermSetsByName(termSetName, termSetLCID);

                    storeContext.Load(termSets);
                    storeContext.ExecuteQueryWithTrace();

                    return termSets.FirstOrDefault();
                }
            }

            if (termSetId.HasGuidValue())
            {
                if (currenGroup != null && (currenGroup.ServerObjectIsNull == false))
                {
                    TermSet termSet = null;

                    var scope = new ExceptionHandlingScope(storeContext);
                    using (scope.StartScope())
                    {
                        using (scope.StartTry())
                        {
                            termSet = currenGroup.TermSets.GetById(termSetId.Value);
                            storeContext.Load(termSet);
                        }

                        using (scope.StartCatch())
                        {

                        }
                    }

                    storeContext.ExecuteQueryWithTrace();

                    if (termSet != null && termSet.ServerObjectIsNull == false)
                    {
                        storeContext.Load(termSet, g => g.Id);
                        storeContext.ExecuteQueryWithTrace();

                        return termSet;
                    }
                }
                else
                {
                    TermSet termSet = null;

                    var scope = new ExceptionHandlingScope(storeContext);
                    using (scope.StartScope())
                    {
                        using (scope.StartTry())
                        {
                            termSet = termStore.GetTermSet(termSetId.Value);
                            storeContext.Load(termSet);
                        }

                        using (scope.StartCatch())
                        {

                        }
                    }

                    storeContext.ExecuteQueryWithTrace();

                    if (termSet != null && termSet.ServerObjectIsNull == false)
                    {
                        storeContext.Load(termSet, g => g.Id);
                        storeContext.ExecuteQueryWithTrace();

                        return termSet;
                    }
                }
            }

            return null;
        }
        private Field FindField(FieldCollection fields, ContentTypeFieldLinkDefinition listFieldLinkModel)
        {
            var context = fields.Context;

            var scope = new ExceptionHandlingScope(context);

            Field field = null;

            if (listFieldLinkModel.FieldId.HasGuidValue())
            {
                var id = listFieldLinkModel.FieldId.Value;

                using (scope.StartScope())
                {
                    using (scope.StartTry())
                    {
                        fields.GetById(id);
                    }

                    using (scope.StartCatch())
                    {

                    }
                }
            }
            else if (!string.IsNullOrEmpty(listFieldLinkModel.FieldInternalName))
            {
                var fieldInternalName = listFieldLinkModel.FieldInternalName;

                using (scope.StartScope())
                {
                    using (scope.StartTry())
                    {
                        fields.GetByInternalNameOrTitle(fieldInternalName);
                    }

                    using (scope.StartCatch())
                    {

                    }
                }
            }

            context.ExecuteQueryWithTrace();

            if (!scope.HasException)
            {
                if (listFieldLinkModel.FieldId.HasGuidValue())
                {
                    field = fields.GetById(listFieldLinkModel.FieldId.Value);
                }
                else if (!string.IsNullOrEmpty(listFieldLinkModel.FieldInternalName))
                {
                    field = fields.GetByInternalNameOrTitle(listFieldLinkModel.FieldInternalName);
                }

                context.Load(field);
                context.Load(field, f => f.SchemaXml);

                context.ExecuteQueryWithTrace();
            }

            return field;
        }
        protected TermGroup FindGroup(TermStoreModelHost storeModelHost, TaxonomyTermGroupDefinition groupModel)
        {
            var termStore = storeModelHost.HostTermStore;
            var context = termStore.Context;

            TermGroup currentGroup = null;

            if (groupModel.IsSiteCollectionGroup)
            {
                currentGroup = FindSiteCollectionGroup(storeModelHost, groupModel);
                return currentGroup;
            }

            if (groupModel.Id.HasValue)
            {
                var scope = new ExceptionHandlingScope(context);
                using (scope.StartScope())
                {
                    using (scope.StartTry())
                    {
                        currentGroup = termStore.Groups.GetById(groupModel.Id.Value);
                        context.Load(currentGroup);
                    }

                    using (scope.StartCatch())
                    {

                    }
                }
            }
            else if (!string.IsNullOrEmpty(groupModel.Name))
            {
                var scope = new ExceptionHandlingScope(context);
                using (scope.StartScope())
                {
                    using (scope.StartTry())
                    {
                        currentGroup = termStore.Groups.GetByName(groupModel.Name);
                        context.Load(currentGroup);
                    }

                    using (scope.StartCatch())
                    {

                    }
                }
            }

            context.ExecuteQueryWithTrace();

            if (currentGroup != null && currentGroup.ServerObjectIsNull == false)
            {
                context.Load(currentGroup, g => g.Id);
                context.Load(currentGroup, g => g.Name);

                context.ExecuteQueryWithTrace();

                return currentGroup;
            }

            return null;
        }
Exemplo n.º 59
0
        private static List LoadCurrentList(Web web, ListDefinition listModel)
        {
            var context = web.Context;

            List currentList = null;

            var listUrl = UrlUtility.CombineUrl(web.ServerRelativeUrl, listModel.GetListUrl());

            Folder folder = null;

            var scope = new ExceptionHandlingScope(context);

            using (scope.StartScope())
            {
                using (scope.StartTry())
                {
                    folder = web.GetFolderByServerRelativeUrl(listUrl);
                    context.Load(folder);
                }

                using (scope.StartCatch())
                {

                }
            }

            context.ExecuteQueryWithTrace();

            if (!scope.HasException && folder != null && folder.ServerObjectIsNull != true)
            {
                folder = web.GetFolderByServerRelativeUrl(listUrl);
                context.Load(folder.Properties);
                context.ExecuteQueryWithTrace();

                var listId = new Guid(folder.Properties["vti_listname"].ToString());
                var list = web.Lists.GetById(listId);

                context.Load(list);
                context.ExecuteQueryWithTrace();

                currentList = list;
            }

            return currentList;
        }
Exemplo n.º 60
-1
        public static Term AddTermToTermset(Guid termSetId, string term, Guid termId, ClientContext clientContext)
        {
            Term t = null;
            var scope = new ExceptionHandlingScope(clientContext);
            using (scope.StartScope())
            {
                using (scope.StartTry())
                {
                    TaxonomySession tSession = TaxonomySession.GetTaxonomySession(clientContext);
                    TermStore ts = tSession.GetDefaultSiteCollectionTermStore();
                    TermSet tset = ts.GetTermSet(termSetId);

                    t = tset.CreateTerm(term, 1033, termId);
                    clientContext.Load(tSession);
                    clientContext.Load(ts);
                    clientContext.Load(tset);
                    clientContext.Load(t);
                }
                using (scope.StartCatch())
                {
                    if (scope.HasException)
                    {
                        return null;
                    }
                }
            }
            clientContext.ExecuteQuery();

            return t;
        }