protected void btnReister_Click(object sender, EventArgs e)
        {
            if (ReturnUser())
            {
                List listReg = web.Lists.GetByTitle("UserRegistration");
                context.Load(listReg);
                context.ExecuteQuery();
                ListItemCreationInformation          itemCreation = new ListItemCreationInformation();
                Microsoft.SharePoint.Client.ListItem item         = listReg.AddItem(itemCreation);
                context.Load(item);
                item["Name"]             = txtName.Text;
                item["Passport_Office"]  = drppassOfc.SelectedValue;
                item["SurName"]          = txtsurName.Text;
                item["DateofBirth"]      = TextBox1.Text;
                item["Email_ID"]         = txtEmail.Text;
                item["Login_ID"]         = txtlogin.Text;
                item["Password"]         = txtPwd.Text;
                item["Confirm_Password"] = txtCPwd.Text;
                item["Hint_Question"]    = drpHint.SelectedValue;
                item["Hint_Answer"]      = txtHanswer.Text;
                item.Update();

                context.ExecuteQuery();
                Console.Write("Record Submitted successful....");
                Clear();
            }
        }
        protected void btnAddTask_Click(object sender, EventArgs e)
        {
            string SiteCollectionURL = txtSiteCollection.Text;

            CLOM.ClientContext      context    = new CLOM.ClientContext(SiteCollectionURL);
            CLOM.List               taskList   = context.Web.Lists.GetByTitle("Tasks");
            CLOM.CamlQuery          query      = new CamlQuery();
            CLOM.ListItemCollection myTaskList = taskList.GetItems(query);

            context.Load(myTaskList,
                         itms => itms.ListItemCollectionPosition,
                         itms => itms.Include(
                             itm => itm["Title"],
                             itm => itm["Body"],
                             itm => itm["DueDate"]));

            context.ExecuteQuery();

            ListItemCreationInformation newTask = new ListItemCreationInformation();

            CLOM.ListItem newTaskItem = taskList.AddItem(newTask);

            newTaskItem["Title"]   = txtTitle.Text;
            newTaskItem["Body"]    = txtDesc.Text;
            newTaskItem["DueDate"] = Calendar1.SelectedDate;
            newTaskItem.Update();

            context.ExecuteQuery();

            lblResult.Text = "Added Task " + txtTitle.Text;
        }
Exemple #3
0
 private void CreateNovoContacto(ClientContext siteContexto, List listaTelefonica, ItemListaTelefonicaProperties itemListaTelefonicaProperties)
 {
     try
     {
         ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
         ListItem addItem = listaTelefonica.AddItem(itemCreateInfo);
         addItem["Title"]       = itemListaTelefonicaProperties.PreferredName;
         addItem["FirstName"]   = itemListaTelefonicaProperties.FirstName;
         addItem["LastName"]    = itemListaTelefonicaProperties.LastName;
         addItem["Email"]       = itemListaTelefonicaProperties.Email;
         addItem["PagerNumber"] = itemListaTelefonicaProperties.Pager;
         addItem["Department"]  = itemListaTelefonicaProperties.Department;
         addItem["CellPhone"]   = itemListaTelefonicaProperties.CellPhone;
         addItem["PictureURL"]  = itemListaTelefonicaProperties.PictureURL;
         addItem["Office"]      = itemListaTelefonicaProperties.Office;
         addItem["WorkFax"]     = itemListaTelefonicaProperties.WorkFax;
         addItem["WorkPhone"]   = itemListaTelefonicaProperties.WorkPhone;
         addItem["WorkState"]   = itemListaTelefonicaProperties.WorkState;
         addItem["WorkCity"]    = itemListaTelefonicaProperties.WorkCity;
         addItem["WorkCountry"] = itemListaTelefonicaProperties.WorkCountry;
         addItem["WorkZip"]     = itemListaTelefonicaProperties.WorkZip;
         addItem["IpPhone"]     = itemListaTelefonicaProperties.IpPhone;
         addItem["WorkAddress"] = itemListaTelefonicaProperties.WorkAddress;
         addItem["AboutMe"]     = itemListaTelefonicaProperties.AboutMe;
         addItem["JobTitle"]    = itemListaTelefonicaProperties.JobTitle;
         addItem["Company"]     = itemListaTelefonicaProperties.Company;
         addItem.Update();
         siteContexto.ExecuteQuery();
     }
     catch (Exception ex)
     {
         _log.Error($"-> CreateNovoContacto no processo: SharepointSyncJob: {ex}", ex);
     }
 }
Exemple #4
0
        void SPtimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            //Comment out either of the below based on On Premise server or Online
            // Uri hostWeb = new Uri("http://tenant/sites/DevCenter");

            //Below line works with On line
            Uri hostWeb = new Uri("https://sweethome03.sharepoint.com");

            string realm = TokenHelper.GetRealmFromTargetUrl(hostWeb);

            string appOnlyAccessToken = TokenHelper.GetAppOnlyAccessToken(SharePointPrincipal, hostWeb.Authority, realm).AccessToken;

            using (ClientContext clientContext = TokenHelper.GetClientContextWithAccessToken(hostWeb.ToString(), appOnlyAccessToken))
            {
                if (clientContext != null)
                {
                    var myList = clientContext.Web.Lists.GetByTitle("WindowsTimerJob");
                    ListItemCreationInformation          listItemCreate = new ListItemCreationInformation();
                    Microsoft.SharePoint.Client.ListItem newItem        = myList.AddItem(listItemCreate);
                    newItem["Title"] = "Added from Timer Job";
                    newItem.Update();
                    clientContext.ExecuteQuery();
                }
            }
        }
        protected void btnScenario_Click(object sender, EventArgs e)
        {
            var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);

            using (var clientContext = spContext.CreateUserClientContextForSPHost())
            {
                Site site = clientContext.Site;
                clientContext.Load(site, s => s.Url);
                clientContext.ExecuteQuery();
                String webPartGalleryUrl = site.Url.TrimEnd('/') + "/_catalogs/wp";

                var folder = site.RootWeb.GetList(webPartGalleryUrl).RootFolder;
                //var folder = clientContext.Site.RootWeb.Lists.GetByTitle("Web Part Gallery").RootFolder;
                clientContext.Load(folder);
                clientContext.ExecuteQuery();

                //upload the "userprofileinformation.webpart" file
                using (var stream = System.IO.File.OpenRead(
                           Server.MapPath("~/userprofileinformation.webpart")))
                {
                    FileCreationInformation fileInfo = new FileCreationInformation();
                    fileInfo.ContentStream = stream;
                    fileInfo.Overwrite     = true;
                    fileInfo.Url           = "userprofileinformation.webpart";
                    File file = folder.Files.Add(fileInfo);
                    // Let's update the group for just uploaded web part
                    ListItem webpartItem = file.ListItemAllFields;
                    webpartItem["Group"] = "Add-in Script Part";
                    webpartItem.Update();
                    clientContext.ExecuteQuery();
                }

                lblStatus.Text = string.Format("Add-in script part has been added to web part gallery. You can find 'User Profile Information' script part under 'Add-in Script Part' group in the <a href='{0}'>host web</a>.", spContext.SPHostUrl.ToString());
            }
        }
        private void createButton_Click(object sender, RoutedEventArgs e)
        {
            string        UserName = "******", Password = "******";
            ClientContext ctx      = new ClientContext("https://omisayeduiu.sharepoint.com/sites/sayeddev");
            SecureString  passWord = new SecureString();

            foreach (char c in Password.ToCharArray())
            {
                passWord.AppendChar(c);
            }
            ctx.Credentials = new SharePointOnlineCredentials(UserName, passWord);


            Web myWeb = ctx.Web;

            Microsoft.SharePoint.Client.List sectionsList = myWeb.Lists.GetByTitle("sectionInfo");

            ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();

            Microsoft.SharePoint.Client.ListItem newItem = sectionsList.AddItem(itemCreateInfo);
            newItem["sectionName"]   = sectionBox.Text.Trim().ToString();
            newItem["sectionWeight"] = Convert.ToInt32(weightBox.Text.Trim());
            newItem.Update();

            ctx.ExecuteQuery();

            this.show();
        }
        public int UpdateEntry(EmployeeModel emp, string siteUrl, string ID)
        {
            try
            {
                using (MSC.ClientContext context = GetContext(siteUrl))
                {
                    MSC.List list = context.Web.Lists.GetByTitle("TIM_DailyAttendance");

                    MSC.ListItem listItem = null;

                    MSC.ListItemCreationInformation itemCreateInfo = new MSC.ListItemCreationInformation();
                    listItem = list.GetItemById(Convert.ToInt32(ID));

                    listItem["AttendanceDate"] = Convert.ToDateTime(emp.attendance_date).ToString("dd-MM-yyyy");
                    listItem["CheckinTime"]    = emp.checkin_time;
                    listItem["CheckoutTime"]   = emp.checkout_time;
                    listItem["Comment"]        = emp.comment;
                    listItem["EmpNo"]          = emp.empno;
                    listItem["Hours"]          = emp.hours;
                    listItem["EmpName"]        = emp.name;
                    listItem["EmpMail"]        = emp.office_email;
                    listItem.Update();
                    context.ExecuteQuery();
                }
            }
            catch (Exception ex)
            {
            }

            return(0);
        }
Exemple #8
0
        private void button4_Click(object sender, EventArgs e)
        {
            ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
            ListItem oListItem = oList.AddItem(itemCreateInfo);

            var    box  = comboBox1.SelectedItem;
            string boxx = box.ToString();


            if (boxx == null)
            {
                this.label5.Text = "Add genre";
            }
            var box2 = comboBox2lang.SelectedItem;
            var tex1 = textBox3title.Text;
            var tex2 = textBox5pages.Text;
            var tex4 = textBox4.Text;

            oListItem["Title"] = tex1;
            try
            {
                oListItem["Genre"] = new SPFieldLookupValue(boxx);
            }
            catch (ArgumentException)
            {
            }
            oListItem["Pages"]    = tex2;
            oListItem["Author4"]  = tex4;
            oListItem["Language"] = box2;
            oListItem.Update();

            clientContext.ExecuteQuery();
        }
