0

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

Naveen
  • 1
  • 1

2 Answers2

1

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;
}
Mary Rivers
  • 798
  • 2
  • 9
  • 16
  • You should really include using statements in code example you provided. By doing so code will be more readable. And creating another SPSite/SPWeb objects just to add new user looks like overkill. Keep your example simple. – Vedran Rasol Oct 03 '11 at 15:31
0

What type of roles are you refering to? SPRoles? ASP.NET roles?

SPGroup.AddUser method