Creating a timer job to ensure the site branding feature is activated

SharePoint provides a framework for tasks that can be executed at scheduled intervals called SharePoint timer jobs. These timer jobs, when configured, are executed by the SharePoint Timer Windows service. In a large site with a lot of contributors, there may be the need to enforce some rules in the environment in a more automated fashion, such as using consistent branding. In this recipe, we will create a timer job that ensures the site branding feature is activated on all sites in the site collection.

How to do it...

Follow these steps to create a timer job:

  1. From the Solution Explorer pane, right-click on the project name.
  2. Select Add and then select Class.
  3. Provide a name for the class (for instance, BrandingTimerJob).
  4. Give the class a public access modifier and inherit from the SPJobDefinition base class as follows:
    public class BrandingTimerJob : SPJobDefinition
  5. In the BrandingTimerJob class, add a static GUID for our SiteBranding feature ID. Replace the sample feature ID with the feature ID from your SiteBranding feature as follows:
    private static Guid BrandingFeatureId = new Guid("1150dec7-4af6-44d8-b241-d976d26b723c");
  6. Create the constructors for the BrandingTimerJob class using the following code:
    public BrandingTimerJob(SPWebApplication webApplication, string title) :
    base("Custom Branding Job", webApplication, null, SPJobLockType.ContentDatabase)
    {

    this.Title = title;
    }
    
    public BrandingTimerJob() : base() { }
  7. Create an override for the Execute method as follows:
    public override void Execute(Guid targetInstanceId)
  8. In the Execute method, attempt to get the site collection ID associated with the timer job instance using the following code:
    Guid? siteId = null;
    
    if (this.Properties.ContainsKey("SiteId"))
    siteId = this.Properties["SiteId"] as Guid?;
  9. Get the site collection in a using statement as follows:
    using (var site = new SPSite(siteId.Value))
  10. Ensure the site collection is not null as follows:
    if (site != null)
  11. Iterate through each site in the site collection as follows:
    foreach (SPWeb web in site.AllWebs)
  12. Ensure the site is not null and that it exists as follows:
    if (web != null && web.Exists)
  13. Verify that the feature is in the collection of features activated on the site. If it is not activated, add the feature to the collection as follows:
    if (web.Features[BrandingFeatureId] == null)
    web.Features.Add(BrandingFeatureId);
  14. Save the BrandingTimerJob.cs file.
  15. Open the SiteCollectionBranding.EventReceiver.cs file.
  16. Add a static string to the class for formatting the name of our timer jobs as follows:
    private static string FormatJobName = "Custom Branding Job_{0}";
  17. In the FeatureActivated method, after the foreach loop iterates through each site in the site collection, create the timer job name, get the web application ID, and then get the site collection ID as follows:
    var jobName = string.Format(CultureInfo.InvariantCulture, FormatJobName, site.ID.ToString());
    
    var webAppId = site.WebApplication.Id;
    
    var siteId = site.ID;
  18. Add a delegate method to be executed by the SPSecurity.RunWithElevatedPrivleges method as follows:
    SPSecurity.RunWithElevatedPrivileges(delegate()
    {
    
    });
  19. In the delegate method, get the web application as follows:
    var webApplication = SPWebService.ContentService.WebApplications[webAppId];
  20. Using the following code, delete any timer jobs that already exist on the web application with the same name as the timer job we are about to instantiate:
    foreach (SPJobDefinition job in webApplication.JobDefinitions.Where(p => p.Name == jobName))
    job.Delete();
  21. Instantiate BrandingTimerJob and give it a daily schedule.
    var brandingJob = new BrandingTimerJob(webApplication, jobName);
    
    brandingJob.Properties.Add("SiteId", siteId);
    
    brandingJob.Schedule = new SPDailySchedule() { BeginHour = 1 };
    
    brandingJob.Update();
  22. Uncomment the FeatureDeactivating method.
  23. In the FeatureDeactivating method, get the site collection in a using statement as follows:
    using (var site = properties.Feature.Parent as SPSite)
  24. Ensure the site collection is not null as follows:
    if (site != null)
  25. Create the job name and get the web application ID as follows:
    var jobName = string.Format(CultureInfo.InvariantCulture, FormatJobName, site.ID.ToString());
    
    var webAppId = site.WebApplication.Id;
  26. Using the following code, add a delegate method to be executed by the SPSecurity.RunWithElevatedPrivleges method:
    SPSecurity.RunWithElevatedPrivileges(delegate()
    {
    });
  27. In the delegate method, get the web application as follows:
    var webApplication = SPWebService.ContentService.WebApplications[webAppId];
  28. Delete all timer jobs on the web application that match the job name as follows:
    foreach (SPJobDefinition job in webApplication.JobDefinitions.Where(p => p.Name == jobName))
    job.Delete();
  29. Save the event receiver.

How it works...

A SharePoint timer job can be created for various scopes in the SharePoint farm. These scopes include the farm, a web application, a service application, and so on. In our example, we created a timer job at the web application level with the ID of the site collection. This allows for us to have multiple timer jobs in the web application for various site collections. Our timer job runs daily to ensure all sites in the site collection have the site branding feature enabled.

Using the RunWithElevatedPrivileges method, we can run the code as the SharePoint farm account. This essentially provides full administrator access to the SharePoint farm. As such, this technique should be used sparingly and in limited scopes. When passing variables into the delegate method, it is important to use simple types, such as strings, integers, and GUIDs. Passing complex objects, such as a site collection (SPSite), can result in the objects referencing the wrong SharePoint content.

See also

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.20.68