Friday, October 9, 2015

Set sharing capabilities of Sharepoint site collection via client object model

In Sharepoint Online it is possible to invite users from other organizations to your site. It works because in most cases organizations which use SPO have federation enabled which allows to use SSO. In on-premise version it is also possible, but IT departments should configure AD FS before that. However having federation is not enough. In order to enable inviting of external users to your site collection you need to set its sharing capabilities. This can be done via following code:

   1: using (var ctx = new ClientContext(""))
   2: {
   3:     var secure = new SecureString();
   4:     foreach (char c in "password")
   5:     {
   6:         secure.AppendChar(c);
   7:     }
   8:     var credentials = new SharePointOnlineCredentials("username", secure);
   9:     ctx.Credentials = credentials;
  10:     ctx.Load(ctx.Web);
  11:     ctx.ExecuteQuery();
  13:     var tenant = new Tenant(ctx);
  14:     tenant.SetSiteProperties("", null, null,
  15:         SharingCapabilities.ExternalUserSharingOnly, null, null, null, null);
  16:     ctx.ExecuteQuery();
  17: }

In order to compile and execute this code you will need the following assemblies:

Assembly Version
Microsoft.Online.SharePoint.Client.Tenant.dll 16.1.3912.1204
Microsoft.SharePoint.Client.dll 16.1.3912.1204
Microsoft.SharePoint.Client.Runtime.dll 16.1.3912.1204
OfficeDevPnP.Core.dll 1.6.915.0