Monday, November 2, 2009

Custom Timer Job to Backup the Web.Config file

The solution that follows will backup the web.config file on each web front end for a given webapplication. Not only is the functionality useful, it demonstrates the power of a custom timer job. With a custom timer, SharePoint will execute the code on each server in the farm. Currently the code is being executed from a FeatureActivated event but could be executed from a webpart, custom action, workflow or ..... It will save the administrator some time.    

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System.Xml;
using Microsoft.SharePoint.Utilities;
using System.IO;

namespace BackUpWebConfig
{
    class WebConfig : SPFeatureReceiver
    {
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
                SPWebApplication oWebApp = (SPWebApplication)properties.Feature.Parent;
              
                //Create a new instance of the timer job
                BackUpWebConfig BackupWeb = new BackUpWebConfig(oWebApp);
                //Configure and submit the new job
                BackupWeb.SubmitJob();
        }


        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            //throw new Exception("The method or operation is not implemented.");
        }

        public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        {
            //throw new Exception("The method or operation is not implemented.");
        }

        public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        {
            //throw new Exception("The method or operation is not implemented.");
        }
    }

    //Our custom timer job class
    public class BackUpWebConfig : SPJobDefinition
    {
        [Persisted]
        private string _uniqueID;

        public BackUpWebConfig() { }

        public BackUpWebConfig(SPWebApplication WebApp)
            : this(WebApp, Guid.NewGuid().ToString())
        {}

        private BackUpWebConfig(SPWebApplication WebApp, string UniqueID)
            : base("BWC_" + UniqueID, WebApp, null, SPJobLockType.None)
        {
            _uniqueID = UniqueID;
        }

        // Submits the job and schedules it to run on every server in the Farm.
        public void SubmitJob()
        {
            //set the schedule property to a one time job, there are a number of other
            //types if you want the job to run on a normal schedule  
            Schedule = new SPOneTimeSchedule(DateTime.Now);
            Title = "Backup Web.config (" + _uniqueID + ")";
            Update();
        }

        //called by the timer service on each server
        public override void Execute(Guid targetInstanceId)
        {
            try
            {
                SPWebApplication o = this.WebApplication;
               
                foreach (SPUrlZone z in o.IisSettings.Keys)
                    UpdateIisSite(o.IisSettings[z]);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Failed to backup web.config");
                Debug.WriteLine(ex);
                throw;
            }
        }

        //Copy the web.config to a backup
        private void UpdateIisSite(SPIisSettings oSettings)
        {
            string webConfigLoc = oSettings.Path.ToString();          
           
            string fileExt = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() +
                DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() +
                DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString();

            //Back up current config
            if(File.Exists(webConfigLoc + @"\web.config"))
            {
                File.Copy(webConfigLoc + @"\web.config", webConfigLoc +
                    @"\web_" + fileExt + ".config", true);
            }
        }
 
    }

}
 

No comments:

Post a Comment