/// <summary> /// Initializes Site Combo box /// </summary> private void InitializeDynamicSiteComboBox() { using (var clientContext = new ClientContext(System.Configuration.ConfigurationManager.AppSettings["SiteURL"])) { SecureString securePassWd = new SecureString(); foreach (var c in this.OUser.Password.ToCharArray()) { securePassWd.AppendChar(c); } clientContext.Credentials = new SharePointOnlineCredentials(this.OUser.UserName, securePassWd); Microsoft.SharePoint.Client.List siteList = clientContext.Web.Lists.GetByTitle(ConfigurationManager.AppSettings["SiteListName"]); clientContext.Load(siteList, list => list.DefaultViewUrl); CamlQuery query = CamlQuery.CreateAllItemsQuery(100); Microsoft.SharePoint.Client.ListItemCollection items = siteList.GetItems(query); clientContext.Load(items); clientContext.ExecuteQuery(); foreach (Microsoft.SharePoint.Client.ListItem listItem in items) { cbx_Site.Items.Add(listItem["Name"].ToString()); } this.cbx_Site.SelectedIndex = -1; this.cbx_Site.Text = "Select Site"; } }
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; }
private async Task Update_List_failed(string candidateID) { try { Microsoft.SharePoint.Client.List list = ctx.Web.Lists.GetByTitle(quizListName); ctx.Load(list); //CamlQuery camlQuery = new CamlQuery(); //camlQuery.ViewXml= "<View><Query><Where><Geq><FieldRef Name='CandidateID'/>" + //"<Value Type='Text'>"+candidateID+"</Value></Geq></Where></Query><RowLimit>100</RowLimit></View>"; Microsoft.SharePoint.Client.ListItemCollection listitems = list.GetItems(CreateCandidateQuery(CandID, CandName.Split('_')[0])); ctx.Load(listitems); ctx.ExecuteQuery(); foreach (ListItem oListItem in listitems) { oListItem["Hire_Status"] = "Failed"; oListItem["Remaining_Test"] = ""; //newItem["FolderUrl"] = folder.ServerRelativeUrl; oListItem.Update(); } await Task.Delay(1000); } catch (Exception ex) { throw ex; } }
public spClient.ListItemCollection getSharePointData(string subProjectRiskUrl, string query) { spClient.ListItemCollection collectionList = null; try { string[] validUrlApi = subProjectRiskUrl.Split(new string[] { "/Lists/" }, StringSplitOptions.None); string newriskUrl = subProjectRiskUrl; if (validUrlApi.Length != 0) { newriskUrl = validUrlApi[0] + "/"; } using (spClient.ClientContext ctx = new spClient.ClientContext(newriskUrl)) { var passWord = new SecureString(); foreach (var c in "intel@123") { passWord.AppendChar(c); } ctx.Credentials = new spClient.SharePointOnlineCredentials("*****@*****.**", passWord); spClient.Web myWeb = ctx.Web; spClient.List proList = myWeb.Lists.GetByTitle("Risk List"); spClient.CamlQuery myQuery = new spClient.CamlQuery(); myQuery.ViewXml = query; collectionList = proList.GetItems(myQuery); ctx.Load(collectionList); ctx.ExecuteQuery(); } } catch (Exception e) { collectionList = null; } return(collectionList); }
public void DeleteItemByQuery(string ListName, ICamlQuery Query) { try { SP.Web web = context.Web; SP.List list = web.Lists.GetByTitle(ListName); SP.CamlQuery query = (SP.CamlQuery)Query.ExecuteQuery(); SP.ListItemCollection items = list.GetItems(query); context.Load(items); context.ExecuteQuery(); if (items != null) { foreach (SP.ListItem item in items) { item.DeleteObject(); context.Load(item); } context.ExecuteQuery(); } else { throw new Exception("Item does not exist"); } } catch (Exception ex) { throw new Exception("Error updating SharePoint list data: " + ex.Message); } }
static string GetDepartment(ClientContext clientContext, int id) { Microsoft.SharePoint.Client.List spList = clientContext.Web.Lists.GetByTitle("People"); clientContext.Load(spList); clientContext.ExecuteQuery(); if (spList != null && spList.ItemCount > 0) { Microsoft.SharePoint.Client.CamlQuery camlQuery = new CamlQuery(); camlQuery.ViewXml = @"<View> <Query> <Where><Eq><FieldRef Name='Employee' LookupId='True' /><Value Type='Integer'>23</Value></Eq></Where> </Query> </View>"; ListItemCollection listItems = spList.GetItems(camlQuery); clientContext.Load(listItems); clientContext.ExecuteQuery(); var dep = (FieldLookupValue)listItems[0]["Department_x0020_name"]; return(dep.LookupValue); } return("DepNotFound"); }
public bool SearchForEventByTitleOnWSS(string strTitle) { CamlQuery camlQuery = new CamlQuery(); camlQuery.ViewXml = String.Format( "<View><Query><Where><Eq><FieldRef Name='Title'/>" + "<Value Type='Text'>{0}</Value></Eq></Where></Query>" + "</View>", strTitle); ListItemCollection collListItem = oList.GetItems(camlQuery); clientContext.Load(collListItem); clientContext.ExecuteQuery(); if (collListItem.Count > 1) { Console.WriteLine("Error: The list contains {0} calendar events with the same title \"{1}\"", collListItem.Count, strTitle); Environment.Exit(3); } else if (collListItem.Count == 0) { return(false); } oListItem = collListItem[0]; return(true); }
public EmployeeModel CheckNewEntry(string EMPCode, string siteUrl) { int returnVal = 0; EmployeeModel employeeModels = new EmployeeModel(); using (MSC.ClientContext context = GetContext(siteUrl)) { var dataDateValue = DateTime.Today; MSC.List list = context.Web.Lists.GetByTitle("TIM_DailyAttendance"); MSC.ListItemCollectionPosition itemPosition = null; var q = new CamlQuery() { ViewXml = "<View><Query><Where><And><Eq><FieldRef Name='EmpNo' /><Value Type='Text'>" + EMPCode + "</Value></Eq><Eq><FieldRef Name='AttendanceDate' /><Value Type='Text'>" + dataDateValue.ToString("dd-MM-yyyy") + "</Value></Eq></And></Where></Query></View>" }; MSC.ListItemCollection Items = list.GetItems(q); context.Load(Items); context.ExecuteQuery(); itemPosition = Items.ListItemCollectionPosition; returnVal = Items.Count; if (returnVal > 0) { employeeModels.ID = Items[0]["ID"].ToString(); employeeModels.count = Items.Count; } else { employeeModels.count = Items.Count; } } return(employeeModels); }
private static bool UpdateServiceResponse(string invoiceNO) { bool status = false; try { using (ClientContext context = new ClientContext(spurl)) { SecureString Password = new SecureString(); foreach (char c in pwd) { Password.AppendChar(c); } CamlQuery query = new CamlQuery(); query.ViewXml = "<View><Query><Where><Eq><FieldRef Name='ID' /><Value Type='Text'>" + invoiceNO + "</Value></Eq></Where></Query></View>"; context.Credentials = new NetworkCredential(UserName, Password); Microsoft.SharePoint.Client.List invoiceSharePointList = context.Web.Lists.GetByTitle("Invoice"); ListItemCollection invoiceListItem = invoiceSharePointList.GetItems(query); context.Load(invoiceListItem); context.ExecuteQuery(); var item = invoiceListItem[0]; item["Invoice_x0020_Status"] = "Pushed"; item.Update(); context.ExecuteQuery(); status = true; } } catch (Exception ex) { throw; } return(status); }
/// <summary> /// Initializes Analyst Combo box /// </summary> private void InitializeDynamicUserComboBox() { using (var clientContext = new ClientContext(System.Configuration.ConfigurationManager.AppSettings["G23SiteURL"])) { SecureString securePassWd = new SecureString(); foreach (var c in this.OUser.Password.ToCharArray()) { securePassWd.AppendChar(c); } clientContext.Credentials = new SharePointOnlineCredentials(this.OUser.UserName, securePassWd); Microsoft.SharePoint.Client.List siteList = clientContext.Web.Lists.GetByTitle(ConfigurationManager.AppSettings["G23UserListName"]); clientContext.Load(siteList, list => list.DefaultViewUrl); CamlQuery query = CamlQuery.CreateAllItemsQuery(100); Microsoft.SharePoint.Client.ListItemCollection items = siteList.GetItems(query); clientContext.Load(items); clientContext.ExecuteQuery(); usersRadDropDownList.Items.Add("Select User"); foreach (Microsoft.SharePoint.Client.ListItem listItem in items) { //Yes = True, No = False if (listItem["Active"].ToString() == "True") { usersRadDropDownList.Items.Add(listItem["Name"].ToString()); } } //Set default item usersRadDropDownList.SelectedIndex = 0; } }
private void AddFolder(string strFileDirRef, string strfileref, string strfileleafref) { string filePath = strfileref.Substring(strfileref.IndexOf(libName)); //Remove the filename string DirectoryPath = filePath; DirectoryPath = DirectoryPath.Replace("/", "\\"); //create the directory path if (!string.IsNullOrEmpty(DirectoryPath) && chkFolders.Checked) { Directory.CreateDirectory(tmpDirLocation + DirectoryPath); foldercount++; } var clientContext = getClientContext(); Microsoft.SharePoint.Client.List library = clientContext.Web.Lists.GetById(new Guid(hostListId.ToString())); CamlQuery camlQuery = new CamlQuery(); camlQuery = new CamlQuery(); string strQuery = @"<View Scope='RecursiveAll'> <Query> <Where> <Eq> <FieldRef Name='FileDirRef'/> <Value Type='Text'>/" + @strfileref + @"</Value> </Eq> </Where> </Query> </View>"; camlQuery.ViewXml = strQuery; Microsoft.SharePoint.Client.ListItemCollection listItems = library.GetItems(camlQuery); clientContext.Load(listItems); clientContext.ExecuteQuery(); if (listItems.Count > 0) { foreach (var item in listItems) { var fileref = item["FileRef"].ToString(); var fileleafref = item["FileLeafRef"].ToString(); if (!fileleafref.Contains('.')) { var FileDirRef = item["FileDirRef"].ToString(); AddFolder(FileDirRef, fileref, fileleafref); } else { AddFile(fileref, item.File, clientContext); } } } }
private void share_Click(object sender, RoutedEventArgs e) { string[] attr = { "Project Lead|Text", "Project Team|Text", "External ID|Numeric", "Priority|Numberic", "Value Stream/LOB|List", "RAG Status|List", "Percent Complete|Numeric", "Due Date|Date", "New Requested Budget|Numeric", "Appropriated Budget|Numeric", "Project Business Value|Text", "Project Dependencies/Assumptions/Risks|Text", "Status Comments|Text", "Total Spent to Date|Numberic", "Financial Comments|Text" }; // Load from App.Config string sharpCloudUsername = shareSharpUsername.Text; string sharpCloudPassword = shareSharpPassword.Password.ToString(); string sharePointUsername = shareUsername.Text; string sharePointPassword = sharePassword.Password.ToString(); string sharePointSite = "https://hawaiioimt.sharepoint.com/sites/ets"; // Login into sharpcloud var sc = new SharpCloudApi(); try { sc = new SharpCloudApi(sharpCloudUsername, sharpCloudPassword); } catch { MessageBox.Show("Incorrect Sharpcloud info"); return; } Story story = sc.LoadStory(shareStory.Text); // Login into Sharepoint var securePassword = new SecureString(); foreach (var character in sharePointPassword) { securePassword.AppendChar(character); } securePassword.MakeReadOnly(); var sharePointCredentials = new SharePointOnlineCredentials(sharePointUsername, securePassword); ClientContext context = new ClientContext(sharePointSite); context.Credentials = sharePointCredentials; Microsoft.SharePoint.Client.List list = context.Web.Lists.GetByTitle("Projects"); // Setup query CamlQuery query = new CamlQuery(); query.ViewXml = "<View/>"; Microsoft.SharePoint.Client.ListItemCollection items = list.GetItems(query); // Loads list context.Load(list); context.Load(items); context.ExecuteQuery(); // Goes through List // Adds Attribute to story if none exist addAttribute(story, attr); // Goes through List Items foreach (var item in items) { addItem(story, item, attr); } story.Save(); }
public void GetTasks() { Tasks.Clear(); CLOM.List taskList = context.Web.Lists.GetByTitle("Tasks"); CLOM.CamlQuery query = new CLOM.CamlQuery(); taskListItems = taskList.GetItems(query); context.Load(taskListItems); context.ExecuteQueryAsync(onQuerySucceeded, onQueryFailed); }
private void Load(string listName) { oList = context.Web.Lists.GetByTitle(listName); CamlQuery camlQuery = new CamlQuery(); camlQuery.ViewXml = @"<View><RowLimit>100</RowLimit></View>"; ListItemCollection collListItem = oList.GetItems(camlQuery); context.Load(collListItem, items => items.Include(item => item.Id, item => item.DisplayName, item => item.FieldValuesForEdit)); context.ExecuteQuery(); foreach (ListItem oListItem in collListItem) { string lang = oListItem.FieldValuesForEdit.FieldValues["ProgrammingLanguages"]; Employees.Add(new Employee() { Id = oListItem.Id, Title = oListItem.FieldValuesForEdit.FieldValues["Title"], Email = oListItem.FieldValuesForEdit.FieldValues["EmailAdd"], ShortDescription = oListItem.FieldValuesForEdit.FieldValues["ShortDesc"], FirstName = oListItem.FieldValuesForEdit.FieldValues["FirstName"], Languages = new ObservableCollection <Language>() { new Language() { LanguageName = ScreenConstants.CSharp, IsChecked = IsContain(lang, ScreenConstants.CSharp) }, new Language() { LanguageName = ScreenConstants.FSharp, IsChecked = IsContain(lang, ScreenConstants.FSharp) }, new Language() { LanguageName = ScreenConstants.VisualBasic, IsChecked = IsContain(lang, ScreenConstants.VisualBasic) }, new Language() { LanguageName = ScreenConstants.Java, IsChecked = IsContain(lang, ScreenConstants.Java) }, new Language() { LanguageName = ScreenConstants.Jquery, IsChecked = IsContain(lang, ScreenConstants.Jquery) }, new Language() { LanguageName = ScreenConstants.AngularJS, IsChecked = IsContain(lang, ScreenConstants.AngularJS) }, new Language() { LanguageName = ScreenConstants.Other, IsChecked = IsContain(lang, ScreenConstants.Other) } } }); } employeeGrid.ItemsSource = Employees; }
public static List <Employee> GetEnterEstimate(string month, string year, string listname, string siteUrl) { List <Employee> _returnEmployee = new List <Employee>(); try { using (MSC.ClientContext context = CustomSharePointUtility.GetContext(siteUrl)) { if (context != null) { MSC.List SalesEstimateEmployee = context.Web.Lists.GetByTitle(listname); MSC.ListItemCollectionPosition itemPosition = null; string fromday = year + "-" + month + "-" + "1"; string Today = year + "-" + month + "31"; while (true) { MSC.CamlQuery camlQuery = new MSC.CamlQuery(); camlQuery.ListItemCollectionPosition = itemPosition; camlQuery.ViewXml = @"<View><Query><Where> <Eq><FieldRef Name='Date' /> <Value IncludeTimeValue='FLASE' Type='DateTime'>" + fromday + "</Value></Eq>"; camlQuery.ViewXml += @" </Where></Query> <RowLimit>5000</RowLimit> <FieldRef Name='ID'/> <FieldRef Name='EmployeeName'/> <FieldRef Name='Author'/> <FieldRef Name='Created'/> </View>"; MSC.ListItemCollection Items = SalesEstimateEmployee.GetItems(camlQuery); context.Load(Items); context.ExecuteQuery(); itemPosition = Items.ListItemCollectionPosition; foreach (MSC.ListItem item in Items) { _returnEmployee.Add(new Employee { EmployeeName = Convert.ToString((item["EmployeeName"] as Microsoft.SharePoint.Client.FieldUserValue).LookupValue), EmployeeID = Convert.ToString((item["EmployeeName"] as Microsoft.SharePoint.Client.FieldUserValue).LookupId) }); } if (itemPosition == null) { break; // TODO: might not be correct. Was : Exit While } } } } } catch (Exception ex) { } return(_returnEmployee); }
public void ProcessRequest(HttpContext context) { StringBuilder sb = new StringBuilder(); context.Response.ContentType = "text/plain"; string tekst = ""; string user = context.Request["user"]; if (!string.IsNullOrEmpty(user)) { string siteUrl = "http://SP2013/"; ClientContext clientContext = new ClientContext(siteUrl); CredentialCache cc = new CredentialCache(); cc.Add(new Uri(siteUrl), "NTLM", new NetworkCredential("apawlowski", "cbv3.560671bf", "valvex")); clientContext.Credentials = cc; clientContext.AuthenticationMode = SP.ClientAuthenticationMode.Default; SP.List oList = clientContext.Web.Lists.GetById(new Guid("FEB89E30-253D-45FF-A213-C6FCBD8FDC52")); Microsoft.SharePoint.Client.ListItemCollection col = oList.GetItems(CamlQuery.CreateAllItemsQuery()); clientContext.Load(col); clientContext.ExecuteQuery(); int licznik = 5000; sb.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><AddressBook>\t<pbgroup>\t\t<id>4</id>\t<name>Blacklist</name>\t\t</pbgroup>"); sb.Append("<pbgroup>\t<id>5</id>\t<name>Whitelist</name>\t</pbgroup>\t<pbgroup>\t<id>6</id>\t<name>Work</name>\t</pbgroup>\t<pbgroup>\t"); sb.Append("<id>7</id>\t<name>Friends</name>\t</pbgroup>\t<pbgroup>\t<id>8</id>\t<name>Family</name>\t</pbgroup>\t"); foreach (Microsoft.SharePoint.Client.ListItem l in col) { if (l["_x0064_hf7"].ToString() == "publiczny" || l["_x0064_hf7"].ToString() == user) { sb.Append($"<Contact>\t<id>{licznik++}</id>\t<FirstName>{l["Title"].ToString()}</FirstName>\t<LastName>{(l["FirstName"] == null ? "" : l["FirstName"].ToString())}</LastName>\t<Frequent>0</Frequent>"); sb.Append($"<Phone type=\"Work\"><phonenumber>{(l["WorkPhone"] == null ? "" : l["WorkPhone"].ToString())}</phonenumber>\t<accountindex>1</accountindex>"); sb.Append($"</Phone>\t<Group>6</Group>\t<Primary>0</Primary>\t<Company>valvex</Company>\t</Contact>\t"); } } sb.Append("\t</AddressBook>"); string tekst16 = sb.ToString(); byte[] bytes = Encoding.Default.GetBytes(tekst16); tekst = Encoding.UTF8.GetString(bytes); tekst = tekst.Replace("ą", "a").Replace("ć", "c").Replace("ę", "e").Replace("ł", "l").Replace("ś", "s").Replace("ń", "n").Replace("ó", "o").Replace("ż", "z").Replace("ź", "z"); tekst = tekst.Replace("Ą", "A").Replace("Ć", "C").Replace("Ę", "E").Replace("Ł", "L").Replace("Ś", "S").Replace("Ń", "N").Replace("Ó", "O").Replace("Ż", "Z").Replace("Ź", "Z"); } context.Response.Write(tekst); }
private string getSharePointNewIteminLastNSeconds() { string siteUrl = txtSharePointServer.Text; ClientContext clientContext = new ClientContext(siteUrl); SP.List oList = clientContext.Web.Lists.GetByTitle(txtTargetList.Text); CamlQuery camlQuery = new CamlQuery(); DateTime endDate = DateTime.Now; DateTime startDate = endDate.AddSeconds(-5); string startDateFx = startDate.ToString("yyyy-MM-ddTHH:mm:ssZ"); string endDatFx = endDate.ToString("yyyy-MM-ddTHH:mm:ssZ"); camlQuery.ViewXml = //"<View><Query><Where><Geq><FieldRef Name='ID'/>" + //"<Value Type='Number'>10</Value></Geq></Where></Query><RowLimit>1</RowLimit></View>"; @"<View>" + "<Query>" + "<Where> <And>" + "<Geq>" + "<FieldRef Name='DueDate'/>" + "<Value Type='DateTime' IncludeTimeValue='FALSE'>" + startDateFx + "</Value>" + "</Geq>" + "<Leq>" + "<FieldRef Name='DueDate'/>" + "<Value Type='DateTime' IncludeTimeValue='FALSE'>" + endDatFx + "</Value>" + "</Leq>" + "</And> </Where>" + "</Query>" + "</View>"; ListItemCollection collListItem = oList.GetItems(camlQuery); clientContext.Load(collListItem); try { clientContext.ExecuteQuery(); } catch (Exception) { richTextBox1.Text += "\n>> list " + txtTargetList + " not exist."; SaveLogs(); } string r = ""; foreach (ListItem oListItem in collListItem) { r = string.Format("ID: {0} \nTitle: {1} \nBody: {2}", oListItem.Id, oListItem["Title"], oListItem["Body"]); } return(r); }
public static SP.ListItemCollection GetViewItemsFromList(SP.ClientContext context, SP.List list, SP.View view) { SP.ListItemCollection items = null; SP.CamlQuery query = new SP.CamlQuery(); query.ViewXml = view.ViewQuery; items = list.GetItems(query); context.Load(items); context.ExecuteQuery(); return(items); }
public string uniqueid(string id) { string login = "******"; //give your username here string password = "******"; //give your password var securePassword = new SecureString(); foreach (char c in password) { securePassword.AppendChar(c); } string server = "https://ectacae.sharepoint.com/sites/ECTPortal/eservices/studentservices"; var ctx = new ClientContext(server); var web = ctx.Web; Microsoft.SharePoint.Client.List lists = web.Lists.GetByTitle("Students_Requests"); var listItemCollection = lists.GetItems(CamlQuery.CreateAllItemsQuery()); // always use QueryTrimming to minimize size of // data that has to be transfered ctx.Load(listItemCollection, eachItem => eachItem.Include( item => item, item => item["Title"])); // ExecuteQuery will pull all data from SharePoint // which has been staged to Load() var onlineCredentials = new SharePointOnlineCredentials(login, securePassword); ctx.Credentials = onlineCredentials; ctx.ExecuteQuery(); DataTable dtid = new DataTable(); dtid.Clear(); dtid.Columns.Add("ID"); foreach (Microsoft.SharePoint.Client.ListItem listItem in listItemCollection) { DataRow dr = dtid.NewRow(); dr["ID"] = listItem["Title"].ToString(); dtid.Rows.Add(dr); } DataRow[] foundRows = dtid.Select("ID='" + id + "'"); if (foundRows.Count() > 0) { Create16DigitString(); return("false"); } else { return("true"); } }
static void Main(string[] args) { using (var clientContext = new ClientContext(adminUrl)) { clientContext.Credentials = new SharePointOnlineCredentials(userName, password); clientContext.Load(clientContext.Web, w => w.Webs); Microsoft.SharePoint.Client.List spList = clientContext.Web.Lists.GetByTitle("Quotation Log"); clientContext.Load(spList); clientContext.ExecuteQuery(); if (spList != null && spList.ItemCount > 0) { Microsoft.SharePoint.Client.CamlQuery camlQuery = new CamlQuery(); camlQuery.ViewXml = @"<View> <Query> <Where><And><Gt><FieldRef Name='Quotation_x0020_Number' /><Value Type='Number'>16000</Value></Gt><IsNull><FieldRef Name='Quote_x0020_Link' /></IsNull></And></Where> </Query> </View>"; ListItemCollection listItems = spList.GetItems(camlQuery); clientContext.Load(listItems); clientContext.Load(listItems, itema => itema.Include( ttt => ttt, ttt => ttt["Customer"], ttt => ttt.Id, ttt => ttt["Quotation_x0020_Number"])); clientContext.ExecuteQuery(); Console.WriteLine(listItems.Count); Console.ReadLine(); foreach (var item in listItems) { string cust = ""; FieldLookupValue ff = (FieldLookupValue)item["Customer"]; if (ff.LookupValue == "*") { cust = "--"; } else { cust = ff.LookupValue; } Console.WriteLine(item["Quotation_x0020_Number"] + " " + ff.LookupValue + " " + item.Id); string url = SetupQuotSite(item["Quotation_x0020_Number"].ToString(), cust, item.Id, clientContext); FixUrlForItem(url, item.Id); } } } }
//public static List<PurchaseOrder> GetAll_PurchaseOrderFromSharePoint(string siteUrl, string listName, string DaysDifference) //{ // List<PurchaseOrder> _retList = new List<PurchaseOrder>(); // try // { // using (MSC.ClientContext context = CustomSharePointUtility.GetContext(siteUrl)) // { // if (context != null) // { // MSC.List list = context.Web.Lists.GetByTitle(listName); // MSC.ListItemCollectionPosition itemPosition = null; // while (true) // { // var dataDateValue = DateTime.Now.AddDays(-Convert.ToInt32(DaysDifference)); // MSC.CamlQuery camlQuery = new MSC.CamlQuery(); // camlQuery.ListItemCollectionPosition = itemPosition; // camlQuery.ViewXml = @"<View> // <Query> // <Where> // <And> // <Or> // <Or> // <Eq> // <FieldRef Name='ApprovalStatus'/> // <Value Type='text'>Submitted</Value> // </Eq> // <Eq> // <FieldRef Name='ApprovalStatus'/> // <Value Type='text'>Approved By Functional Head</Value> // </Eq> // </Or> // <Or> // <Eq> // <FieldRef Name='ApprovalStatus'/> // <Value Type='text'>Approved By Purchase Head</Value> // </Eq> // <Eq> // <FieldRef Name='ApprovalStatus'/> // <Value Type='text'>Approved By Plant Head</Value> // </Eq> // </Or> // </Or> // <Leq><FieldRef Name='Modified'/><Value Type='DateTime'>" + dataDateValue.ToString("o") + "</Value></Leq>"; // camlQuery.ViewXml += @"</And></Where></Query> // <RowLimit>5000</RowLimit> // <ViewFields> // <FieldRef Name='ID'/> // <FieldRef Name='POReferenceNumber'/> // <FieldRef Name='Author'/> // <FieldRef Name='Created'/> // <FieldRef Name='DepartmentName'/> // <FieldRef Name='DepartmentID'/> // <FieldRef Name='LocationName'/> // <FieldRef Name='LocationID'/> // <FieldRef Name='LocationType'/> // <FieldRef Name='DivisionName'/> // <FieldRef Name='DivisionID'/> // <FieldRef Name='PONumber'/> // <FieldRef Name='POCost'/> // <FieldRef Name='MaterialDetails'/> // <FieldRef Name='ApprovalStatus'/> // <FieldRef Name='FHCode'/> // <FieldRef Name='Modified'/> // </ViewFields></View>"; // MSC.ListItemCollection Items = list.GetItems(camlQuery); // context.Load(Items); // context.ExecuteQuery(); // itemPosition = Items.ListItemCollectionPosition; // foreach (MSC.ListItem item in Items) // { // _retList.Add(new PurchaseOrder // { // Id = Convert.ToInt32(item["ID"]), // POReferenceNumber = Convert.ToString(item["POReferenceNumber"]).Trim(), // Author = Convert.ToString((item["Author"] as Microsoft.SharePoint.Client.FieldUserValue).LookupValue), // Created = Convert.ToString(item["Created"]).Trim(), // DepartmentName = Convert.ToString(item["DepartmentName"]).Trim(), // DepartmentID = Convert.ToString(item["DepartmentID"]).Trim(), // LocationName = Convert.ToString(item["LocationName"]).Trim(), // LocationID = Convert.ToString(item["LocationID"]).Trim(), // LocationType = Convert.ToString(item["LocationType"]).Trim(), // ////Author = Convert.ToString((item["Author"] as Microsoft.SharePoint.Client.FieldUserValue).LookupId), // //Author = Convert.ToString((item["Author"] as Microsoft.SharePoint.Client.FieldUserValue).LookupValue), // //FunctionalHead = Convert.ToString((item["FunctionalHead"] as Microsoft.SharePoint.Client.FieldUserValue[])[0].LookupId), // //HRHead = Convert.ToString((item["HRHead"] as Microsoft.SharePoint.Client.FieldUserValue[])[0].LookupId), // //HRHeadOnly = Convert.ToString((item["HRHeadOnly"] as Microsoft.SharePoint.Client.FieldUserValue).LookupId), // //MDorJMD = item["MDorJMD"] == null ? "" : Convert.ToString((item["MDorJMD"] as Microsoft.SharePoint.Client.FieldUserValue).LookupId), // //Recruiter = Convert.ToString((item["Recruiter"] as Microsoft.SharePoint.Client.FieldUserValue[])[0].LookupId), // DivisionName = Convert.ToString(item["DivisionName"]).Trim(), // DivisionID = Convert.ToString(item["DivisionID"]).Trim(), // PONumber = Convert.ToString(item["PONumber"]).Trim(), // POCost = Convert.ToString(item["POCost"]).Trim(), // MaterialDetails = Convert.ToString(item["MaterialDetails"]).Trim(), // ApprovalStatus = Convert.ToString(item["ApprovalStatus"]).Trim(), // FHCode = Convert.ToString(item["FHCode"]).Trim(), // Modified = Convert.ToString(item["Modified"]).Trim(), // }); // } // if (itemPosition == null) // { // break; // TODO: might not be correct. Was : Exit While // } // } // } // } // } // catch (Exception ex) // { // CustomSharePointUtility.WriteLog("Error in GetAll_ManpowerRequisitionFromSharePoint()" + " Error:" + ex.Message); // } // return _retList; //} #endregion /// New Code to Get Employee /// public static List <Employee> GetEmployees(string siteUrl, string listName) { List <Employee> _returnEmployee = new List <Employee>(); try { using (MSC.ClientContext context = CustomSharePointUtility.GetContext(siteUrl)) { if (context != null) { MSC.List HODList = context.Web.Lists.GetByTitle(listName); MSC.ListItemCollectionPosition itemPosition = null; while (true) { MSC.CamlQuery camlQuery = new MSC.CamlQuery(); camlQuery.ListItemCollectionPosition = itemPosition; camlQuery.ViewXml = @"<View><Query><Where> <Eq><FieldRef Name='Reminder' /><Value Type='Choice'>Yes</Value></Eq> </Where></Query> <RowLimit>5000</RowLimit> <FieldRef Name='ID'/> <FieldRef Name='EmployeeName'/> <FieldRef Name='Author'/> <FieldRef Name='Created'/> </View>"; MSC.ListItemCollection Items = HODList.GetItems(camlQuery); context.Load(Items); context.ExecuteQuery(); itemPosition = Items.ListItemCollectionPosition; foreach (MSC.ListItem item in Items) { _returnEmployee.Add(new Employee { EmployeeName = Convert.ToString((item["EmployeeName"] as Microsoft.SharePoint.Client.FieldUserValue).LookupValue), EmployeeID = Convert.ToString((item["EmployeeName"] as Microsoft.SharePoint.Client.FieldUserValue).LookupId) }); } if (itemPosition == null) { break; // TODO: might not be correct. Was : Exit While } } } } } catch (Exception ex) { } return(_returnEmployee); }
protected static Microsoft.SharePoint.Client.ListItemCollection GetListItems(ClientContext context, Microsoft.SharePoint.Client.List list, CamlQuery query) { Microsoft.SharePoint.Client.ListItemCollection coll = null; coll = list.GetItems(query); context.Load(coll); context.ExecuteQuery(); return(coll); }
private int?GetIdByTitle(string title) { try { using (ClientContext clientContext = new ClientContext(_configuration.TenantUrl)) { SecureString passWord = new SecureString(); foreach (char c in _configuration.Password.ToCharArray()) { passWord.AppendChar(c); } clientContext.Credentials = new SharePointOnlineCredentials(_configuration.EmailAccount, passWord); List list = clientContext.Web.Lists.GetByTitle(_configuration.ListTitle); CamlQuery camlQuery = new CamlQuery(); camlQuery.ViewXml = string.Format($@" <View> <Query> <Where> <Eq> <FieldRef Name='Title' /> <Value Type='Text'>{title}</Value> </Eq> </Where> </Query> <ViewFields> <FieldRef Name='ID'/> <FieldRef Name='Title'/> </ViewFields> <RowLimit>1</RowLimit> </View>"); // reads the item with the specified caml query ListItemCollection itemCollection = list.GetItems(camlQuery); // tells the ClientContext object to load the collect, // while we define the fields that should be returned like: // Id, Title, SomeDate, OtherField and Modified clientContext.Load(itemCollection, items => items.Include( item => item.Id, item => item["Title"])); // executes everything that was loaded before (the itemCollection) clientContext.ExecuteQuery(); // iterates the list printing the title and another field of each list item foreach (ListItem item in itemCollection) { return(item.Id); } } } catch (Exception ex) { _log.Error($"-> GetIdByTitle no processo: SharepointSyncJob: {ex}", ex); } return(null); }
public void DynamicHamburgerLinks() { string FileRef = String.Empty; string SiteName = String.Empty; string RedirectLink = String.Empty; string ElementType = String.Empty; string GlobalURL = ConfigurationManager.AppSettings["GlobalSearchURL"]; // string CurrentURL = SPContext.Current.Site.Url; /*Gets the current URL of the Sitecollection*/ string AccountUsername = ConfigurationManager.AppSettings["AccountUsername"]; string AccountPassword = ConfigurationManager.AppSettings["AccountPassword"]; string AccountDomain = ConfigurationManager.AppSettings["AccountDomain"]; HtmlGenericControl oCSS = new HtmlGenericControl(); /*Set the Css from the Library Elements */ using (ClientContext clientContext = new ClientContext(GlobalURL)) { NetworkCredential Credentials = new System.Net.NetworkCredential(AccountUsername, AccountPassword, AccountDomain); clientContext.Credentials = Credentials; Web web = clientContext.Web; clientContext.Load(web); Microsoft.SharePoint.Client.List siteList = web.Lists.GetByTitle("CentralNavigationAssets"); clientContext.Load(siteList); CamlQuery camlQuery = new CamlQuery(); camlQuery.ViewXml = @"<View><Query><Where><And><Eq><FieldRef Name='NavigationType'/><Value Type='Lookup'>Hamburger Menu Item</Value></Eq><Eq><FieldRef Name='Status'/><Value Type='Choice'>Active</Value></Eq></And></Where></Query></View>"; Microsoft.SharePoint.Client.ListItemCollection listCol = siteList.GetItems(camlQuery); clientContext.Load(listCol); clientContext.ExecuteQuery(); // Now update the list. foreach (Microsoft.SharePoint.Client.ListItem oListItem in listCol) { HamBurgerMenu.InnerHtml += "<li> <a href=" + oListItem["RedirectLink"] + " target=\"_blank\">" + (oListItem.FieldValues["SiteName"] as FieldLookupValue).LookupValue.ToString() + "</a> </li>"; } HamBurgerMenu.InnerHtml += "<li class=\"searchItem\"><input type=\"text\" name=\"q\" class=\"form-control\" placeholder=\"Search\" id=\"txtSearch\" onkeypress=\"handle(event)\"><span class=\"glyphicon glyphicon-search\" style=\"color:white\" onclick=\"RouteToSearch($('#txtSearch').val());\"> </span></li>"; } }
static Microsoft.SharePoint.Client.ListItemCollection GetSpListItems(Microsoft.SharePoint.Client.ClientContext ctx, string siteUrl, string listName, string camlXml)//string[] listFields) { Microsoft.SharePoint.Client.List list = ctx.Web.Lists.GetByTitle(listName); Microsoft.SharePoint.Client.CamlQuery camlQuery = new Microsoft.SharePoint.Client.CamlQuery() { ViewXml = camlXml }; Microsoft.SharePoint.Client.ListItemCollection lic = list.GetItems(camlQuery); ctx.Load(lic); ctx.ExecuteQuery(); return(lic); }
private static List <Invoice> GetInvoiceList() { SecureString Password = new SecureString(); foreach (char c in pwd) { Password.AppendChar(c); } List <Invoice> InvoiceList = new List <Invoice>(); try { using (ClientContext context = new ClientContext(spurl)) { DateTime yesterdayDate = DateTime.Now.AddDays(-1); CamlQuery query = new CamlQuery(); //query.ViewXml = "<View><Query><Where><Eq><FieldRef Name='Payment_x0020_Status' /><Value Type='Text'>Paid</Value></Eq><Eq><FieldRef Name='PaymentDate' /><Value Type='Text'>"+ yesterdayDate.ToString("s") + "</Value></Eq></Where></Query></View>"; query.ViewXml = "<View><Query><Where><Eq><FieldRef Name='Payment_x0020_Status' /><Value Type='Text'>Paid</Value></Eq></Where></Query></View>"; context.Credentials = new NetworkCredential(UserName, Password); Microsoft.SharePoint.Client.List invoiceSharePointList = context.Web.Lists.GetByTitle("Invoice"); ListItemCollection invoiceListItem = invoiceSharePointList.GetItems(query); context.Load(invoiceListItem); context.Load(invoiceSharePointList.RootFolder); context.ExecuteQuery(); if (invoiceListItem.Count > 0) { foreach (ListItem itmPass in invoiceListItem) { Invoice invoiceObject = new Invoice(); invoiceObject.InvoiceNO = Convert.ToString(itmPass["ID"]); invoiceObject.Date = Convert.ToString(Convert.ToDateTime(itmPass["Created"]).ToString("dd.MM.yyyy"));//put paymentDate Here invoiceObject.Year = Convert.ToString(Convert.ToDateTime(itmPass["Created"]).ToString("yyyy")); //invoiceObject.DocumentHeadReference = "REVENUE COLLECTIONS";//need to confirm invoiceObject.CreatedBY = Convert.ToString(itmPass["Author"]); invoiceObject.CreatedDate = Convert.ToString(Convert.ToDateTime(itmPass["Created"]).ToString("dd.MM.yyyy")); invoiceObject.CreatedTime = Convert.ToString(Convert.ToDateTime(itmPass["Created"]).ToString("HH:mm:ss")); invoiceObject.InvoiceDetails = GetInvoiceDetailList(invoiceObject.InvoiceNO); InvoiceList.Add(invoiceObject); } } } } catch (Exception ex) { throw; } return(InvoiceList); }
// load the product categories private void LoadProductCategories(object state) { SP.List categoryList = Globals.ClientContext.Web.Lists.GetByTitle("Product Categories"); SP.CamlQuery query = new SP.CamlQuery(); query.ViewXml = "<View><Query><OrderBy><FieldRef Name='Title' /></OrderBy></Query></View>"; Globals.ProductCategories = categoryList.GetItems(query); Globals.ClientContext.Load(Globals.ProductCategories); Globals.ClientContext.ExecuteQuery(); // fire the UI work on another thread this.Dispatcher.BeginInvoke(new Action(LoadProductCategoriesUIUpdater), DispatcherPriority.Normal); }
public static List <ErrorModel> GetActiveErrorList(string siteUrl, string listName) { List <ErrorModel> errorModels = new List <ErrorModel>(); try { using (MSC.ClientContext context = CustomSharePointUtility.GetContext(siteUrl)) { if (context != null) { MSC.List list = context.Web.Lists.GetByTitle(listName); MSC.ListItemCollectionPosition itemPosition = null; while (true) { MSC.CamlQuery camlQuery = new MSC.CamlQuery(); camlQuery.ListItemCollectionPosition = itemPosition; camlQuery.ViewXml = @"<View><Query><Where><Eq><FieldRef Name='SystemUpdated' /><Value Type='Choice'>No</Value></Eq></Where></Query><ViewFields><FieldRef Name='UserDisplayName' /><FieldRef Name='DisplayNo' /><FieldRef Name='URL' /><FieldRef Name='SystemUpdated' /><FieldRef Name='ID' /></ViewFields><QueryOptions /></View>"; MSC.ListItemCollection Items = list.GetItems(camlQuery); context.Load(Items); context.ExecuteQuery(); itemPosition = Items.ListItemCollectionPosition; foreach (MSC.ListItem item in Items) { errorModels.Add(new ErrorModel { ID = Convert.ToInt32(item["ID"]), URL = Convert.ToString(item["URL"]).Trim(), SystemUpdate = Convert.ToString(item["SystemUpdated"]).Trim(), }); } if (itemPosition == null) { break; // TODO: might not be correct. Was : Exit While } } } } } catch (Exception ex) { } return(errorModels); }
public void getEmailSubjectTypesFromSharePointOnline() { try { string siteUrl = Properties.Settings.Default.ClientContextUrl; using (var clientContext = new AuthenticationManager().GetAppOnlyAuthenticatedContext(siteUrl, Properties.Settings.Default.ClientId, Properties.Settings.Default.ClientSecret)) { Web oWebsite = clientContext.Web; ListCollection collList = oWebsite.Lists; SP.List oList = collList.GetByTitle("EmailSubject_Types"); ListItemCollection collListItem = oList.GetItems(new CamlQuery()); clientContext.Load(collListItem, items => items.Include( item => item.Id, item => item["Title"], item => item["Parent"], item => item["Code"])); clientContext.ExecuteQuery(); Globals.ThisAddIn.SubjectTypeList.Clear(); foreach (ListItem oListItem in collListItem) { string codeValue = ""; var s = GetSubjectTopicById(((Microsoft.SharePoint.Client.FieldLookupValue)oListItem["Parent"]).LookupId); if (s != null) { codeValue = s.Code; } SubjectTypeList.Add(new SubjectType() { ID = oListItem.Id, Title = oListItem["Title"].ToString(), Code = oListItem["Code"].ToString(), Parent = new SubjectTopic( ((Microsoft.SharePoint.Client.FieldLookupValue)oListItem["Parent"]).LookupId, codeValue, ((Microsoft.SharePoint.Client.FieldLookupValue)oListItem["Parent"]).LookupValue.ToString()) }); } }; } catch (Exception ex) { throw new Exception(ex.ToString()); } }
private void LoadItems(SP.ClientContext ctx, SP.List list, SP.View view) { SP.CamlQuery query = new SP.CamlQuery(); query.ViewXml = "<View>" + view.ViewQuery + "<RowLimit>" + txtResultsNumber.Text + "</RowLimit></View>"; var items = list.GetItems(query); ctx.Load(items, itms => itms.ListItemCollectionPosition , itms => itms.Include( itm => itm.FieldValuesAsText , itm => itm.ContentType ) ); ctx.ExecuteQuery(); progressBar1.Value++; DataTable tbl = new DataTable(); DataColumnCollection columns = tbl.Columns; DataRowCollection rows = tbl.Rows; if (items != null && items.Count > 0) { columns.Add("N.", typeof(System.String)); columns.Add("ContentType", typeof(System.String)); foreach (var fld in items[0].FieldValuesAsText.FieldValues) { columns.Add(fld.Key, typeof(System.String)); } int i = 1; foreach (var item in items) { DataRow row = tbl.NewRow(); row["N."] = i; row["ContentType"] = item.ContentType.Name; foreach (var fld in item.FieldValuesAsText.FieldValues) { if (fld.Value != null) { row[fld.Key] = item.FieldValuesAsText[fld.Key]; } } rows.Add(row); i++; } } dgResults.AutoGenerateColumns = true; dgResults.AutoSize = true; dgResults.DataSource = tbl; }