/// <summary>
/// Add a user to a Sharepoint group
/// </summary>
/// <param name="userLoginName">Login name of the user to add</param>
/// <param name="userGroupName">Group name to add</param>
private void AddUserToAGroup(string userLoginName, string userGroupName)
{
//Executes this method with Full Control rights even if the user does not otherwise have Full Control
SPSecurity.RunWithElevatedPrivileges(delegate
{
//Don't use context to create the spSite object since it won't create the object with elevated privileges but with the privileges of the user who execute the this code, which may casues an exception
using (SPSite spSite = new SPSite(Page.Request.Url.ToString()))
{
using (SPWeb spWeb = spSite.OpenWeb())
{
try
{
//Allow updating of some sharepoint lists, (here spUsers, spGroups etc...)
spWeb.AllowUnsafeUpdates = true;
/// Add a user to a Sharepoint group
/// </summary>
/// <param name="userLoginName">Login name of the user to add</param>
/// <param name="userGroupName">Group name to add</param>
private void AddUserToAGroup(string userLoginName, string userGroupName)
{
//Executes this method with Full Control rights even if the user does not otherwise have Full Control
SPSecurity.RunWithElevatedPrivileges(delegate
{
//Don't use context to create the spSite object since it won't create the object with elevated privileges but with the privileges of the user who execute the this code, which may casues an exception
using (SPSite spSite = new SPSite(Page.Request.Url.ToString()))
{
using (SPWeb spWeb = spSite.OpenWeb())
{
try
{
//Allow updating of some sharepoint lists, (here spUsers, spGroups etc...)
spWeb.AllowUnsafeUpdates = true;
SPUser spUser = spWeb.EnsureUser(userLoginName);
if (spUser != null)
{
SPGroup spGroup = spWeb.Groups[userGroupName];
{
SPGroup spGroup = spWeb.Groups[userGroupName];
if (spGroup != null)
spGroup.AddUser(spUser);
}
}
catch (Exception ex)
{
//Error handling logic should go here
}
finally
{
spWeb.AllowUnsafeUpdates = false;
}
}
}
spGroup.AddUser(spUser);
}
}
catch (Exception ex)
{
//Error handling logic should go here
}
finally
{
spWeb.AllowUnsafeUpdates = false;
}
}
}
});
}
}
No comments:
Post a Comment