Get username from SharePoint User field in List - sharepoint

I have a custom sharepoint workflow that I'm developing in Visual Studio. The workflow is running against a document library which has a custom content type connected to it. The content type includes a user lookup field ("owner").
I'm trying to have my workflow assign a task to the "owner" lookup field. However, I've only been able to get the display name for the user, not the account username.
Can anyone help?

Refer to this Article on how to get the User Details from the Field.
public static SPUser GetSPUser(SPListItem item, string key) {
SPFieldUser field = item.Fields[key] as SPFieldUser;
if( field != null) {
SPFieldUserValue fieldValue = field.GetFieldValue(item[key].ToString()) as SPFieldUserValue;
if(fieldValue != null)
return fieldValue.User;
}
return null;
}
Your Code should be like this
SPUser spUser=GetSPUser(splistItem,"Owner");
String sUserName=(spUser!=null)?spUser.UserName:null;

My solution:
public static SPUser GetSPUser(SPListItem item, string key)
{
SPUser user=null;
SPFieldUserValue userValue = new SPFieldUserValue(item.Web, item[key].ToString());
if (userValue != null)
{
SPUser user = userValue.User;
}
return user;
}
How To Call:
SPUser spUser=GetSPUser(splistItem,"Owner");
This is tested code and working fine.

Related

[SharePoint 2010]Value from a User Profile custom field returns Null

In an EventReceiver I call this method GetPernNr on Item Added:
public override void ItemAdded(SPItemEventProperties properties)
{
SPSite site = properties.Web.Site;
using (SPWeb currentWeb = site.OpenWeb(properties.Web.ID))
{
.....
perNr = UserProfileUtils.GetPernNr(currentWeb, assignedTo.ToString());
.....
}
}
where assignedTo is a SPUser.
public static string GetPernNr(SPWeb web, string accountName)
{
string perNr = string.Empty;
UserProfile upUser = null;
try
{
PermissionSet ps = new PermissionSet(System.Security.Permissions.PermissionState.Unrestricted);
ps.Assert();
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite siteColl = new SPSite(web.Site.ID))
{
SPServiceContext serviceContext = SPServiceContext.GetContext(siteColl);
UserProfileManager upm = new UserProfileManager(serviceContext);
if (upm.UserExists(accountName))
{
upUser = upm.GetUserProfile(accountName);
if (upUser["PersonNumber"] != null)
{
perNr = upUser["PersonNumber"].Value.ToString();
}
}
}
});
}
catch (Exception ex)
{
..
}
finally { System.Security.CodeAccessPermission.RevertAssert(); }
return perNr;
}
It's strange, this code works when I try to get value from a default field in UserProfile (Office, Manager, etc). And also works when I call this method outside EventReceiver, but in my case, upUser["PersonNumber"].Value returns null.
Any help will be much appreciated
Did you check the custom property permission in the central admin.
Central Administration -> Edit User Profile Property -> Policy Settings
Make default privacy policy to everyone and then try.
Here is the steps for SharePoint Server 2013:
Central Admin > Application Management > Manage service applications > Your User Profile Application > Manage User
Properties
Select Edit option from property menu.
Now Under "Policy Settings":
Set Default Privacy Setting: Everyone

sharepoint object model itemadding eventreceiver

I am trying to add a event receiver on a list for itemadding. I have a field called EmployeeName people picker from which i need to get userprofile of that particular employee on item adding and trying to get EmployeeNo auto updated from userprofile.
I using as below: but not working
public override void ItemAdding(SPItemEventProperties properties)
{
base.ItemAdding(properties);
UserProfileManager profileManager = new UserProfileManager(context);
UserProfile myProfile = profileManager.GetUserProfile(item["EmployeeName"].ToString());
if (myProfile["EmployeeNo"].Value != null)
{
properties.AfterProperties["EmployeeNo"] = (myProfile["EmployeeNo"]).ToString();
}
item.Update();
}
Please help me on this.
Check if you use the correct internal column names.
Where do you get "item" from? Try using properties.ListItem instead.
Don't call properties.ListItem.update() (or item.update() in your code).

SharePoint 2010: Adding a User to a Group from code

