SharePoint + Visual Studio + Get Current User
A frequently asked question in the MSDN forums is “how you can get access to the user who is interacting with your workflow?”. For example, the user modifying a task. The workflow is likely running in a different context and/or session to your browser session so there’s not an obvious tie-up.
However, in this scenario, you can get the login name of the person who modified the SharePoint task, via the Executor property of the OnTaskChanged event. Simply bind the Executor property to a string (e.g., “taskLastModifiedBy”) and whenever the task changes, SharePoint will copy the user ID to this property in the format of DOMAIN\LoginName. You can then get an SPUser object for that login name with, e.g.
SPUser user = workflowProperties.Web.AllUsers[taskLastModifiedBy];
Note: On a related subject, and the thing that prompted this post - if you’re trying to update a Person or Group field on your workflowProperties.Item, then you must pass it an SPUser object! This is bizarre, because other types of list (e.g, the task list) you can pass it a string and SharePoint will do the rest. I spent ages and all kinds of different things and always getting the “Invalid data has been used to update the list item. The field you are trying to update may be read only.” error. Annoying.
What if you don’t have a Web.AllUsers? Well, I don’t know why you wouldn’t. But as part of the things I was trying, I started trying to user the UserGroup.asmx web service to get access to the user. So not necessary here, but this code might come in handy in the future.
First thing you need to do is create a web service proxy. In VS, right click your project > Add Service Reference > Advanced > Add Web Reference. In the URL field type
http:
Give the reference a name (e.g., UserGroupProxy) and click OK. You’ll also need to import/using System.Xml. Your code to query the web service might look like this:
`
private string GetNameForUserID(string loginName)
{
UGProxy.UserGroup userGroupSvc = new UGProxy.UserGroup();
userGroupSvc.Credentials = System.Net.CredentialCache.DefaultCredentials;
userGroupSvc.Url = “http://
XmlNode ndUser = userGroupSvc.GetUserInfo(loginName);
return ndUser.FirstChild.Attributes[“Name”].Value;
}
string name = GetNameForUserID(taskLastModifiedBy);
`
Note that it’s not strictly necessary to set the URL property - but I demonstrate it here because it will be useful if you’re deploying your code through different environments. And also note it returns the value of the Name attribute. The full XML can be found here: http://msdn.microsoft.com/en-us/library/ms774637.