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;
        }
Esempio n. 2
0
    private void GetDocIDURL(ref StringBuilder permaurl)
    {
        string ctxurl = permaurl.ToString(0, 24);
        string relurl = permaurl.Replace("https://sp.contoso.com", "").ToString();

        // Starting with ClientContext, the constructor requires a URL to the
        // server running SharePoint.
        SP.ClientContext context = new SP.ClientContext(ctxurl);
        // The SharePoint web at the URL.
        SP.Web web = context.Web;
        // Load
        context.Load(web);
        // Execute query.
        context.ExecuteQuery();
        //
        SP.File     ObjFile = web.GetFileByServerRelativeUrl(relurl);
        SP.ListItem item    = ObjFile.ListItemAllFields;
        //
        context.Load(ObjFile);
        context.Load(item);
        context.ExecuteQuery();
        //
        //string fileName = item.FieldValues["FileLeafRef"].ToString();
        //string fileType = System.IO.Path.GetExtension(fileName);
        //Guid uniqueId = new Guid(item.FieldValues["UniqueId"].ToString());
        var furl = item.FieldValues["_dlc_DocIdUrl"] as SP.FieldUrlValue;

        permaurl.Clear();
        permaurl.Append(furl.Url);
    }
Esempio n. 3
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();
            }
        }
Esempio n. 4
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();
        }
Esempio n. 5
0
 public static News QueryNewsDetails(int newsId)
 {
     try
     {
         News news = new News();
         Microsoft.SharePoint.Client.ListItemCollection coll = DAT.DataQuery.QueryListItems(NewsModel.newsSiteUrl, NewsModel.sayfalarListName, string.Format(NewsModel.newsDetailCamlQuery, newsId));
         SP.ListItem item = coll[0];
         news.ID       = newsId;
         news.Modified = Convert.ToDateTime(item["Modified"]);
         news.Title    = item["Title"].ToString();
         string[] metaInfo = item["MetaInfo"].ToString().Split('\n');
         foreach (var i in metaInfo)
         {
             if (i.Contains("vti_cachedcustomprops"))
             {
                 continue;
             }
             if (i.Contains("PublishingPageContent:SW"))
             {
                 news.PublishingPageContent = HLP.TransformHtmlString(i.Split('|')[1].Replace("\r", ""));
             }
         }
         return(news);
     }
     catch (Exception ex)
     {
         EXP.RedirectToErrorPage(ex.Message);
         return(null);
     }
 }
Esempio n. 6
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);
     }
 }
Esempio n. 7
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();
            }
        }
Esempio n. 8
0
        public static FieldLookupValue GetLookupFieldValue(string lookupName, string lookupListName, string lookupFieldName, string lookupFieldType, ClientContext clientContext)
        {
            //Ref:https://karinebosch.wordpress.com/2015/05/11/setting-the-value-of-a-lookup-field-using-csom/
            var       lookupList = clientContext.Web.Lists.GetByTitle(lookupListName);
            CamlQuery query      = new CamlQuery();


            query.ViewXml = string.Format(@"<View><Query><Where><Eq><FieldRef Name='{0}'/><Value Type='{1}'>{2}</Value></Eq>" +
                                          "</Where></Query></View>", lookupFieldName, lookupFieldType, lookupName);

            sp.ListItemCollection listItems = lookupList.GetItems(query);
            clientContext.Load(listItems, items => items.Include
                                   (listItem => listItem["ID"],
                                   listItem => listItem[lookupFieldName]));
            clientContext.ExecuteQuery();

            if (listItems != null)
            {
                sp.ListItem      item        = listItems[0];
                FieldLookupValue lookupValue = new FieldLookupValue();
                lookupValue.LookupId = int.Parse(item["ID"].ToString());
                return(lookupValue);
            }



            return(null);
        }
        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();
            }
        }
Esempio n. 10
0
        public void uploadCSVFile(ClientContext ctx, string libraryName, string filePath, string fn)
        {
            Web web = ctx.Web;
            FileCreationInformation newFile = new FileCreationInformation();

            newFile.Overwrite = true;
            newFile.Content   = System.IO.File.ReadAllBytes(filePath);
            newFile.Url       = System.IO.Path.GetFileName(filePath);

            List docs = web.Lists.GetByTitle(libraryName);

            // Add file to the library.
            Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(newFile);
            sp.ListItem item = uploadFile.ListItemAllFields;
            item["Title"]             = "ITL";
            item["Project"]           = "project";
            item["_x0023_Records"]    = "RECORDS";
            item["Target_x0020_List"] = "Target";
            item["_x0023_Records"]    = 22;

            uploadFile.ListItemAllFields.Update();

            ctx.Load(uploadFile);
            ctx.ExecuteQuery();
        }
Esempio n. 11
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);
            }
        }
Esempio n. 12
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();
        }
Esempio n. 13
0
        //파일정보 가져오기
        protected void btnGetFile_Click(object sender, EventArgs e)
        {
            Web web = ClContext.Web;

            ClContext.Load(web);
            ClContext.ExecuteQuery();

            File spfile = web.GetFileByUrl(txtFileUrl.Text);

            ClContext.Load(spfile);
            ClContext.ExecuteQuery();

            List splist = spfile.ListItemAllFields.ParentList;

            ClContext.Load(splist);
            ClContext.ExecuteQuery();

            Microsoft.SharePoint.Client.ListItem splistitem = splist.GetItemByUniqueId(spfile.UniqueId);
            ClContext.Load(splistitem);
            ClContext.ExecuteQuery();

            Dictionary <string, object> fields = splistitem.FieldValues;

            foreach (string fieldKey in fields.Keys)
            {
                lblFileInfo.Text += fieldKey + ":: " + splistitem[fieldKey];
                lblFileInfo.Text += "<br>";
            }
        }
Esempio n. 14
0
        public string GetFileInfo([FromBody] TestParams param)
        {
            string fileUrl = param.fileUrl;

            Web web = ClContext.Web;

            ClContext.Load(web);
            ClContext.ExecuteQuery();

            File spfile = web.GetFileByUrl(fileUrl);

            ClContext.Load(spfile);
            ClContext.ExecuteQuery();

            List splist = spfile.ListItemAllFields.ParentList;

            ClContext.Load(splist);
            ClContext.ExecuteQuery();

            Microsoft.SharePoint.Client.ListItem splistitem = splist.GetItemByUniqueId(spfile.UniqueId);
            ClContext.Load(splistitem);
            ClContext.ExecuteQuery();


            Dictionary <string, object> dict = splistitem.FieldValues;

            return(MyDictionaryToJson(dict));
        }
Esempio n. 15
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();
                }
            }
        }
Esempio n. 16
0
        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());
            }
        }
Esempio n. 17
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);
        }
Esempio n. 18
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);
        }
        public SP.FileCollection Attachments(SPListItem listItem, SPList list, object value)
        {
            if (value == null || !(bool)value)
            {
                return(null);
            }

            using (var clientContext = new SPContext(list.SPWebUrl, credentials.Get(list.SPWebUrl)))
            {
                SP.Web web = clientContext.Web;
                clientContext.Load(web);
                SP.List splist = clientContext.ToList(list.Id);
                clientContext.Load(splist);
                SP.ListItem splistItem = splist.GetItemById(listItem.Id);
                clientContext.Load(splistItem);
                clientContext.ExecuteQuery();

                SP.Folder listFolder = splistItem.ParentList.RootFolder;
                clientContext.Load(listFolder, f => f.ServerRelativeUrl);
                clientContext.ExecuteQuery();

                SP.Folder attachmentsFolder = web.GetFolderByServerRelativeUrl(listFolder.ServerRelativeUrl + "/attachments/" + splistItem.Id.ToString());
                clientContext.Load(attachmentsFolder);
                var attachments = attachmentsFolder.Files;
                clientContext.Load(attachments);
                clientContext.ExecuteQuery();

                return(attachments);
            }
        }
        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();
        }
Esempio n. 21
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();
        }
Esempio n. 22
0
        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);
        }
Esempio n. 23
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();
            }
        }
