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