Sunday, April 1, 2012

Create local active directory group and add it to sharepoint site.

Leave a Comment

This post will explain how to  create security group  and assign permission to the group in SharePoint Site.

So before we proceed forward to create security group, we will create a user in local active directory

Firstly we need to get object for the computer on which user is going to be created

 var directoryEntry= new DirectoryEntry("WinNT://" + Environment.MachineName + ",Computer");

Now lets create user with name "TestUser"

DirectoryEntry newUser= directoryEntry.Children.Add("TestUser", "User");

This will create user in local active directory. Now you have to assign values to the properties. For example we will assign password to the user.

newUser.Password = "Password";

Next Step will be to create security group.

We already have directoryEntry object so now we can add new object of type Group to create security group

DirectoryEntry  groupEntry = directoryEntry.Children.Add("TestGroup", "Group");

Now we will add newuser to the new Group

groupEntry .Invoke("Add", new object[] { newUser.Path });

We have now created new user and group,  also added new user to the new group. So we are all set to add this group  to the SharePoint. By adding this security group will automatically assign the group permission to the each and every user inside this security group.  We will create a new Group in Sharepoint and add this security group to that group. This way we can control broad level SharePoint group entity.

SPSite site = new SPSite("site url");
SPWeb web = site.RootWeb;
web.AllowUnsafeUpdates = true;
 web.SiteGroups.Add("MyGroup", web.CurrentUser,web.CurrentUser,"MyGroup users");

SPGroup gGroup = web.SiteGroups["MyGroup"];
SPRoleDefinition roleDefinition = web.RoleDefinitions.GetByType(SPRoleType.Contributor);
var roleAssignment = new SPRoleAssignment(gGroup);

SPUser spUser = web.EnsureUser(SecurityGroupName);
gGroup.Users.Add(spUser.LoginName, "", "", "");
web.AllowUnsafeUpdates = false;

This will assign permission to the group in SharePoint Site