In this post I will describe the process of connecting to publishing catalog programmatically. As you probably know in Sharepoint a lot of actions can be done manually in UI. However if we develop solution with repeatable deployments it is more efficient to automate as much actions as possible. Almost all actions which you may do via UI can be done programmatically or by script in Sharepoint (in some cases you will need to use internal classes via Reflection, but it is still possible). And connecting to the publishing catalog is not exception from this point of view.
First of all before to go forward I recommend to check my previous articles about cross-site publishing and catalogs in Sharepoint 2013, especially Provision Sharepoint 2013 site collection with cross-site publishing. It will help to understand on which step during provisioning methods shown below should be called and other important moments:
Problem with cross site publishing catalog connections when use SPExport/SPImport for copying sites
Restore Sharepoint site with configured cross-site publishing on different environment
Cross site publishing and anonymous access in Sharepoint 2013
Problem with connecting to catalog on site collections imported with SPExport/SPImport API in Sharepoint
First of all we created Site scope feature for configuring search-related functionalities. This feature was activated with assumption that it can be activated and deactivated several times on the site collection. So for each step we have both configuration in FeatureActivated() method of feature receiver and deleting of configuration in FeatureDeactivating() method:
In SearchConfigurationHelper.ConnectAndConfigureNewsPublishingCatalog() we used slightly modified CatalogSubscriber from this MSDN example:
Here we used method getCatalogByName() (lines 126-147) which returns catalog from site collection by its name which work more stable than those which was used in MSDN example.
And in SearchConfigurationHelper.DeleteNewsPublishingCatalogConnection() method which is called in FeatureDeactivating() method we just called CatalogSubscriber.DeleteCatalog() method shown above (lines 176-197):
Hope that this information will help you if you will need to connect to publishing catalog programmatically.