Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

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

share|improve this question

2 Answers 2

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;
}
share|improve this answer
    
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 3 '11 at 15:31

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

SPGroup.AddUser method

share|improve this answer
    
I want to add as sproles... –  Naveen Oct 4 '11 at 4:39

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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