Tuesday, March 6, 2012

Best practice for SharePoint developers to create new objects

When you create SharePoint objects, you may need to clean up the older version of the object before creating it. This is a good practice to avoid multiple instances or wrong content associated with the objects. Here are two examples.

The first is SharePoint timer job example. Before creating the timer job, the best practice is to delete the older version of the job definition. This might save you lots of time to debug since the new timer job may not even be reflected after the deployment due to the timer job cache. Here is the code example.

//Good Practice to delete the older version of Job if it exists
foreach (SPJobDefinition job in webApp.JobDefinitions)
{
      if (job.Name.ToLower() == myJobName.ToLower())
      {
           job.Delete();
      }
}

//Install the job definition
SyncListsJob tempJob = new SyncListsJob (myJobName,webApp);
 
  
//If you want to run it every hour, use SPHourlySchedule class to configure.
//This one will run between 0 to 5 minutes of every hour
  
SPHourlySchedule schedule = new SPHourlySchedule();
schedule.BeginMinute = 0;
schedule.EndMinute = 5;
tempJob.Schedule = schedule;
tempJob.Update();

 
The second is SharePoint role assignment. Before you assign the role, the best practice is to remove all the existing roles so we know exactly what role will be assigned. Here is the example.


SPRoleAssignment roleAssignment;
//update existing role assignment
roleAssignment = rootWeb.RoleAssignments.GetAssignmentByPrincipal(
                (SPPrincipal)rootWeb.SiteGroups[siteGroupOwnerName]);

// Good practice to delete older role assignment before assigning new one
roleAssignment.RoleDefinitionBindings.RemoveAll();
      roleAssignment.RoleDefinitionBindings.Add(rootWeb.RoleDefinitions[permissionLevelName]);
roleAssignment.Update();


The third is web part example. Before add user control to the web part, the best practice is to clear the controls first. Code example is

        protected override void CreateChildControls()
        {
            base.CreateChildControls();
 
            // Best practice to clear the controls first 
Controls.Clear();
            myLabel = new Label();
            myLabel.Text = "This is the best practice";
            Controls.Add(myLabel);
        }

 We should apply the same best practice when creating many other SharePoint objects such as Policy. We are encourage new developers in the team to adopt this best practice.

No comments:

Post a Comment