Tuesday, June 9, 2015

SP2013 - Programmatically filter workflow task list for tasks assigned to current user or his group

If you are using SharePoint workflows (default or custom), you are probably using tasks and Workflow Task List. In the default view of that list, every user can approve every task in the list. This could be a big problem, because, if users have option to do something wrong, they will probably do it. Usually, the requirement is that users are allowed to see only their own tasks.

If you want to do this programmatically, it is easy to make caml query that would filter tasks for a logged in user, but what if task is assigned to a SP group and current user is a member of that group? Fortunately, this is a simple task too.

For this example, I created SharePoint console application in Visual Studio. This example fetches your Workflow Task List, gets the default view of that list and sets the filter on the list items. It filters tasks that are assigned to current user and tasks assigned SP groups that user is a member of. This is the code:




namespace SharePointConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            using (SPSite site = new SPSite("http://dev/mySite"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPList list = web.Lists["WorkflowTaskList"];

                    for (int i = 0; i < list.Views.Count; i++)
                    {
                        SPView view = list.Views[i];
                        if (view.DefaultView)
                        {
                            web.AllowUnsafeUpdates = true;
                            view.Query = @"<Where>
                                           <Or>
                                             <Eq>
                                               <FieldRef Name='AssignedTo'/>
                                               <Value Type='Integer'><UserID/></Value>
                                             </Eq>
                                             <Membership Type='CurrentUserGroups'>
                                             <FieldRef Name='AssignedTo'/></Membership>
                                           </Or>
                                         </Where>";
                            view.Update();
                            web.AllowUnsafeUpdates = false;
                        }
                    }
                }
            }
        }
    }
}




Source:
https://msdn.microsoft.com/en-us/library/office/aa544234.aspx?f=255&MSPPError=-2147217396

1 comment: