Obtain an SPUser from an SPWeb 'web':
SPUser user = web.EnsureUser("UserName"); // it may throw an exception "The specified user could not be found"
Check if an SPUser belongs to an SPGroup:
bool belongs = false; try { SPUser test = group.Users[userName]; belongs = true; } catch (Exception exc) { if (exc.Message == "User cannot be found.") belongs = false; else throw; }
Check if the current user is the site admin:
if (SPContext.Current.Web.CurrentUser.IsSiteAdmin) { // the user is the site admin }
Create a user using a membership provider. The membership provider has to be configured in advance:
using System; using System.Web.Security; using Microsoft.SharePoint; Guid key = Guid.NewGuid(); MembershipCreateStatus status; MembershipUser user = Membership.CreateUser("username", "password", "test@test.com", "security question?", "security answer", true, key, out status); if (status == System.Web.Security.MembershipCreateStatus.Success) { SPWeb web = SPContext.Current.Web; try { web.AllowUnsafeUpdates = true; SPUser newUser = web.EnsureUser("username"); SPGroup group = web.Groups["group"]; group.AddUser(newUser); } finally { web.AllowUnsafeUpdates = false; } }
Get the user name inside an event receiver:
SPUserCollection users = properties.Web.Site.RootWeb.AllUsers; var currUser = users.Cast<SPUser>().Where(user => user.ID == properties.CurrentUserId).FirstOrDefault(); if (currUser != null) { string name = currUser.Name; // ... }
Check if the user has appropriate permissions and if s/he is a member of 'myUserGroup':
// This code should be executed within an event receiver. if (properties.Web.DoesUserHavePermissions(SPBasePermissions.ViewListItems)) { SPUser user = properties.Web.SiteUsers[properties.UserLoginName]; SPGroupCollection groups = user.Groups; var group = groups.Cast<SPGroup>().Where(g => g.Name == myUserGroup).FirstOrDefault(); if (group == null) { properties.Cancel = true; properties.ErrorMessage = "The user has to be a member of the " + myUserGroup + " group."; properties.Status = SPEventReceiverStatus.CancelWithError; } }
Check if a user has certain permissions using the elevated privileges context:
private bool HasPermissions(SPUser user) { bool hasAccess = true; SPSecurity.RunWithElevatedPrivileges(delegate() { // Check access to the list. if (!list.DoesUserHavePermissions(user, SPBasePermissions.ViewListItems)) hasAccess = false; // Check access to the list item. if (item != null && !item.DoesUserHavePermissions(user, SPBasePermissions.ViewListItems) && !item.DoesUserHavePermissions(user, SPBasePermissions.OpenItems)) hasAccess = false; }); return hasAccess; }
Check if a user is the site collection administrator or if she belongs to the associated owner group:
// Get the current user. SPUser user = SPContext.Current.Web.CurrentUser; // Check if the current user is a site collection admin. if (user.IsSiteAdmin) { // ... the user is the site collection administrator } else { foreach (SPGroup group in user.Groups) { string groupName = group.Name.ToLower().Trim(); if (SPContext.Current.Web.AssociatedOwnerGroup != null && groupName.ToLower() == SPContext.Current.Web.AssociatedOwnerGroup.Name.ToLower()) { // ... the user belongs to the associated owner group } else { // ... } } }
Obtain a user email from a list that contains a field type SPUser:
// 'val' is a value to convert into a field type value // e.g. 'val' could be properties.ListItem["Employee"].ToString() in an event receiver SPFieldUserValue userValue = (SPFieldUserValue)((SPFieldUser)field).GetFieldValue(val); if (userValue != null && userValue.User != null) { string email = userValue.User.Email; }
Enumerate all fields in a list and if a field is of type SPUser, obtain its email and name:
foreach (SPField field in myList.Fields) { if (field is SPFieldUser) { object fieldValue = properties.ListItem[field.StaticName]; if (fieldValue != null) { SPFieldUserValue userValue = (SPFieldUserValue)field.GetFieldValue(fieldValue.ToString()); SPUser user = userValue.User; // user.Name, user.Email // ... } } }
Enumerate all groups the current user belongs to:
private void DisplayUserGroups() { // Get the current user. SPUser user = SPContext.Current.Web.CurrentUser; foreach (SPGroup group in user.Groups) { Console.WriteLine(group.Name); } Console.WriteLine("Groups associated with the site:"); if (SPContext.Current.Web.AssociatedOwnerGroup != null) Console.WriteLine("AssociatedOwnerGroup: " + SPContext.Current.Web.AssociatedOwnerGroup.Name); if (SPContext.Current.Web.AssociatedMemberGroup != null) Console.WriteLine("AssociatedMemberGroup: " + SPContext.Current.Web.AssociatedMemberGroup.Name); if (SPContext.Current.Web.AssociatedVisitorGroup != null) Console.WriteLine("AssociatedVisitorGroup: " + SPContext.Current.Web.AssociatedVisitorGroup.Name); }