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

2 Answers 2

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;
}
1
  • 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. Commented Oct 3, 2011 at 15:31
0

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

SPGroup.AddUser method

1
  • I want to add as sproles...
    – Naveen
    Commented Oct 4, 2011 at 4:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.