SharePoint customization – applying a theme programmatically

SharePoint sites can be customized through MasterPages and/or Themes. There are 2 main differences between these two methods:
1. masterpages allow you to rebuild the design from scratch – as in move the elements around on the page as you like – but do not affect system pages
2. themes are made up of css files only, allowing you just to skin a SharePoint site, but are also applied on the system pages.

Customizing a site generally means skinning all its pages. So that the user doesn’t get confused as of why some pages look different than others, or at least to give the system pages almost the same look and feel as the rest of the pages.
Automating the masterpage install is easy -you create a feature and write code in the FeatureActivated event, code that sets your masterpage as the default and custom master(details on that feature are to come in a future post).
But what about applying a theme? The general procedure would be to have the administrator go on the server and copy some files on the Windows drive and then modify an XML file so that SharePoint can read the theme and display it on the Site Settings > Site Theme page. One of the many posts that explains this method is this one.

But what if you want to do this programmatically? With a feature, like you would do when you deploy a masterpage.

Well, simple enough, this is possible. As long as the theme exists in the THEMES directory, SharePoint can retrieve it. The only reason you modify the spthemes.xml is for SharePoint to display the theme in the Themes list. So if you place the theme in the Themes directory (just by copying it there in a bat file for example) you can use code to apply it:

web.ApplyTheme(“MyTHEME”);

Since we are here, the way to revert a SharePoint site to the default theme isn’t web.ApplyTheme(“Default”), but web.ApplyTheme(“none”).

And there you go – you can programmatically apply a theme to a site. And the way to make the theme “visible” to the user is to have it as a feature instead of having it in the Themes list.