Question

I want to create a new Hub site and associate some of the existing sites to the Hub site using CSOM C# in SharePoint Online. I know how to do this using the SharePoint Admin center. But I want to do the same operation using CSOM C# I hope this can be done using PNP CSOM.

Can anyone provide me any reference links or samples?

Was it helpful?

Solution

To register a site as Hubsite, you can use the below code:

string tenantAdminSiteUrl = "https://tenant-admin.sharepoint.com/";    

string userName = "admin@tenant.onmicrosoft.com";
string password = "password";

using (ClientContext context = new ClientContext(tenantAdminSiteUrl))
{
    SecureString securePassword = new SecureString();
    foreach (char c in password.ToCharArray())
    {
        securePassword.AppendChar(c);
    }

    context.AuthenticationMode = ClientAuthenticationMode.Default;
    context.Credentials = new SharePointOnlineCredentials(userName, securePassword);

    var tenant = new Tenant(context);   

    string hubSiteUrl = "https://tenant.sharepoint.com/sites/HubSiteCollection";
    tenant.RegisterHubSite(hubSiteUrl);

    context.ExecuteQuery(); 
}

To associate a site collection to a Hub site, you can use the below code:

string tenantSiteUrl = "https://tenant-admin.sharepoint.com/";

string userName = "admin@tenant.onmicrosoft.com";
string password = "password";

using (ClientContext context = new ClientContext(tenantSiteUrl))
{
    SecureString securePassword = new SecureString();
    foreach (char c in password.ToCharArray())
    {
        securePassword.AppendChar(c);
    }

    context.AuthenticationMode = ClientAuthenticationMode.Default;
    context.Credentials = new SharePointOnlineCredentials(userName, securePassword);

    var tenant = new Tenant(context);   

    string hubSiteUrl = "https://tenant.sharepoint.com/sites/HubSiteCollection";
    string associateSiteUrl = "https://tenant.sharepoint.com/sites/AssociateSiteCollection";

    tenant.ConnectSiteToHubSite(associateSiteUrl, hubSiteUrl);

    context.ExecuteQuery(); 
}

Note: both these methods are tenant level methods and to execute them you need to be SharePoint admin.

References - Register HubSite method

ConnectSiteToHubSite method

OTHER TIPS

Yes this can be done. Below is code for your reference.

$myHubsite = "https://marvel.sharepoint.com/sites/avengers"
$SiteUrl = "https://marvel.sharepoint.com/sites/captainmarvel"

Add-PnPHubSiteAssociation -Site $SiteUrl  -HubSite $myHubsite
Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top