0

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?

2 Answers 2

3

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

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

string userName = "[email protected]";
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 = "[email protected]";
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

2
  • 1
    Hope it has answered your question ! If it has, you can accept it as answer so that it can help others in the community, thanks. Cheers :) Commented Jul 9, 2019 at 18:43
  • Thanks for your solution. Its worked fine for me
    – TARUN
    Commented Jul 10, 2019 at 9:01
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.