Exemple #9
0
        public static int SendSTaticDataToSharePoint()
        {
            #region Connexion to SharePoint
            string WebUrl         = "https://ilcomptroller.sharepoint.com/spotestsite/";
            string login          = "******";
            string password       = "******";
            var    securePassword = new SecureString();
            foreach (char c in password)
            {
                securePassword.AppendChar(c);
            }
            var onlineCredentials = new SharePointOnlineCredentials(login, securePassword);
            #endregion
            #region Insert the data
            using (ClientContext CContext = new ClientContext(WebUrl))
            {
                CContext.Credentials = onlineCredentials;
                List announcementsList = CContext.Web.Lists.GetByTitle("SAMSTestList");
                ListItemCreationInformation          itemCreateInfo = new ListItemCreationInformation();
                Microsoft.SharePoint.Client.ListItem newItem        = announcementsList.AddItem(itemCreateInfo);

                newItem["Title"]            = "Ms.";
                newItem["First_x0020_Name"] = "R";
                newItem["Last_x0020_Name"]  = "S";
                newItem.Update();
                CContext.ExecuteQuery();
            }
            #endregion

            return(0);
        }
Exemple #10
0
        /// <summary>
        /// Updates the selected item in the list view, then reloads the data.
        /// </summary>
        private void UpdateButton_Click(object sender, EventArgs e)
        {
            if (RecipesListView.SelectedItems.Count != 0)
            {
                var selectedRecipe = RecipesListView.SelectedItems[0];

                Guid        uniqueId = Guid.Parse(selectedRecipe.Tag.ToString());
                SP.ListItem listItem = RecipesList.GetItemByUniqueId(uniqueId);

                // get updated values from input fields
                listItem["Title"] = RecipeTitleTextBox.Text;
                listItem["Required_x0020_Time"] = TimeNumericUpDown.Value.ToString();
                listItem["Difficulty"]          = DifficultyComboBox.SelectedItem.ToString();

                var categories = new List <string>();
                foreach (var checkedCategory in CategoryCheckedListBox.CheckedItems)
                {
                    categories.Add(checkedCategory.ToString());
                }

                listItem["Category"] = categories.ToArray();

                listItem.Update();
                Context.ExecuteQuery();

                LoadRecipes();
            }
        }
Exemple #11
0
        /// <summary>
        /// Adds a new item, then reloads the data.
        /// </summary>
        private void AddButton_Click(object sender, EventArgs e)
        {
            var creationInfo = new SP.ListItemCreationInformation();

            SP.ListItem newRecipe = RecipesList.AddItem(creationInfo);

            // get values from input fields
            newRecipe["Title"] = RecipeTitleTextBox.Text;
            newRecipe["Required_x0020_Time"] = TimeNumericUpDown.Value.ToString();
            newRecipe["Difficulty"]          = DifficultyComboBox.SelectedItem.ToString();

            var categories = new List <string>();

            foreach (var checkedCategory in CategoryCheckedListBox.CheckedItems)
            {
                categories.Add(checkedCategory.ToString());
            }

            newRecipe["Category"] = categories.ToArray();

            newRecipe.Update();
            Context.ExecuteQuery();

            LoadRecipes();
        }
Exemple #12
0
        static void CreateQuotFolders(ClientContext cc, List newLib, Web _web)
        {
            List <string> folders = new List <string> {
                "1 RFQ",
                "2 Communication",
                "3 Drawings and technical specifications",
                "4 RFQ Project (LQG 1_1)",
                "5 Purchase material and external operations",
                "6 Calculations",
                "7 Quotation (LQG 1_2)",
                "8 Customer decision (Order or No order)",
                "9 Handover to project or production (LQG 2)",
                "98 Work in Progress",
                "99 Archive"
            };

            foreach (string folder in folders)
            {
                ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();

                itemCreateInfo.UnderlyingObjectType = FileSystemObjectType.Folder;
                itemCreateInfo.LeafName             = folder;

                Microsoft.SharePoint.Client.ListItem newItem = newLib.AddItem(itemCreateInfo);
                newItem["Title"] = folder;
                newItem.Update();
                cc.ExecuteQuery();
            }
        }
Exemple #13
0
        public void AddHtmlToWikiPage(ClientContext ctx, Web web, string folder, string html, string page)
        {
            Microsoft.SharePoint.Client.Folder pagesLib = web.GetFolderByServerRelativeUrl(folder);
            ctx.Load(pagesLib.Files);
            ctx.ExecuteQuery();

            Microsoft.SharePoint.Client.File wikiPage = null;

            foreach (Microsoft.SharePoint.Client.File aspxFile in pagesLib.Files)
            {
                if (aspxFile.Name.Equals(page, StringComparison.InvariantCultureIgnoreCase))
                {
                    wikiPage = aspxFile;
                    break;
                }
            }

            if (wikiPage == null)
            {
                return;
            }

            ctx.Load(wikiPage);
            ctx.Load(wikiPage.ListItemAllFields);
            ctx.ExecuteQuery();

            string wikiField = (string)wikiPage.ListItemAllFields["WikiField"];

            Microsoft.SharePoint.Client.ListItem listItem = wikiPage.ListItemAllFields;
            listItem["WikiField"] = html;
            listItem.Update();
            ctx.ExecuteQuery();
        }
