Sunday, January 24, 2010

Ensure a user is registered at a site and is at least a visitor

We recently were presented with a problem where a SharePoint workflow would assign a task to an individual based on our corporate hierarchy.  For example, a task would be assigned to an individual’s manager.  We discovered that if the users didn’t have exclusive rights granted to the site, they were not able to open the task and take their action.  My co-worker came up with the following code that we run when a task is assigned.  This block of code ensures the user is included in the Visitors group so they can access the task that has been assigned to them.

private SPUser EnsureSiteUser( string username )
   SPUser user = null;
   //Get User from workflowProperties object.
   using( SPWeb web = workflowProperties.Web )
       //Ensure user will check to see if user is in site and if not add them.
       user = web.EnsureUser( username );
       // DoesUserHavePermissions will check if user has permission to ViewPages in this case.
       if( !web.DoesUserHavePermissions( user.LoginName, SPBasePermissions.ViewPages ) )
           // If user doesn't have ViewPages Permission we use AssociatedVisitorGroup.Add to add the user to the SharePoint Visitors group.
           web.AssociatedVisitorGroup.AddUser( user );
   return user;