Is task assigned to user

SP2013

Hello everyone,

Today I’ll talk about a piece of code that I used recently to determine whether a workflow task is assigned to the person who created it.

The following code shows whether a task is assigned to the task creator or to one of his groups, even if it is not added namely in the SharePoint group but via an Active Directory group.

Firstly, we first obtain the value of fields “Created by” and “Assigned To”

SPFieldUser authorUserField = (SPFieldUser)task.Fields.GetField(“Author”);

SPFieldUserValue authorUserFieldValue = (SPFieldUserValue)authorUserField.GetFieldValue(task[“Author”].ToString());

 

SPFieldUser assignedUserField = (SPFieldUser)task.Fields.GetField(“AssignedTo”);

SPFieldUserValue assignedUserFieldValue = (SPFieldUserValue) assignedUserField.GetFieldValue(task[“AssignedTo”].ToString());

 

We test first whether the field “assigned to” contains a user

If (assignedUserFieldValue.User!=null)

{

SPUser assignedUser = assignedUserFieldValue.User;

isAssignedToUser =(assignedUser.ToString() == authorUserFieldValue.User.ToString());

}

 

If this is not the case , we test whether the group contains the user wanted.

To do this, we will use the “SPGroup.ContainsCurrentUser” function which also works if the user is part of an active directory group added to SharePoint group!

To use this function, we will use the usertoken of the desired user.

 

Here’s the code to do this:

isAssignedToCurrentUser=false;

SPGroup assignedGroup = task.Web.SiteGroups.GetByID(assignedUserFieldValue.LookupId) ;

SPSecurity.RunWithElevatedPrivileges( delegate

{

using(SPSite elevatedSite = new SPSite (task.Web.Site.ID))

{

using(SPWeb elevatedWeb = elevatedSite.OpenWeb(task.Web.ID))

{

SPuser currentUser = elevatedWeb.EnsureUser(authorUserFieldValue.User.LoginName);

If (currentUser !=null)

{

using (SPSite currentUserSite = new SPSite(task.web.Site.ID,currentUser.UserToken))

{

using (SPweb currentUserweb = currentUserSite.OpenWeb(task.Web.ID))

{

isAssignedToCurrentUser=assignedGroup.ContainsCurrentUser;

}

}

}

}

} 

});

 

With this code, there is a case that is not managed, when the task is directly assigned to the active directory group.

Hope this helps.

Christopher.

Advertisements
This entry was posted in SharePoint 2013 and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s