Exemple #14
0
        private void ProductEditorDialog_AddClosed(object sender, EventArgs e)
        {
            ProductEditor dialog = (ProductEditor)sender;

            // stop if they clicked cancel
            if (dialog.DialogResult == false)
            {
                return;
            }

            StatusBarPanel.BeginUpdateMessage("Creating new item...");

            SP.List products = Globals.ClientContext.Web.Lists.GetByTitle("Products");
            SP.ListItemCreationInformation newProductInfo = new SP.ListItemCreationInformation();

            SP.ListItem newProduct = products.AddItem(newProductInfo);
            newProduct["Title"] = dialog.ProductNameTextBox.Text;
            newProduct["Product_x0020_Number"] = dialog.ProductNumberTextBox.Text;
            newProduct["Price"] = dialog.ProductPriceTextBox.Text;
            SP.FieldLookupValue fieldValue = new SP.FieldLookupValue();
            foreach (SP.ListItem item in Globals.ProductCategories)
            {
                if (item["Title"].ToString() == ((SP.ListItem)dialog.ProductCategoryComboBox.SelectedItem)["Title"].ToString())
                {
                    fieldValue.LookupId = item.Id;
                }
            }
            newProduct["Category"] = fieldValue;

            newProduct.Update();
            Globals.ClientContext.ExecuteQuery();

            this.Dispatcher.BeginInvoke(new Action(OnProducteditorAddUIUpdater), DispatcherPriority.Normal);
        }
Exemple #15
0
        /// <summary>
        /// Creates new options to the look and feel section
        /// </summary>
        /// <param name="clientContext"></param>
        /// <param name="web"></param>
        private void AddNewThemeOptionToSite(ClientContext clientContext, Web web)
        {
            // Let's get instance to the composite look gallery
            List themesOverviewList = web.GetCatalog(124);

            clientContext.Load(themesOverviewList);
            clientContext.ExecuteQuery();
            // Is the item already in the list?
            if (!ContosoThemeEntryExists(clientContext, web, themesOverviewList))
            {
                // Let's create new theme entry. Notice that theme selection is not available from UI in personal sites, so this is just for consistency sake
                ListItemCreationInformation          itemInfo = new ListItemCreationInformation();
                Microsoft.SharePoint.Client.ListItem item     = themesOverviewList.AddItem(itemInfo);
                item["Name"]          = "Contoso";
                item["Title"]         = "Contoso";
                item["ThemeUrl"]      = URLCombine(web.ServerRelativeUrl, "/_catalogs/theme/15/contoso.spcolor");;
                item["FontSchemeUrl"] = URLCombine(web.ServerRelativeUrl, "/_catalogs/theme/15/contoso.spfont");;
                item["ImageUrl"]      = URLCombine(web.ServerRelativeUrl, "/_catalogs/theme/15/contosobg.jpg");
                // Notice that we use oob master, but just as well you vould upload and use custom one
                item["MasterPageUrl"] = URLCombine(web.ServerRelativeUrl, "/_catalogs/masterpage/seattle.master");
                item["DisplayOrder"]  = 0;
                item.Update();
                clientContext.ExecuteQuery();
            }
        }
Exemple #16
0
        public override bool Write(string fileName, byte[] data)
        {
            try
            {
                SharepointClientContext.Load(SharepointList.RootFolder);
                SharepointClientContext.ExecuteQuery();

                string fileUrl = String.Format("{0}/{1}", SharepointList.RootFolder.ServerRelativeUrl, fileName);
                Microsoft.SharePoint.Client.File.SaveBinaryDirect(_clientContext, fileUrl, new MemoryStream(data, false), true);
                _clientContext.ExecuteQuery(); //Uploaded .. but still checked out...


                //Load the FieldCollection from the list...
                SP.FieldCollection fileFields = SharepointList.Fields;
                _clientContext.Load(fileFields);
                _clientContext.ExecuteQuery();

                SP.File     uploadedFile    = _web.GetFileByServerRelativeUrl(fileUrl);
                SP.ListItem newFileListItem = uploadedFile.ListItemAllFields;
                newFileListItem.Update();
                _clientContext.ExecuteQuery();
                return(true);
            }
            catch
            {
                return(false);
            }
        }
Exemple #17
0
        void ProvisionSample2(Web web)
        {
            //Delete list if it already exists
            ListCollection     lists   = web.Lists;
            IEnumerable <List> results = web.Context.LoadQuery <List>(lists.Where(list => list.Title == "CSR-Substring-long-text"));

            web.Context.ExecuteQuery();
            List existingList = results.FirstOrDefault();

            if (existingList != null)
            {
                existingList.DeleteObject();
                web.Context.ExecuteQuery();
            }

            //Create list
            ListCreationInformation creationInfo = new ListCreationInformation();

            creationInfo.Title        = "CSR-Substring-long-text";
            creationInfo.TemplateType = (int)ListTemplateType.Announcements;
            List newlist = web.Lists.Add(creationInfo);

            newlist.Update();
            web.Context.Load(newlist);
            web.Context.ExecuteQuery();

            //Add items
            Microsoft.SharePoint.Client.ListItem item1 = newlist.AddItem(new ListItemCreationInformation());
            item1["Title"] = "Announcement 1";
            item1["Body"]  = "Aaaaaa Bbbbbb Cccccc Dccccc Eeeeee Ffffff Gggggg Hhhhhh Iiiiii Jjjjjj Kkkkkk Llllll Mmmmmm Nnnnnn Oooooo Pppppp Qqqqqq Rrrrrr Ssssss Tttttt Uuuuuu Vvvvvv Wwwwww Xxxxx Yyyyyy Zzzzzz";
            item1.Update();

            Microsoft.SharePoint.Client.ListItem item2 = newlist.AddItem(new ListItemCreationInformation());
            item2["Title"] = "Announcement 2";
            item2["Body"]  = "Aaaaaa Bbbbbb Cccccc Dccccc Eeeeee Ffffff Gggggg Hhhhhh Iiiiii Jjjjjj Kkkkkk Llllll Mmmmmm Nnnnnn Oooooo Pppppp Qqqqqq Rrrrrr Ssssss Tttttt Uuuuuu Vvvvvv Wwwwww Xxxxx Yyyyyy Zzzzzz";
            item2.Update();

            Microsoft.SharePoint.Client.ListItem item3 = newlist.AddItem(new ListItemCreationInformation());
            item3["Title"] = "Announcement 3";
            item3["Body"]  = "Aaaaaa Bbbbbb Cccccc Dccccc Eeeeee Ffffff Gggggg Hhhhhh Iiiiii Jjjjjj Kkkkkk Llllll Mmmmmm Nnnnnn Oooooo Pppppp Qqqqqq Rrrrrr Ssssss Tttttt Uuuuuu Vvvvvv Wwwwww Xxxxx Yyyyyy Zzzzzz";
            item3.Update();

            //Create sample view
            ViewCreationInformation sampleViewCreateInfo = new ViewCreationInformation();

            sampleViewCreateInfo.Title            = "CSR Sample View";
            sampleViewCreateInfo.ViewFields       = new string[] { "Title", "Body" };
            sampleViewCreateInfo.SetAsDefaultView = true;
            Microsoft.SharePoint.Client.View sampleView = newlist.Views.Add(sampleViewCreateInfo);
            sampleView.Update();
            web.Context.Load(newlist, l => l.DefaultViewUrl);
            web.Context.ExecuteQuery();

            //Register JS files via JSLink properties
            RegisterJStoWebPart(web, newlist.DefaultViewUrl, "~sitecollection/Style Library/JSLink-Samples/SubstringLongText.js");
        }