Esempio n. 24
0
        private void button3_Click(object sender, EventArgs e)
        {
            string delete = textBox2.Text;

            ListItem oListItem = oList.GetItemById(delete);


            clientContext.ExecuteQuery();
        }
Esempio n. 25
0
        static void Main(string[] args)
        {
            string userName = "******";

            Console.WriteLine("Enter your password.");
            SecureString password = GetPassword();
            bool         IsError  = true;

            using (var clientContext = new ClientContext("https://acuvatehyd.sharepoint.com/teams/VenuProject13102018/"))
            {
                clientContext.Credentials = new SharePointOnlineCredentials(userName, password);

                try
                {
                    List list = clientContext.Web.Lists.GetByTitle("Documents");

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

                    CamlQuery camlQuery = new CamlQuery();
                    camlQuery.ViewXml = @"<View Scope='Recursive'><Query></Query></View>";
                    camlQuery.FolderServerRelativeUrl = "/teams/VenuProject13102018/Shared%20Documents";

                    ListItemCollection listitems = list.GetItems(camlQuery);

                    clientContext.Load(listitems, items => items.Include(i => i["Title"]));
                    clientContext.ExecuteQuery();
                    for (int i = 0; i < listitems.Count; i++)
                    {
                        SP.ListItem itemOfInterest = listitems[i];
                        if (itemOfInterest["Title"] != null)
                        {
                            string fileName = itemOfInterest["Title"].ToString();
                            if (i == 0)
                            {
                                ReadExcelData(clientContext, fileName);
                            }
                        }
                    }
                    IsError = false;
                }
                catch (Exception e)
                {
                    IsError = true;
                    Console.WriteLine(e.Message);
                    Console.WriteLine("first catch block main");
                }
                finally
                {
                    if (IsError)
                    {
                    }
                }
                Console.ReadKey();
            }
        }
Esempio n. 26
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");
        }
Esempio n. 27
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");
        }
Esempio n. 28
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();
        }
Esempio n. 29
0
        public ListItem GetServiceDeskListItem(int id)
        {
            Web  site            = context.Web;
            List serviceDeskList = site.Lists.GetByTitle("ServiceDesk Requests");

            Microsoft.SharePoint.Client.ListItem serviceDeskItem = serviceDeskList.GetItemById(id);
            context.Load(serviceDeskItem, item => item["Title"], item => item["Subject"], item => item["Body"], item => item["From"]);
            context.ExecuteQuery();

            return(serviceDeskItem);
        }
Esempio n. 30
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");
        }
        private string ElementSelector(Model.Field field, ListItem item)
        {
            if (!item.FieldValues.ContainsKey(field.InternalName)) return null;

            var value = item.FieldValues[field.InternalName];
            if (value == null) return null;

            switch (field.Type)
            {
                case Model.FieldType.Lookup:
                    if (value is FieldLookupValue) return Converter.LookupValueToString((FieldLookupValue)value);
                    if (value is FieldLookupValue[]) return Converter.LookupCollectionValueToString((FieldLookupValue[])value);
                    return value.ToString();

                case Model.FieldType.User:
                    if (value is FieldUserValue) return Converter.LookupValueToString((FieldUserValue)value);
                    if (value is FieldUserValue[]) return Converter.LookupCollectionValueToString((FieldUserValue[])value);
                    return value.ToString();

                case Model.FieldType.Url:
                    if (value is FieldUrlValue) return Converter.UrlValueToString((FieldUrlValue)value);
                    return value.ToString();

                case Model.FieldType.MultiChoice:
                    if (value is string[]) return Converter.ChoiceMultiValueToString((string[])value);
                    return value.ToString();

                case Model.FieldType.DateTime:
                    return ((DateTime)value).ToLocalTime().ToString(CultureInfo.CurrentCulture);

                case Model.FieldType.Taxonomy:
                    if (value is TaxonomyFieldValue) return Converter.TaxonomyValueToString((TaxonomyFieldValue) value);
                    if (value is TaxonomyFieldValueCollection) return Converter.TaxonomyCollectionValueToString((TaxonomyFieldValueCollection)value);
                    return value.ToString();

                default:
                    return value.ToString();

            }
        }