Wednesday, February 25, 2009

Programmatically Apply Theme to a site

Hi all,
If you want to apply a theme to a site programmatically then the code is pretty straight forward. Have a look at it:

using (SPSite parentSite = new SPSite(SPContext.Current.Site.Url))
{
//Allow the unsafe updates in site from the current user
parentSite.AllowUnsafeUpdates = true;
using (SPWeb currentWeb = parentSite.AllWebs[SPContext.Current.Web.Name])
{
using (SPWeb childWeb = currentWeb.Webs[name])
{
childWeb.AllowUnsafeUpdates = true;
//The code line shown below will apply the theme of the parent site to the child site
childWeb.ApplyTheme(currentWeb.Theme);
childWeb.Update();
childWeb.AllowUnsafeUpdates = false;
}
}
parentSite.AllowUnsafeUpdates = false;
}

Although this code works fine when you use it for applying theme to a site which already exists in the site collection, but this may not work (atleast in my case)when i tried applying a theme to a site which i am creating programmatically.
So if you are also facing same problem then instead of applying theme just after creating the site, move the code outside the create method and take reference of the newly created site and then call the above code. It will work !

In case you are still not able to understand it then write to us at sharepointkings@gmail.com or write a comment to this post.

1 comment:

zee said...

Thanks for sharing. Good info.
zee
walisystems.com




Share your SharePoint Experiences with us...
As good as the SharePointKings is, we want to make it even better. One of our most valuable sources of input for our Blog Posts comes from ever enthusiastic Visitors/Readers. We welcome every Visitor/Reader to contribute their experiences with SharePoint. It may be in the form of a code stub, snippet, any tips and trick or any crazy thing you have tried with SharePoint.
Send your Articles to sharepointkings@gmail.com with your Profile Summary. We will Post them. The idea is to act as a bridge between you Readers!!!

If anyone would like to have their advertisement posted on this blog, please send us the requirement details to sharepointkings@gmail.com