I am trying to add a user to an existing group from a custom login page. Right now, I have no problem getting the current user from SPWeb.CurrentUser. I can view all of this current users groups, but now I am having a problem adding this user to an existing group. I think I need to use SPRoleDefinition and SPRoleAssignment, but all I can find is how to change the permissions on a group using these classes. Does anyone know how I can add this user to a group by the groupname?
Thanks!
You can utilize this function to add user to the current site. You need to pass Group name and UserName.
public void AddUsers(string groupname, string username)
{
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
// Gets a new security context using SHAREPOINT\system
using (SPSite site = new SPSite(SPContext.Current.Site.Url))
{
using (SPWeb thisWeb = site.OpenWeb())
{
thisWeb.AllowUnsafeUpdates = true;
SPUser Name = thisWeb.EnsureUser(username);
thisWeb.Groups[groupname].AddUser(Name);
thisWeb.AllowUnsafeUpdates = false;
}
}
});
}
catch (Exception ex)
{
//Log error here.
}
}
Have you tried any of this?
If you're trying to add a user to a group, this should work:
SPUser currentUser = SPContext.Current.Web.CurrentUser;
SPGroup group = SPContext.Current.Web.SiteGroups["My Group Name"];
group.AddUser(currentUser);
http://msdn.microsoft.com/en-us/library/ms454048.aspx

Get user email programmatically if I have user guid? (SharePoint)

Currently I have a method to get all the users in a site collection and databind this to a dropdown.
private void getUsers()
{
SPGroupCollection collGroups = SPContext.Current.Web.Groups;
foreach (SPGroup oGroup in collGroups)
{
foreach (SPUser oUser in oGroup.Users)
{
ddlSiteOwner.Items.Add(new ListItem(oUser.Name, oUser.ID.ToString()));
}
}
}
Is there a way to get users based on their guid?
I select a user in the dropdown with guid as value and I would like to use this to search for the users email.
I tried something like
private string getUserEmail(string userGuid)
{
string userEmail = null;
SPGroupCollection collGroups = SPContext.Current.Web.Groups;
foreach (SPGroup oGroup in collGroups)
{
foreach (SPUser oUser in oGroup.Users.GetByID(userGuid))
{
userEmail = oUser.Email;
}
}
return userEmail;
}
But with GetByID it wants 32bit integer and not a guid so how would I achieve this?
Thanks in advance.
Edit: saw that users don't have guids but sids now.
The SPUser.ID property you are using in your dropdown is an integer, not a guid.
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spuser.id.aspx
So the GetByID should work normally, just parse the value as an integer.
int.Parse(), or int.TryParse()

Fba roles with SharePoint user groups

I have built custom Membership and Role providers. Users are some clients that belong to the company and I am using Company as a Role.
I would like to create SharePoint Group and add more companies to it (for example type of industry) and then do redirecting and security by the SPGroup.
How do I retrieve SPGroup for the current logged in user ?
I would like to this in my custom Login page so another problem is how do I retrieve SPUser or SPGroup knowing login name ?
This is what I have now:
private List GetGroupsForUser(List roleAccounts)
{
List groups = new List();
SPSecurity.RunWithElevatedPrivileges(
delegate()
{
using (SPSite site = new SPSite(SPContext.Current.Web.Site.ID))
{
SPUserCollection users = site.RootWeb.SiteUsers;
foreach (string account in roleAccounts)
{
SPGroupCollection accGroups = users[account].Groups;
foreach (SPGroup spg in groups)
{
groups.Add(spg);
}
}
}
}
);
return groups;
}
private string GetRoleManagerName()
{
foreach (KeyValuePair setting in SPContext.Current.Site.WebApplication.IisSettings)
{
if (string.IsNullOrEmpty(setting.Value.RoleManager) == false)
return setting.Value.RoleManager.ToLower();
}
return null;
}
private List GetSpAccounts()
{
List roleAccounts = new List();
string roleProviderName = GetRoleManagerName();
foreach (string role in Roles.GetRolesForUser(login.UserName))
{
roleAccounts.Add(roleProviderName + ":" + role.ToLower());
}
return roleAccounts;
}
// and now I can use it
List roleAccounts = GetSpAccounts();
List groups = GetGroupsForUser(roleAccounts);
But I have a felling that I should not have to do this manually like this. How will Target Audience work if only role is added to the group ?
Use the OwnedGroups property of the SPUser class to return the collection of groups owned by a user.
Update misunderstood the question:
Get the currently logged in user: SPContext.Current.Web.CurrentUser
Add that use to a group: SPGroup.Users.Add([username],[email],[name],[notes]);
Update, third times the charm. So you want to find out what group the user is in based on the roles they have?
It's a bit of a combination of the above two attempts at answering it:
var matched = from r in SPContext.Current.Web.CurrentUser.Roles
where r.Name = [Role]
select r.Groups;
Important note that the Roles property won't work in the next version of SharePoint!
Personally I think SPContext.Current.Web.CurrentUser.Groups would be an easier way to figure out what groups the user is in, but it ignores your role requirementment.

Resources