How we can work with output cache programmatically ?

Once I got an interesting question from one of our discussion lists about how we can enable output cache programmatically ? and how we can create a cache policy through code. After my research on it I was able to accomplish this one by using the following code snippet.

    1: using Microsoft.SharePoint;
    2: using Microsoft.SharePoint.Publishing;
    3:  
    4: SPSite oSite = new SPSite("https://blr3r7-19c:6000/sites/CacheTestSite");
    5:  
    6: SiteCacheSettingsWriter oWriter = new SiteCacheSettingsWriter(oSite);
    7:  
    8: oWriter.EnableCache = true;
    9: oWriter.EnableDebuggingOutput = true;
   10: oWriter.AllowPublishingWebPageOverrides = true;
   11: oWriter.AllowLayoutPageOverrides = true;
   12: // second parameter is the id of the cache profiles in the dropdown. Once you create you custom profile that profile also will come under this dropdown
   13: oWriter.SetAnonymousPageCacheProfileId(oSite, 2);
   14: oWriter.SetAuthenticatedPageCacheProfileId(oSite, 2);
   15:  
   16: oWriter.SetFarmCacheFlushFlag();
   17: oWriter.Update();

Creating custom cache profile:

Cache profile is nothing but a list in a publishing site. Thus you have to create a new custom profile list item with all the metadata.

    1: SPList oList = oWeb.Lists["Cache Profiles"];
    2: SPListItem oListItem = oList.Items.Add();
    3: oListItem["Title"] = "custom profile";
    4: oListItem.Update();

If you want to get the current cache setting of a site through code you can use the following line of code.

SiteCacheSettings oCacheSettings = SiteCacheSettings.GetSiteCacheSettings(oSite);

You can see the site collection cache profiles under the Site Collection Administration of a publishing site.

Site Collection Administration

Search settings

Search scopes

Search keywords

Recycle bin

Site collection features

Site hierarchy

Portal site connection

Site collection audit settings

Site collection policies

Site collection object cache

Site collection cache profiles

Site collection output cache

Variations

Variation labels

Translatable columns

Variation logs