i want to add a user to a spgroup with specified roles can any one help to write the code in visual webpart?
thanks Naveen
You may need to customized it for your requirements. Sorry I left out the 2nd half where SPGroup plays role. (run under using or add dispose, add try n catch as well)
//Open Site
SPSite spSite = new SPSite(strSiteURL);
SPWeb spWeb = spSite.OpenWeb();
if(spUser == null)
{
spUser = CreateUser(strLoginName, strEMail, strName, strNotes, strSiteURL);
}
//Open group
SPGroup spGroup = spWeb.SiteGroups[strGroup];
//Add and update group with new user
spGroup.AddUser(spUser.LoginName, spUser.Email, spUser.Name, "Added by UserControl");
spGroup.Update();
private SPUser CreateUser(string strLoginName, string strEMail,
string strName, string strNotes, string strSiteURL)
{
SPUser spReturn = null;
SPSite spSite = null;
SPWeb spWeb = null;
try
{
//Open the SharePoint site
spSite = new SPSite(strSiteURL);
spWeb = spSite.OpenWeb();
//Assign role and add user to site
SPRoleAssignment spRoleAssignment =
new SPRoleAssignment(strLoginName, strEMail, strName, strNotes);
//Using Contribute, might need high access
SPRoleDefinition spSPRoleDefinition =
spWeb.RoleDefinitions["Contribute"];
spRoleAssignment.RoleDefinitionBindings.Add(spSPRoleDefinition);
spWeb.RoleAssignments.Add(spRoleAssignment);
//Update site
spWeb.Update();
spReturn = spWeb.AllUsers[strLoginName];
}
catch(Exception)
{
}
finally
{
spWeb.Close();
spSite.Close();
}
return spReturn;
}
What type of roles are you refering to? SPRoles? ASP.NET roles?