Microsoft introduced a new functionality to interact with CSOM. It has SharePointOnlineCredentials, which will handle any authentication; you should need to do.
This class is included in version 15 of Microsoft.SharePoint.Client dll.
Method
Using this method, it is a simple way to connect to Sharepoint Online sites.
var onlineCredentials = new SharePointOnlineCredentials(Configuration.ServiceUserName, securePassword);
Configure your credentials in a separate configuration class.
- private class Configuration
- {
- public static string ServiceSiteUrl = "https:// https://gowthamr.sharepoint.com";
- public static string ServiceUserName = "[email protected]";
- public static string ServicePassword = "xxxxxxxxxx";
- }
-
-
-
- static ClientContext GetonlineContext()
- {
- var securePassword = new SecureString();
- foreach (char c in Configuration.ServicePassword)
- {
- securePassword.AppendChar(c);
- }
-
- var onlineCredentials = new SharePointOnlineCredentials(Configuration.ServiceUserName, securePassword);
-
- var context = new ClientContext(Configuration.ServiceSiteUrl);
- context.Credentials = onlineCredentials;
-
- return context;
- }
-
-
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using Microsoft.SharePoint.Client;
-
- namespace O365SPAddUsertoRole
- {
- class Program
- {
-
-
- private class Configuration
- {
- public static string ServiceSiteUrl = "https:// https://gowthamr.sharepoint.com";
- public static string ServiceUserName = "[email protected]";
- public static string ServicePassword = "xxxxxxxxxx";
- }
-
- static ClientContext GetonlineContext()
- {
- var securePassword = new SecureString();
- foreach (char c in Configuration.ServicePassword)
- {
- securePassword.AppendChar(c);
- }
- var onlineCredentials = new SharePointOnlineCredentials(Configuration.ServiceUserName, securePassword);
- var context = new ClientContext(Configuration.ServiceSiteUrl);
- context.Credentials = onlineCredentials;
- return context;
- }
-
-
- static void Main(string[] args)
- {
- var context=GetonlineContext();
- Web web = context.Web;
- Principal user = context.Web.SiteUsers.GetByLoginName(@"X");
- RoleDefinition readDef = context.Web.RoleDefinitions.GetByName("Read");
- RoleDefinitionBindingCollection roleDefCollection = new RoleDefinitionBindingCollection(context);
- roleDefCollection.Add(readDef);
- RoleAssignment newRoleAssignment = context.Web.RoleAssignments.Add(user, roleDefCollection);
- context.ExecuteQuery();
-
- }
- }
- }
Run this code and check your SharePoint Site. New Site list is created successfully.
Was my blog helpful?
If the blog was helpful, please let us know at the bottom of this page. If you did not like the blog, let us know what was confusing or missing. I’ll use your feedback to double-check the facts, add info and update this article.