Exemple #18
0
        private static void AddListItem(ClientContext clientContext, string listName)
        {
            Web currentWeb = clientContext.Web;
            var myList     = clientContext.Web.Lists.GetByTitle(listName);
            ListItemCreationInformation listItemCreate = new ListItemCreationInformation();

            Microsoft.SharePoint.Client.ListItem newItem = myList.AddItem(listItemCreate);
            newItem["Title"] = "Item added by Job at " + DateTime.Now;
            newItem.Update();
            clientContext.ExecuteQuery();
        }
Exemple #19
0
        void ProvisionSample7(Web web)
        {
            //Delete list if it already exists
            ListCollection lists = web.Lists;

            web.Context.Load(web.CurrentUser, i => i.Id);
            IEnumerable <List> results = web.Context.LoadQuery <List>(lists.Where(list => list.Title == "CSR-Read-only-SP-Controls"));

            web.Context.ExecuteQuery();
            List existingList = results.FirstOrDefault();

            if (existingList != null)
            {
                existingList.DeleteObject();
                web.Context.ExecuteQuery();
            }

            //Create list
            ListCreationInformation creationInfo = new ListCreationInformation();

            creationInfo.Title        = "CSR-Read-only-SP-Controls";
            creationInfo.TemplateType = (int)ListTemplateType.Tasks;
            List newlist = web.Lists.Add(creationInfo);

            newlist.Update();
            web.Context.Load(newlist);
            web.Context.ExecuteQuery();

            //Add items
            Microsoft.SharePoint.Client.ListItem item1 = newlist.AddItem(new ListItemCreationInformation());
            item1["Title"]      = "Task 1";
            item1["StartDate"]  = "2014-1-1";
            item1["DueDate"]    = "2014-2-1";
            item1["AssignedTo"] = new FieldLookupValue {
                LookupId = web.CurrentUser.Id
            };
            item1.Update();


            //Create sample view
            ViewCreationInformation sampleViewCreateInfo = new ViewCreationInformation();

            sampleViewCreateInfo.Title            = "CSR Sample View";
            sampleViewCreateInfo.ViewFields       = new string[] { "DocIcon", "LinkTitle", "DueDate", "AssignedTo" };
            sampleViewCreateInfo.SetAsDefaultView = true;
            Microsoft.SharePoint.Client.View sampleView = newlist.Views.Add(sampleViewCreateInfo);
            sampleView.Update();
            web.Context.Load(newlist,
                             l => l.DefaultEditFormUrl);
            web.Context.ExecuteQuery();

            //Register JS files via JSLink properties
            RegisterJStoWebPart(web, newlist.DefaultEditFormUrl, "~sitecollection/Style Library/JSLink-Samples/ReadOnlySPControls.js");
        }
