Monday, June 24, 2013

Programmatically applying themes to Sharepoint all sites and subsites


I have found one of the very useful code below to apply themes to Sharepoint all sites and subsites
using Console application. Enjoy coding. Cheers.


using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System.IO;
namespace Theme_Update
{
    class Theme_Update
    {
        static void Main(string[] args)
        {
            string site;
            string siteTheme;
            try
            {
                if (args.Length == 0)
                {
                    Console.WriteLine("Enter the Web Application URL:");
                    site = Console.ReadLine();
                    Console.WriteLine("Enter the Site Theme:");
                    siteTheme = Console.ReadLine();
                }
                else
                {
                    site = args[0];
                    siteTheme = args[1];
                }
                SPSite tmpRoot = new SPSite(site);
                SPSiteCollection tmpRootColl = tmpRoot.WebApplication.Sites;
                //Enumerate through each site
                foreach (SPSite tmpSite in tmpRootColl)
                {
                    //Enumerate through each web for the site
                    foreach (SPWeb tmpWeb in tmpSite.AllWebs)
                    {
                            //Apply the default theme for the current Web
                            tmpWeb.AllowUnsafeUpdates = true;
                            tmpWeb.ApplyTheme("none");
                            tmpWeb.Update();
                            tmpWeb.ApplyTheme(siteTheme);
                            tmpWeb.Update();
                            tmpWeb.AllowUnsafeUpdates = false;

                        //Log to a file, where the theme is applied!
                            StreamWriter SW;
                            SW = File.AppendText("C:\\ThemeLog.txt");
                            SW.WriteLine(tmpWeb.Url);
                            SW.Close();

                            //Dispose of the Web Object
                            tmpWeb.Dispose();
                        }
                    //Dispose of the Site Object
                    tmpSite.Dispose();
                }
                //Dispose of the Root Site Object
                tmpRoot.Dispose();
                //Confirmation Message
                Console.WriteLine("The operation completed successfully");
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry("Theme Updater", ex.Message);
                //Failure Message
                Console.WriteLine("The operation failed");
            }
        }
    }
}

 

No comments:

Post a Comment