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())

//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;

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(

// Good practice to delete older role assignment before assigning new one

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()
            // Best practice to clear the controls first 
            myLabel = new Label();
            myLabel.Text = "This is the best practice";

 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