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;
4: SPSite oSite = new SPSite("http://blr3r7-19c:6000/sites/CacheTestSite");
6: SiteCacheSettingsWriter oWriter = new SiteCacheSettingsWriter(oSite);
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);
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";
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