Exemple #20
0
        void ProvisionSample6(Web web)
        {
            //Delete list if it already exists
            ListCollection     lists   = web.Lists;
            IEnumerable <List> results = web.Context.LoadQuery <List>(lists.Where(list => list.Title == "CSR-Email-Regex-Validator"));

            web.Context.ExecuteQuery();
            List existingList = results.FirstOrDefault();

            if (existingList != null)
            {
                existingList.DeleteObject();
                web.Context.ExecuteQuery();
            }

            //Create list
            ListCreationInformation creationInfo = new ListCreationInformation();

            creationInfo.Title        = "CSR-Email-Regex-Validator";
            creationInfo.TemplateType = (int)ListTemplateType.GenericList;
            List newlist = web.Lists.Add(creationInfo);

            newlist.Update();
            web.Context.Load(newlist);
            web.Context.ExecuteQuery();

            //Add field
            newlist.Fields.AddFieldAsXml("<Field Type=\"" + FieldType.Text + "\" Name=\"Email\" DisplayName=\"Email\" ID=\"" + Guid.NewGuid() + "\" Group=\"CSR Samples\" />", false, AddFieldOptions.DefaultValue);
            newlist.Update();
            web.Context.ExecuteQuery();

            //Add items
            Microsoft.SharePoint.Client.ListItem item1 = newlist.AddItem(new ListItemCreationInformation());
            item1["Title"] = "Email address";
            item1["Email"] = "*****@*****.**";
            item1.Update();

            //Create sample view
            ViewCreationInformation sampleViewCreateInfo = new ViewCreationInformation();

            sampleViewCreateInfo.Title            = "CSR Sample View";
            sampleViewCreateInfo.ViewFields       = new string[] { "LinkTitle", "Email" };
            sampleViewCreateInfo.SetAsDefaultView = true;
            Microsoft.SharePoint.Client.View sampleView = newlist.Views.Add(sampleViewCreateInfo);
            sampleView.Update();

            web.Context.Load(newlist, l => l.DefaultNewFormUrl, l => l.DefaultEditFormUrl);
            web.Context.ExecuteQuery();

            //Register JS files via JSLink properties
            RegisterJStoWebPart(web, newlist.DefaultNewFormUrl, "~sitecollection/Style Library/JSLink-Samples/RegexValidator.js");
            RegisterJStoWebPart(web, newlist.DefaultEditFormUrl, "~sitecollection/Style Library/JSLink-Samples/RegexValidator.js");
        }
Exemple #21
0
        private static void AddNewThemeOptionToWebImplementation(this Web web, Web rootWeb, string themeName, string colorFileName, string fontFileName, string backgroundName, string masterPageName)
        {
            LoggingUtility.Internal.TraceInformation((int)EventId.AddThemeOption, "Adding theme option '{0}' to '{1}'", themeName, web.Context.Url);

            // Let's get instance to the composite look gallery of specific site
            List themesOverviewList = web.GetCatalog((int)ListTemplateType.DesignCatalog);

            web.Context.Load(themesOverviewList);
            web.Context.ExecuteQuery();
            // Is the item already in the list?
            if (!web.ThemeEntryExists(themeName, themesOverviewList))
            {
                // Let's ensure that we have root site loaded for setting URLs properly
                Utility.EnsureWeb(rootWeb.Context, rootWeb, "ServerRelativeUrl");
                Utility.EnsureWeb(web.Context, web, "ServerRelativeUrl");

                // Let's create new theme entry. Notice that theme selection is not available from UI in personal sites, so this is just for consistency sake
                ListItemCreationInformation          itemInfo = new ListItemCreationInformation();
                Microsoft.SharePoint.Client.ListItem item     = themesOverviewList.AddItem(itemInfo);
                item["Name"]  = themeName;
                item["Title"] = themeName;
                if (!string.IsNullOrEmpty(colorFileName))
                {
                    item["ThemeUrl"] = UrlUtility.Combine(rootWeb.ServerRelativeUrl, string.Format(Constants.THEMES_DIRECTORY, Path.GetFileName(colorFileName)));
                }
                if (!string.IsNullOrEmpty(fontFileName))
                {
                    item["FontSchemeUrl"] = UrlUtility.Combine(rootWeb.ServerRelativeUrl, string.Format(Constants.THEMES_DIRECTORY, Path.GetFileName(fontFileName)));
                }
                if (!string.IsNullOrEmpty(backgroundName))
                {
                    item["ImageUrl"] = UrlUtility.Combine(rootWeb.ServerRelativeUrl, string.Format(Constants.THEMES_DIRECTORY, Path.GetFileName(backgroundName)));
                }
                // we use seattle master if anything else is not set
                if (string.IsNullOrEmpty(masterPageName))
                {
                    item["MasterPageUrl"] = UrlUtility.Combine(web.ServerRelativeUrl, Constants.MASTERPAGE_SEATTLE);
                }
                else
                {
                    item["MasterPageUrl"] = UrlUtility.Combine(web.ServerRelativeUrl, string.Format(Constants.MASTERPAGE_DIRECTORY, Path.GetFileName(masterPageName)));
                }

                item["DisplayOrder"] = 11;
                item.Update();
                web.Context.ExecuteQuery();
            }
            else
            {
                LoggingUtility.Internal.TraceWarning((int)EventId.ThemeNotOverwritten, "Theme '{0}' already exists (and was not overwritten). No changes made.", themeName);
            }
        }
        private void Edit(Project pro)
        {
            if (oList != null)
            {
                // Edit
                if (pro.Id != 0)
                {
                    // Assume there is a list item with ID=1.
                    ListItem listItem = oList.GetItemById(pro.Id);
                    // Write a new value to the Body field of the Announcement item.
                    listItem["ProjectName"]     = pro.ProjectName;
                    listItem["ProjDescription"] = pro.Description;
                    listItem["StartDate"]       = pro.StartDate;
                    listItem["_EndDate"]        = pro.EndDate;
                    listItem["State"]           = pro.State;

                    // Leader
                    FieldLookupValue lookup = new FieldLookupValue();
                    lookup.LookupId    = 3;
                    listItem["Leader"] = lookup;

                    // Members
                    List <FieldLookupValue> lvList = new List <FieldLookupValue>();
                    lvList.Add(lookup);
                    lvList.Add(new FieldLookupValue()
                    {
                        LookupId = 1
                    });
                    listItem["Member"] = lvList;
                    listItem.Update();
                    context.ExecuteQuery();

                    context.ExecuteQuery();
                }
                // Add new item
                else
                {
                    ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
                    ListItem newItem = oList.AddItem(itemCreateInfo);
                    newItem["Title"]           = Guid.NewGuid();
                    newItem["ProjectName"]     = pro.ProjectName;
                    newItem["ProjDescription"] = pro.Description;
                    newItem["StartDate"]       = pro.StartDate;
                    newItem["_EndDate"]        = pro.EndDate;
                    newItem["State"]           = pro.State;
                    newItem.Update();

                    context.ExecuteQuery();
                }
            }
        }
