private void AddViews(frm_Data_View viewForm, string listId, string siteAddress, string siteName) { Guid g = new Guid(listId); SP.ClientContext clientContext = SharePoint.GetClient(siteAddress, frm_Main_Menu.username, frm_Main_Menu.password); SP.List oList = clientContext.Web.Lists.GetById(g); // Load in the Views clientContext.Load(oList.Views); clientContext.ExecuteQuery(); int i = 0; foreach (SP.View oView in oList.Views) { i++; clientContext.Load(oView.ViewFields); clientContext.ExecuteQuery(); string viewName = oView.Title; string viewId = oView.Id.ToString(); string fieldCount = oView.ViewFields.Count.ToString(); string rowLimit = oView.RowLimit.ToString(); string viewQuery = oView.ViewQuery; string url = frm_Main_Menu.siteUrl + oView.ServerRelativeUrl; viewForm.AddRow(i, viewName, siteName, siteAddress, fieldCount, rowLimit, viewId, viewQuery, url); lbl_Row_Count.Text = i.ToString() + " record(s) found"; lbl_Row_Count.Refresh(); } }
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); }
/// <summary> /// Retrieves the server-relative URL of a folder from its absolute URL. /// </summary> /// <param name="webUrl">Web URL to establish context.</param> /// <param name="folderUrl">folder URL</param> /// <param name="username">Username for SharePoint authentication.</param> /// <param name="password">Password for SharePoint authentication.</param> /// <returns>The server-relative folder URL if found. Null otherwise.</returns> private string GetFolderUrlDirect(string webUrl, string folderUrl, string username, string password) { string methodName = "SharePointManager2003.GetFolderUrlDirect"; try { SP.ClientContext context = new SP.ClientContext(webUrl); context.Credentials = new NetworkCredential(username, password); // load the web data SP.Web web = context.Web; context.Load(web); // load the folder data Uri uri = new Uri(folderUrl); SP.Folder folder = web.GetFolderByServerRelativeUrl(uri.AbsolutePath); context.Load(folder); context.ExecuteQuery(); // check if the URL belongs to a folder if (folder != null) { return(folder.ServerRelativeUrl); } return(null); } catch (Exception e) { Logger.Error(string.Format("{0}: Could not find folder with URL {1}.", methodName, folderUrl), e); return(null); } }
private void Bw_sharepoint_safety_site_lib_DoWork(object sender, DoWorkEventArgs e) { //throw new NotImplementedException(); toolStripStatusLabel1.Text = "Connecting to Safety Libraries"; using (Microsoft.SharePoint.Client.ClientContext context = new Microsoft.SharePoint.Client.ClientContext(spCandidateSite)) { try { context.Credentials = new Microsoft.SharePoint.Client.SharePointOnlineCredentials(O365UserName, O365Password); context.Load(context.Web, w => w.Title); context.ExecuteQuery(); //toolStripStatusLabel1.Text = "Connecting to Libraries.."; Microsoft.SharePoint.Client.List doclist = context.Web.Lists.GetByTitle(docLibraryName); context.Load(doclist); context.ExecuteQuery(); //toolStripStatusLabel1.Text = "Connecting to Lists.."; //Microsoft.SharePoint.Client.List list = context.Web.Lists.GetByTitle(quizListName); //context.Load(list); e.Result = doclist; } catch (Microsoft.SharePoint.Client.ServerException ex) { e.Result = ex; } catch (Exception ex) { e.Result = ex; } } }
public static void LoadSubFolders(TreeNode parentNode, SPClient.Folder folder, MainBrowser form) { try { SPClient.ClientContext ctx = GetClientContext(parentNode); ctx.Load(folder.Folders); ctx.Load(folder.Files); ctx.ExecuteQuery(); int total = folder.Folders.Count + folder.Files.Count; int current = 0; // Add folder properties AddLoadingNode(parentNode, "Properties", Constants.IMAGE_PROPERTY, LoadType.FolderProperties); // Add folders foreach (SPClient.Folder subFolder in folder.Folders) { LoadFolder(parentNode, subFolder, form); // Update progress current++; ItemLoaded(null, new ItemLoadedEventArgs() { TotalItem = total, CurrentItem = current }); } // Add files foreach (SPClient.File file in folder.Files) { // Add file node TreeNode node = parentNode.Nodes.Add(file.Name); node.ImageKey = Constants.IMAGE_FILE; node.SelectedImageKey = Constants.IMAGE_FILE; node.Tag = file; node.ContextMenuStrip = form.mnContextItem; // Update progress current++; ItemLoaded(null, new ItemLoadedEventArgs() { TotalItem = total, CurrentItem = current }); } } catch (Exception ex) { MessageBox.Show(ex.Message, form.Text, MessageBoxButtons.OK, MessageBoxIcon.Error); AddLoadingNode(parentNode, LoadType.Folder); } }
private async void btn_Upload_Click(object sender, EventArgs e) { try { ctx = connect_Sharepoint(); if (ctx != null) { try { List doclist = ctx.Web.Lists.GetByTitle(docLibraryName); ctx.Load(doclist); ctx.ExecuteQuery(); Microsoft.SharePoint.Client.List list = ctx.Web.Lists.GetByTitle(quizListName); ctx.Load(list); ctx.ExecuteQuery(); label5.Visible = true; progressBarUpload.Visible = true; foreach (DataRow row in candidateList.Rows) { label5.Text = "Processing : " + row["First_Name"] + row["Last_Name"]; if (Convert.ToString(row["Upload_Status"]) == "Failed") { if (Convert.ToString(row["IsReturningCandidate"]) == "No") { await upload_new_Candidates(row, ctx, doclist, list); row["Current_Upload_Status"] = "Uploaded"; progressBarUpload.PerformStep(); } else { await upload_RC_Candidates(row, ctx, doclist, list); row["Current_Upload_Status"] = "Uploaded"; progressBarUpload.PerformStep(); } } } label5.Text = "Upload Complete"; } catch (Exception ex) { } } else { MessageBox.Show("Error connecting to Sharepoint. Kindly check internet connectivity"); } } catch (Exception ex) { } }
/// <summary> /// This is simple demo on sub site creation based on selected "template" with configurable options /// </summary> /// <param name="txtUrl"></param> /// <param name="template"></param> /// <param name="title"></param> /// <param name="description"></param> /// <param name="cc"></param> /// <param name="page"></param> /// <param name="configuration"></param> /// <returns></returns> public Web CreateSubSite(string txtUrl, string template, string title, string description, Microsoft.SharePoint.Client.ClientContext cc, Page page, XDocument baseConfiguration, bool isChildSite = false, Web subWeb = null) { // Resolve the template configuration to be used for chosen template XElement templateConfig = GetTemplateConfig(template, baseConfiguration); string siteTemplate = SolveUsedTemplate(template, templateConfig); // Create web creation configuration WebCreationInformation information = new WebCreationInformation(); information.WebTemplate = siteTemplate; information.Description = description; information.Title = title; information.Url = txtUrl; // Currently all english, could be extended to be configurable based on language pack usage information.Language = 1033; Microsoft.SharePoint.Client.Web newWeb = null; //if it's child site from xml, let's do somethign else if (!isChildSite) { // Load host web and add new web to it. Microsoft.SharePoint.Client.Web web = cc.Web; cc.Load(web); cc.ExecuteQuery(); newWeb = web.Webs.Add(information); } else { newWeb = subWeb.Webs.Add(information); } cc.ExecuteQuery(); cc.Load(newWeb); cc.ExecuteQuery(); DeployFiles(cc, newWeb, templateConfig); DeployCustomActions(cc, newWeb, templateConfig); DeployLists(cc, newWeb, templateConfig); DeployNavigation(cc, newWeb, templateConfig); DeployTheme(cc, newWeb, templateConfig, baseConfiguration); SetSiteLogo(cc, newWeb, templateConfig); if (!isChildSite) { DeploySubSites(cc, newWeb, templateConfig, page, baseConfiguration); } // All done, let's return the newly created site return(newWeb); }
private void AddJsLink(Microsoft.SharePoint.Client.ClientContext ctx) { Web web = ctx.Web; ctx.Load(web, w => w.UserCustomActions); ctx.ExecuteQuery(); ctx.Load(web, w => w.UserCustomActions, w => w.Url, w => w.AppInstanceId); ctx.ExecuteQuery(); UserCustomAction userCustomAction = web.UserCustomActions.Add(); userCustomAction.Location = "Microsoft.SharePoint.StandardMenu"; userCustomAction.Group = "SiteActions"; BasePermissions perms = new BasePermissions(); perms.Set(PermissionKind.ManageWeb); userCustomAction.Rights = perms; userCustomAction.Sequence = 100; userCustomAction.Title = "Modify Site"; string realm = TokenHelper.GetRealmFromTargetUrl(new Uri(ctx.Url)); string issuerId = WebConfigurationManager.AppSettings.Get("ClientId"); var modifyPageUrl = string.Format("https://{0}/Pages/Modify.aspx?{{StandardTokens}}", Request.Url.Authority); string url = "javascript:LaunchApp('{0}', 'i:0i.t|ms.sp.ext|{1}@{2}','{3}',{{width:300,height:200,title:'Modify Site'}});"; url = string.Format(url, Guid.NewGuid().ToString(), issuerId, realm, modifyPageUrl); userCustomAction.Url = url; userCustomAction.Update(); ctx.ExecuteQuery(); // Remove the entry from the 'Recents' node NavigationNodeCollection nodes = web.Navigation.QuickLaunch; ctx.Load(nodes, n => n.IncludeWithDefaultProperties(c => c.Children)); ctx.ExecuteQuery(); var recent = nodes.Where(x => x.Title == "Recent").FirstOrDefault(); if (recent != null) { var appLink = recent.Children.Where(x => x.Title == "Site Modifier").FirstOrDefault(); if (appLink != null) { appLink.DeleteObject(); } ctx.ExecuteQuery(); } }
static void GetChanges(ClientContext SPClientContext, string ListId, ILogger log) { Web spWeb = SPClientContext.Web; List myList = spWeb.Lists.GetByTitle(ConfigurationManager.AppSettings["whListName"]); SPClientContext.Load(myList); SPClientContext.ExecuteQuery(); ChangeQuery myChangeQuery = GetChangeQueryNew(ListId); var allChanges = myList.GetChanges(myChangeQuery); SPClientContext.Load(allChanges); SPClientContext.ExecuteQuery(); foreach (Change oneChange in allChanges) { if (oneChange is ChangeItem) { int myItemId = (oneChange as ChangeItem).ItemId; log.LogInformation($"---- Changed ItemId : " + myItemId); ListItem myItem = myList.GetItemById(myItemId); Microsoft.SharePoint.Client.File myFile = myItem.File; ClientResult <System.IO.Stream> myFileStream = myFile.OpenBinaryStream(); SPClientContext.Load(myFile); SPClientContext.ExecuteQuery(); byte[] myFileBytes = ConvertStreamToByteArray(myFileStream); TextAnalyzeOCRResult myResult = GetAzureTextAnalyzeOCR(myFileBytes).Result; log.LogInformation($"---- Text Analyze OCR Result : " + JsonConvert.SerializeObject(myResult)); myItem["Language"] = myResult.language; string myText = string.Empty; for (int oneLine = 0; oneLine < myResult.regions[0].lines.Count(); oneLine++) { for (int oneWord = 0; oneWord < myResult.regions[0].lines[oneLine].words.Count(); oneWord++) { myText += myResult.regions[0].lines[oneLine].words[oneWord].text + " "; } } myItem["OCRText"] = myText; myItem.Update(); SPClientContext.ExecuteQuery(); log.LogInformation($"---- Text Analyze OCR added to SharePoint Item"); } } }
public static SP.View GetViewFromList(SP.ClientContext context, SP.List list, string viewName) { SP.View view = list.Views.GetByTitle(viewName); context.Load(view); context.ExecuteQuery(); return(view); }
public static SP.List GetListFromWeb(SP.ClientContext context, string listTitle) { SP.List list = context.Web.Lists.GetByTitle(listTitle); context.Load(list); context.ExecuteQuery(); return(list); }
protected void Page_Load(object sender, EventArgs e) { // The following code gets the client context by using TokenHelper. if (!Page.IsPostBack) { SPSocial.SocialFeedManager feedMngr; string contextToken; string hostWeb; // The following code handles authentication/authorization against our SPO tenant // because this page is not running in SharePoint. The important thing for us is to // be able to get the ClientContext object. // NOTE: The TokenHelper class is the one provided by the Visual Studio template for // autohosted Apps, so we haven't modified it's implementation in any way. HttpRequest req; req = Page.Request; contextToken = TokenHelper.GetContextTokenFromRequest(req); hostWeb = Page.Request["SPHostUrl"]; clientContext = TokenHelper.GetClientContextWithContextToken(hostWeb, contextToken, Request.Url.Authority); // Now we are into the useful bits that enable us to work with feeds, posts, replies, and so on. feedMngr = new SPSocial.SocialFeedManager(clientContext); clientContext.Load(feedMngr); clientContext.ExecuteQuery(); // Call our own function (see below) to render the three most recent posts as tiles. LoadPosts(); } }
public static void LoadRoleDefinitions(TreeNode parentNode, SPClient.RoleDefinitionCollection roleDefinitions, MainBrowser form, LoadType loadType) { try { SPClient.ClientContext ctx = GetClientContext(parentNode); ctx.Load(roleDefinitions); ctx.ExecuteQuery(); int total = roleDefinitions.Count; int current = 0; foreach (var roleDefinition in roleDefinitions) { LoadRoleDefinition(parentNode, form, roleDefinition); // Update progress current++; ItemLoaded(null, new ItemLoadedEventArgs() { TotalItem = total, CurrentItem = current }); } } catch (Exception ex) { MessageBox.Show(ex.Message, form.Text, MessageBoxButtons.OK, MessageBoxIcon.Error); AddLoadingNode(parentNode, loadType); } }
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); }
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; }
public static void LoadProperties(TreeNode parentNode, SPClient.PropertyValues properties, MainBrowser form, LoadType loadType) { try { SPClient.ClientContext ctx = GetClientContext(parentNode); ctx.Load(properties); ctx.ExecuteQuery(); int total = properties.FieldValues.Count; int current = 0; foreach (var property in properties.FieldValues) { TreeNode node = parentNode.Nodes.Add(string.Format("{0}", property.Key)); node.ImageKey = Constants.IMAGE_PROPERTY; node.SelectedImageKey = Constants.IMAGE_PROPERTY; node.Tag = property; node.ContextMenuStrip = form.mnContextItem; // Update progress current++; ItemLoaded(null, new ItemLoadedEventArgs() { TotalItem = total, CurrentItem = current }); } } catch (Exception ex) { MessageBox.Show(ex.Message, form.Text, MessageBoxButtons.OK, MessageBoxIcon.Error); AddLoadingNode(parentNode, loadType); } }
public static void LoadRecycleBin(TreeNode parentNode, SPClient.RecycleBinItemCollection recycleBinItems, MainBrowser form, LoadType loadType) { try { SPClient.ClientContext ctx = GetClientContext(parentNode); ctx.Load(recycleBinItems); ctx.ExecuteQuery(); int total = recycleBinItems.Count; int current = 0; foreach (var recycleBinItem in recycleBinItems) { TreeNode node = parentNode.Nodes.Add(string.Format("{0}", recycleBinItem.Title)); node.ImageKey = Constants.IMAGE_RECYCLE_BIN; node.SelectedImageKey = Constants.IMAGE_RECYCLE_BIN; node.Tag = recycleBinItem; node.ContextMenuStrip = form.mnContextItem; // Update progress current++; ItemLoaded(null, new ItemLoadedEventArgs() { TotalItem = total, CurrentItem = current }); } } catch (Exception ex) { MessageBox.Show(ex.Message, form.Text, MessageBoxButtons.OK, MessageBoxIcon.Error); AddLoadingNode(parentNode, loadType); } }
public static void LoadFolder(TreeNode parentNode, SPClient.Folder folder, MainBrowser form, bool isRootFolder = false) { try { SPClient.ClientContext ctx = GetClientContext(parentNode); ctx.Load(folder); ctx.ExecuteQuery(); // Add folder node TreeNode node = parentNode.Nodes.Add(isRootFolder ? "Root Folder" : folder.Name); node.ImageKey = Constants.IMAGE_FOLDER; node.SelectedImageKey = Constants.IMAGE_FOLDER; node.Tag = folder; node.ContextMenuStrip = form.mnContextItem; AddLoadingNode(node, LoadType.Folder); } catch (Exception ex) { MessageBox.Show(ex.Message, form.Text, MessageBoxButtons.OK, MessageBoxIcon.Error); if (isRootFolder) { TreeNode node = parentNode.Nodes.Add("Root Folder (Error)"); node.ImageKey = Constants.IMAGE_FOLDER; node.SelectedImageKey = Constants.IMAGE_FOLDER; } else { AddLoadingNode(parentNode, LoadType.Folder); } } }
public static void LoadWorkflowTemplates(TreeNode parentNode, SPClient.Workflow.WorkflowTemplateCollection workflows, MainBrowser form, LoadType loadType) { try { SPClient.ClientContext ctx = GetClientContext(parentNode); ctx.Load(workflows); ctx.ExecuteQuery(); int total = workflows.Count; int current = 0; foreach (var workflow in workflows) { TreeNode node = parentNode.Nodes.Add(workflow.Name); node.ImageKey = Constants.IMAGE_WORKFLOW_ASSOCIATION; node.SelectedImageKey = Constants.IMAGE_WORKFLOW_ASSOCIATION; node.Tag = workflow; node.ContextMenuStrip = form.mnContextItem; // Update progress current++; ItemLoaded(null, new ItemLoadedEventArgs() { TotalItem = total, CurrentItem = current }); } } catch (Exception ex) { MessageBox.Show(ex.Message, form.Text, MessageBoxButtons.OK, MessageBoxIcon.Error); AddLoadingNode(parentNode, loadType); } }
public static void LoadViews(TreeNode parentNode, SPClient.ViewCollection views, MainBrowser form) { try { SPClient.ClientContext ctx = GetClientContext(parentNode); ctx.Load(views); ctx.ExecuteQuery(); int total = views.Count; int current = 0; foreach (SPClient.View view in views) { TreeNode node = parentNode.Nodes.Add(view.Title); node.ImageKey = Constants.IMAGE_VIEW; node.SelectedImageKey = Constants.IMAGE_VIEW; node.Tag = view; node.ContextMenuStrip = form.mnContextItem; // Update progress current++; ItemLoaded(null, new ItemLoadedEventArgs() { TotalItem = total, CurrentItem = current }); } } catch (Exception ex) { MessageBox.Show(ex.Message, form.Text, MessageBoxButtons.OK, MessageBoxIcon.Error); AddLoadingNode(parentNode, LoadType.ListViews); } }
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); } }
public static void LoadSubWebs(TreeNode parentNode, SPClient.WebCollection webs, MainBrowser form) { try { SPClient.ClientContext ctx = GetClientContext(parentNode); ctx.Load(webs); ctx.ExecuteQuery(); int total = webs.Count; int current = 0; foreach (SPClient.Web subweb in webs) { LoadWeb(parentNode, subweb, form); // Update progress current++; ItemLoaded(null, new ItemLoadedEventArgs() { TotalItem = total, CurrentItem = current }); } } catch (Exception ex) { MessageBox.Show(ex.Message, form.Text, MessageBoxButtons.OK, MessageBoxIcon.Error); AddLoadingNode(parentNode, LoadType.WebSubWebs); } }
public Web CreateSubSite(Microsoft.SharePoint.Client.ClientContext ctx, Web hostWeb, string txtUrl, string template, string title, string description) { // Create web creation configuration WebCreationInformation information = new WebCreationInformation(); information.WebTemplate = template; information.Description = description; information.Title = title; information.Url = txtUrl; // Currently all english, could be extended to be configurable based on language pack usage information.Language = 1033; Microsoft.SharePoint.Client.Web newWeb = null; newWeb = hostWeb.Webs.Add(information); ctx.ExecuteQuery(); ctx.Load(newWeb); ctx.ExecuteQuery(); // Add sub site link override new LabHelper().AddJsLink(ctx, newWeb, this.Request); // Set oob theme to the just created site new LabHelper().SetThemeBasedOnName(ctx, newWeb, hostWeb, "Orange"); // All done, let's return the newly created site return(newWeb); }
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); }
private async Task Update_List(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(); FieldLookupValue lval = await GetLookupValue(ctx, jobName, "Job", "JobFullName", "Text", false); foreach (ListItem oListItem in listitems) { //oListItem["JobSite"] = lval.LookupValue; oListItem["JobSite"] = lval; oListItem["Job"] = jobName; //double percent = Convert.ToDouble(no_of_passes) / Convert.ToDouble(dt.Rows.Count); //if (percent >= 0.7 && percent < 1.0) // oListItem["Hire_Status"] = "Conditional Hire"; //else // oListItem["Hire_Status"] = "Hired"; oListItem["Hire_Status"] = hireStatus; string tempFolderurl = docFolder.ServerRelativeUrl; FieldUrlValue _url = new FieldUrlValue(); _url.Url = tempFolderurl.Substring(0, tempFolderurl.LastIndexOf('/'));; _url.Description = "View Tests"; oListItem["FolderUrl"] = _url; oListItem["Remaining_Test"] = remaining_test; oListItem["Category"] = pos_category; //newItem["FolderUrl"] = folder.ServerRelativeUrl; oListItem.Update(); ctx.Load(oListItem); ctx.ExecuteQuery(); } await Task.Delay(1000); } catch (Exception ex) { throw ex; } }
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); }
public void AddJsLink(Microsoft.SharePoint.Client.ClientContext ctx) { Web web = ctx.Web; ctx.Load(web, w => w.UserCustomActions); ctx.ExecuteQuery(); ctx.Load(web, w => w.UserCustomActions, w => w.Url, w => w.AppInstanceId); ctx.ExecuteQuery(); UserCustomAction userCustomAction = web.UserCustomActions.Add(); userCustomAction.Location = "Microsoft.SharePoint.StandardMenu"; userCustomAction.Group = "SiteActions"; BasePermissions perms = new BasePermissions(); perms.Set(PermissionKind.ManageWeb); userCustomAction.Rights = perms; userCustomAction.Sequence = 100; userCustomAction.Title = "Say Hello"; string url = "javascript:alert('Hello SharePoint Custom Action!!!');"; userCustomAction.Url = url; userCustomAction.Update(); ctx.ExecuteQuery(); // Remove the entry from the 'Recents' node Microsoft.SharePoint.Client.NavigationNodeCollection nodes = web.Navigation.QuickLaunch; ctx.Load(nodes, n => n.IncludeWithDefaultProperties(c => c.Children)); ctx.ExecuteQuery(); var recent = nodes.Where(x => x.Title == "Recent").FirstOrDefault(); if (recent != null) { var appLink = recent.Children.Where(x => x.Title == "Site Modifier").FirstOrDefault(); if (appLink != null) { appLink.DeleteObject(); } ctx.ExecuteQuery(); } }
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 static void GetFieldsFromList(SP.ClientContext context, SP.List list) { context.Load(list.Fields); context.ExecuteQuery(); foreach (SP.Field field in list.Fields) { // TODO do something with the fields Console.Write(field.InternalName); } }
public static void LoadRoleAssignments(TreeNode parentNode, SPClient.RoleAssignmentCollection roleAssignments, MainBrowser form, LoadType loadType) { try { SPClient.ClientContext ctx = GetClientContext(parentNode); ctx.Load(roleAssignments); ctx.ExecuteQuery(); int total = roleAssignments.Count; int current = 0; foreach (var roleAssignment in roleAssignments) { ctx.Load(roleAssignment.Member); ctx.Load(roleAssignment.RoleDefinitionBindings); ctx.ExecuteQuery(); TreeNode node = parentNode.Nodes.Add(string.Format("{0}", roleAssignment.Member.LoginName)); node.ImageKey = Constants.IMAGE_ROLE_ASSIGNMENT; node.SelectedImageKey = Constants.IMAGE_ROLE_ASSIGNMENT; node.Tag = roleAssignment; node.ContextMenuStrip = form.mnContextItem; foreach (var binding in roleAssignment.RoleDefinitionBindings) { LoadRoleDefinition(node, form, binding); } // Update progress current++; ItemLoaded(null, new ItemLoadedEventArgs() { TotalItem = total, CurrentItem = current }); } } catch (Exception ex) { MessageBox.Show(ex.Message, form.Text, MessageBoxButtons.OK, MessageBoxIcon.Error); AddLoadingNode(parentNode, loadType); } }
private void CheckCalendarAsync(object sender, DoWorkEventArgs e) { calendarDaysForWeek.Clear(); using (Microsoft.SharePoint.Client.ClientContext client = new Microsoft.SharePoint.Client.ClientContext(ConfigManager.SharePointWebUrl)) { var optionsVM = ViewModelLocater.OptionsViewModel; var mainWindowVM = ViewModelLocater.MainWindowViewModel; if (optionsVM.SpecifyUserCredentials && optionsVM.CredentialsAreValid) { NetworkCredential cred = new NetworkCredential(optionsVM.Username, optionsVM.Password, optionsVM.Domain); client.Credentials = cred; } List list = client.Web.Lists.GetByTitle(ConfigManager.SharepointCalendarName); CamlQuery camlQuery = new CamlQuery(); camlQuery.ViewXml = @"<View> <Query> <Where> <And> <Eq> <FieldRef Name='Author' LookupId='TRUE' /> <Value Type='Integer'><UserID/></Value> </Eq> <Or> <And> <Geq> <FieldRef Name='EventDate' /> <Value IncludeTimeValue='FALSE' Type='DateTime'>" + mainWindowVM.SelectedWeek.StartOfWeek.Date.ToString("o") + @"</Value> </Geq> <Leq> <FieldRef Name='EventDate' /> <Value IncludeTimeValue='FALSE' Type='DateTime'>" + mainWindowVM.SelectedWeek.EndOfWeek.Date.ToString("o") + @"</Value> </Leq> </And> <And> <Geq> <FieldRef Name='EndDate' /> <Value IncludeTimeValue='FALSE' Type='DateTime'>" + mainWindowVM.SelectedWeek.StartOfWeek.Date.ToString("o") + @"</Value> </Geq> <Leq> <FieldRef Name='EndDate' /> <Value IncludeTimeValue='FALSE' Type='DateTime'>" + mainWindowVM.SelectedWeek.EndOfWeek.Date.ToString("o") + @"</Value> </Leq> </And> </Or> </And> </Where> </Query> <RowLimit>100</RowLimit> </View>"; ListItemCollection listItems = list.GetItems(camlQuery); client.Load( listItems, items => items .Include( item => item["Title"], item => item["EventDate"], item => item["EndDate"])); client.ExecuteQuery(); foreach (ListItem listItem in listItems) calendarDaysForWeek.Add(new CalendarDayModel(listItem)); } }
/// <summary> /// Checks if a URL belongs to a SharePoint website. /// </summary> /// <param name="url">The URL.</param> /// <param name="username">Username for SharePoint authentication.</param> /// <param name="password">Password for SharePoint authentication.</param> /// <returns>True if the URL is a SharePoint website. False, otherwise.</returns> private bool IsWeb(string url, string username, string password) { string methodName = "SharePointManager2013.IsWeb"; try { Logger.DebugFormat("{0}: Checking if {1} is a website.", methodName, url); SP.ClientContext context = new SP.ClientContext(url); context.Credentials = new NetworkCredential(username, password); SP.Web web = context.Web; // The SharePoint web at the URL. context.Load(web, w => w.Title); // We want to retrieve the web's properties. context.ExecuteQuery(); // Execute the query to the server. Logger.DebugFormat("{0}: URL {1} is a website with title {2}.", methodName, url, web.Title); return true; } catch (Exception e) { Logger.Error(string.Format("{0}: Error checking URL {1}.", methodName, url), e); return false; } }
/// <summary> /// Retrieves the server-relative URL of a folder from its absolute URL. /// </summary> /// <param name="webUrl">Web URL to establish context.</param> /// <param name="folderUrl">folder URL</param> /// <param name="username">Username for SharePoint authentication.</param> /// <param name="password">Password for SharePoint authentication.</param> /// <returns>The server-relative folder URL if found. Null otherwise.</returns> private string GetFolderUrlDirect(string webUrl, string folderUrl, string username, string password) { string methodName = "SharePointManager2003.GetFolderUrlDirect"; try { SP.ClientContext context = new SP.ClientContext(webUrl); context.Credentials = new NetworkCredential(username, password); // load the web data SP.Web web = context.Web; context.Load(web); // load the folder data Uri uri = new Uri(folderUrl); SP.Folder folder = web.GetFolderByServerRelativeUrl(uri.AbsolutePath); context.Load(folder); context.ExecuteQuery(); // check if the URL belongs to a folder if (folder != null) { return folder.ServerRelativeUrl; } return null; } catch (Exception e) { Logger.Error(string.Format("{0}: Could not find folder with URL {1}.", methodName, folderUrl), e); return null; } }