Showing posts with label and assign user to group in SharePoint using Visual Studio 2010. Show all posts
Showing posts with label and assign user to group in SharePoint using Visual Studio 2010. Show all posts

Sunday, 2 December 2012

Programmatically how to assign user to SharePoint group

Assign a user to group:

In this example, i wanna show how to create group, assign role to the group and assign a user to the group.

            using (SPSite site = new SPSite("http://UKREDDY:6969/"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    web.AllowUnsafeUpdates = true;
                    web.SiteGroups.Add("UdayGroup", web.CurrentUser, web.CurrentUser, "This is Test Group for adding users to group.");
                    SPGroup group = web.SiteGroups["UdayGroup"];
                    SPRoleDefinition roleDefinition = web.RoleDefinitions.GetByType(SPRoleType.Contributor);
                    SPRoleAssignment roleAssigment = new SPRoleAssignment(group);
                    roleAssigment.RoleDefinitionBindings.Add(roleDefinition);
                    web.RoleAssignments.Add(roleAssigment);
                    web.Update();
                    SPUser spUser = web.EnsureUser("ukreddysykam\\urkeddy");
                    group.Users.Add(spUser.LoginName, spUser.Email, spUser.Name, spUser.Notes);
                    web.AllowUnsafeUpdates = false;
                }
            }