Exemple #23
0
        private void OnProducteditorUpdateWorker(object state)
        {
            SP.ListItem product = state as SP.ListItem;

            // get the category selected
            product["Category"] = selectedCategory;

            // update the field
            product.Update();
            Globals.ClientContext.ExecuteQuery();

            // fire the UI work on another thread
            this.Dispatcher.BeginInvoke(new Action(OnProducteditorUpdateUIUpdater), DispatcherPriority.Normal);
        }
Exemple #24
0
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            CLOM.ClientContext context = new CLOM.ClientContext(CLOM.ApplicationContext.Current.Url);

            CLOM.List taskList = context.Web.Lists.GetByTitle("Tasks");

            CLOM.ListItemCreationInformation itemCreateInfo = new CLOM.ListItemCreationInformation();
            CLOM.ListItem newItem = taskList.AddItem(itemCreateInfo);
            newItem["Title"]   = textBox1.Text;
            newItem["DueDate"] = calendar1.SelectedDate.Value.ToShortDateString();
            newItem.Update();

            context.ExecuteQueryAsync(ClientRequestSucceeded, ClientRequestFailed);
        }
Exemple #25
0
        Tree _folder_tree = null;         // this is a local copy of the SharePoint List folder tree. to improve performance.

        /// <summary>
        /// Create folder for items, if it's not exists.
        /// </summary>
        /// <param name="parent_folder">The parent folder. Tree object.</param>
        /// <param name="target_folder_name">The name of the target folder under current parent folder.</param>
        /// <returns>The reference to the target folder. Tree object.</returns>
        private Tree create_folder_if_not_exists(Tree parent_folder, string target_folder_name)
        {
            this.Invoke(_update_message,
                        new object[] { "Processing: " + target_folder_name + " " + DateTime.Now.ToLongTimeString() }
                        );
            string target_folder_url = parent_folder.URL + "/" + target_folder_name;

            foreach (Tree child_folder in parent_folder.Children)
            {
                if (child_folder.URL.ToLower().Equals(target_folder_url.ToLower()))
                {
                    return(child_folder);
                }
            }

            try {
                // TODO: I should try to catch exceptions here.
                ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
                itemCreateInfo.UnderlyingObjectType = FileSystemObjectType.Folder;
                itemCreateInfo.FolderUrl            = parent_folder.URL;
                _message += "\n  create folder:" + parent_folder.URL + "/" + target_folder_name;
                Microsoft.SharePoint.Client.ListItem olistItem = _list.AddItem(itemCreateInfo);
                olistItem["Title"] = target_folder_name;
                olistItem.Update();
                _clientContext.ExecuteQuery();
            }
            catch (Exception ex) {
                //MessageBox.Show(_message+"\n"+ex.ToString());
                if (ex.Message.Contains("exist"))
                {
                    //nothing to do with it.
                }
                else
                {
                    throw ex;
                }
            }

            Tree target_folder = new Tree();

            target_folder.Name     = target_folder_name;
            target_folder.URL      = target_folder_url;
            target_folder.Parent   = parent_folder;
            target_folder.Children = new List <Tree>();
            parent_folder.Children.Add(target_folder);

            return(target_folder);
        }
