Saturday, 31 March 2018

Working with SharePoint Online Hub sites using CSOM

With SharePoint Online Hub sites launched for Targeted release tenants, here is some quick code I put together to work with them using CSOM:

1) Register a Hub site, Connect a site to a Hub site, Disconnect a site from a Hub site and Unregister a Hub site:


static void Main(string[] args)
{
string adminSiteUrl = "https://tenant-admin.sharepoint.com/";
string hubSiteUrl = "https://tenant.sharepoint.com/sites/MyHubSite";
string siteUrl = "https://tenant.sharepoint.com/sites/Demo";
var clientContext = GetClientContext(adminSiteUrl);
var tenant = new Tenant(clientContext);
tenant.RegisterHubSite(hubSiteUrl);
tenant.ConnectSiteToHubSite(siteUrl, hubSiteUrl);
tenant.DisconnectSiteFromHubSite(siteUrl);
tenant.UnregisterHubSite(hubSiteUrl);
clientContext.ExecuteQuery();
}
private static ClientContext GetClientContext(string siteUrl)
{
//Part of OfficeDevPnP.Core
var authManager = new AuthenticationManager();
//https://docs.microsoft.com/en-us/sharepoint/dev/solution-guidance/security-apponly-azureacs
return authManager.GetAppOnlyAuthenticatedContext(siteUrl, "<client-id>", "<client-secret>");
}

2) Grant and Revoke specific users rights to connect sites to a Hub site:


When a Hub site is registered, it is public by default. Any user is able to connect their site to the hub site. If you want only a specific set of users to be able to connect their site to the Hub site, you can grant "Join" rights to these users:

static void Main(string[] args)
{
string adminSiteUrl = "https://tenant-admin.sharepoint.com/";
string hubSiteUrl = "https://tenant.sharepoint.com/sites/hub";
var clientContext = GetClientContext(adminSiteUrl);
//Only these users or groups will have rights to join a site to the hub
var hubManagers = new string[]{ "user1@tenant.onmicrosoft.com",
"user2@tenant.onmicrosoft.com"};
var tenant = new Tenant(clientContext);
tenant.GrantHubSiteRights(hubSiteUrl, hubManagers, SPOHubSiteUserRights.Join);
//To revoke rights for users or groups
//tenant.RevokeHubSiteRights(hubSiteUrl, hubManagers);
clientContext.ExecuteQuery();
}
private static ClientContext GetClientContext(string siteUrl)
{
//Part of OfficeDevPnP.Core
var authManager = new AuthenticationManager();
//https://docs.microsoft.com/en-us/sharepoint/dev/solution-guidance/security-apponly-azureacs
return authManager.GetAppOnlyAuthenticatedContext(siteUrl, "<client-id>", "<client-secret>");
}
Hope this helps!