Tuesday, April 15, 2014

Accessing List or Library in Custom SharePoint TimerJob code of a site without Hard-codding site URL/ID

When we write any custom SharePoint timer job using visual studio, some times, we may need to access values from a list / library. and in such cases, some times you may not be predict the site ID/URL in which the list / library present.

In such scenario's the best options is to develop a feature with "site" scope. and use this feature to create timer job instance and also to get required list object. This feature GUID will be used for getting site collection where your list/library exists.

Once after creating feature, note down the GUID and now go to execute method of your timer job. In that method, you get the webapplication object and iterate through all its site collection. Now find the site collection in which the above feature with GUID is activated. Take that site collection as your SPSite object and access your required lists.

In this way, you can avoid hard coding site URL or ID. only thing you have to make sure is, this feature should be activated only in your required site collection.


Example: You have to write a timer job that will execute every week on sunday. And this job should read items from a master list called "EmployeesToBeNotified" which contains all employees to whom you have to send notifications using email.

Sample Code:

 public override void Execute(Guid targetInstanceId)
        {
               SPSecurity.RunWithElevatedPrivileges(delegate
                {
                    System.Diagnostics.EventLog.WriteEntry("TimeSheet TimerJob", "TimeSheet TimerJob Executed");
                     SPWebApplication webAppNew = (SPWebApplication)this.Parent;
                     if (webAppNew.Sites.Count > 0)
                     {
                         Guid NewSiteID =new Guid();
                         foreach (SPSite timesheetSite in webAppNew.Sites)
                         {
                             Guid featureGuid = new Guid("d5ef5623-270a-4c8c-b4c5-784b82306b87");
                             if (timesheetSite.Features[featureGuid] != null)
                             {
                                 NewSiteID = timesheetSite.ID;
                                 timesheetSite.Dispose();
                                 break;
                             }
                       
                         } //close of foreach

                             using (SPSite site = new SPSite(NewSiteID))
                               {
                                    //write your required code here.
                                }

                     } //close of outer if
                 });       //close of spsecurity
     } //close of execute method



hope it is helpful.

happy coding :)

No comments:

Post a Comment