Exemple #26
0
        private static void AddNewThemeOptionToSite(Web web, string themeName, string colorFilePath, string fontFilePath, string backGroundPath, string masterPageName)
        {
            // Let's get instance to the composite look gallery
            List themesOverviewList = web.GetCatalog(124);

            web.Context.Load(themesOverviewList);
            web.Context.ExecuteQuery();
            // Do not add duplicate, if the theme is already there
            if (!ThemeEntryExists(web, themesOverviewList, themeName))
            {
                // if web information is not available, load it
                if (!web.IsObjectPropertyInstantiated("ServerRelativeUrl"))
                {
                    web.Context.Load(web);
                    web.Context.ExecuteQuery();
                }
                // Let's create new theme entry. Notice that theme selection is not available from UI in personal sites, so this is just for consistency sake
                ListItemCreationInformation          itemInfo = new ListItemCreationInformation();
                Microsoft.SharePoint.Client.ListItem item     = themesOverviewList.AddItem(itemInfo);
                item["Name"]  = themeName;
                item["Title"] = themeName;
                if (!string.IsNullOrEmpty(colorFilePath))
                {
                    item["ThemeUrl"] = URLCombine(web.ServerRelativeUrl, string.Format("/_catalogs/theme/15/{0}", System.IO.Path.GetFileName(colorFilePath)));
                }
                if (!string.IsNullOrEmpty(fontFilePath))
                {
                    item["FontSchemeUrl"] = URLCombine(web.ServerRelativeUrl, string.Format("/_catalogs/theme/15/{0}", System.IO.Path.GetFileName(fontFilePath)));
                }
                if (!string.IsNullOrEmpty(backGroundPath))
                {
                    item["ImageUrl"] = URLCombine(web.ServerRelativeUrl, string.Format("/_catalogs/theme/15/{0}", System.IO.Path.GetFileName(backGroundPath)));
                }
                // we use seattle master if anythign else is not set
                if (string.IsNullOrEmpty(masterPageName))
                {
                    item["MasterPageUrl"] = URLCombine(web.ServerRelativeUrl, "/_catalogs/masterpage/seattle.master");
                }
                else
                {
                    item["MasterPageUrl"] = URLCombine(web.ServerRelativeUrl, string.Format("/_catalogs/masterpage/{0}", Path.GetFileName(masterPageName)));
                }

                item["DisplayOrder"] = 11;
                item.Update();
                web.Context.ExecuteQuery();
            }
        }
        private void Seeding(object sender, RoutedEventArgs e)
        {
            //Add Data.
            ListItem newItem1 = oList.AddItem(new ListItemCreationInformation());

            newItem1["Title"]           = $"Project {Guid.NewGuid()}";
            newItem1["ProjectName"]     = "Project 1";
            newItem1["ProjDescription"] = "A12345";
            newItem1["StartDate"]       = new DateTime(2021, 6, 4).ToString("o");
            newItem1["_EndDate"]        = new DateTime(2021, 6, 4).ToString("o");
            newItem1["State"]           = "Signed";

            // Leader
            FieldLookupValue lv = new FieldLookupValue();

            lv.LookupId        = 1;
            newItem1["Leader"] = lv;

            // Members
            List <FieldLookupValue> lvList = new List <FieldLookupValue>();

            lvList.Add(lv);
            lvList.Add(new FieldLookupValue()
            {
                LookupId = 3
            });
            newItem1["Member"] = lvList;
            newItem1.Update();
            context.ExecuteQuery();


            //Add Data.
            ListItem newItem2 = oList.AddItem(new ListItemCreationInformation());

            newItem2["Title"]           = $"Project {Guid.NewGuid()}";
            newItem2["ProjectName"]     = "Project 3";
            newItem2["ProjDescription"] = "A78901";
            newItem2["StartDate"]       = new DateTime(2021, 8, 7).ToString("o");
            newItem2["_EndDate"]        = new DateTime(2021, 8, 7).ToString("o");
            newItem2["State"]           = "Signed";

            lv                 = new FieldLookupValue();
            lv.LookupId        = 1;
            newItem2["Leader"] = lv;
            newItem2.Update();

            context.ExecuteQuery();
        }
 protected void UpdateListItem()
 {
     try
     {
         List testeList = context.Web.Lists.GetByTitle("Teste");
         Microsoft.SharePoint.Client.ListItem item = testeList.GetItemById(1);
         item["Title"] = "Nome alterado via código";
         item.Update();
         context.ExecuteQuery();
     }
     catch (Exception ex)
     {
         lbl1.Text = ex.Message;
         throw;
     }
 }
Exemple #29
0
        /// <summary>
        /// Creates sample codes list for demo purposes
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="web"></param>
        public void SetupCodesList(ClientContext ctx, Web web)
        {
            string newListName = "CodesList";

            var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);

            using (ctx = spContext.CreateUserClientContextForSPHost())
            {
                if (!ctx.Web.ListExists(newListName))
                {
                    ctx.Web.AddList(ListTemplateType.GenericList, newListName, false, true);

                    List newlist = ctx.Web.Lists.GetByTitle(newListName);

                    FieldCollection collField = newlist.Fields;

                    // Add url field for links to site assets images
                    collField.AddFieldAsXml("<Field DisplayName='CodesImageUrl' Name='CodesImageUrl' Type='URL' />",
                                            true,
                                            AddFieldOptions.DefaultValue);
                    ctx.Load(collField);
                    ctx.ExecuteQuery();

                    // Create sample list items needed for demo purposes only
                    ListItemCreationInformation          itemCreateInfo = new ListItemCreationInformation();
                    Microsoft.SharePoint.Client.ListItem newXXItem      = newlist.AddItem(itemCreateInfo);
                    newXXItem["Title"]         = "XX";
                    newXXItem["CodesImageUrl"] = "/SiteAssets/contosoxx.png";
                    newXXItem.Update();

                    itemCreateInfo = new ListItemCreationInformation();
                    Microsoft.SharePoint.Client.ListItem newYYItem = newlist.AddItem(itemCreateInfo);
                    newYYItem["Title"]         = "YY";
                    newYYItem["CodesImageUrl"] = "/SiteAssets/contosoyy.png";
                    newYYItem.Update();

                    itemCreateInfo = new ListItemCreationInformation();
                    Microsoft.SharePoint.Client.ListItem newZZItem = newlist.AddItem(itemCreateInfo);
                    newZZItem["Title"]         = "ZZ";
                    newZZItem["CodesImageUrl"] = "/SiteAssets/contosoZZ.png";
                    newZZItem.Update();

                    // Batch update
                    ctx.ExecuteQuery();
                }
            }
        }
        public void Update(User mergeUser, IEnumerable <string> fields)
        {
            var userProfile = mergeUser as SPSiteUser;

            if (userProfile == null)
            {
                return;
            }

            SP.ListItem spUser = userProfile.Profile;
            foreach (string fieldName in fields)
            {
                SetSanitizeUserFieldValue(spUser, fieldName, mergeUser[fieldName]);
            }
            spUser.Update();
            spcontext.ExecuteQuery();
        }