How do I prepare a solution which does this:
When we add a new user to a Sharepoint Group, it should automatically add the user to an Active Directory Group. This should create two groups with the same users
Why not just have the active directory group as the only member inside of a SharePoint group?
If you want to do it that way, it may have to be an Event Receiver for a Site using the GroupUserAdded event receiver, then you tie into adding that user to Active Directory like so:
using System.DirectoryServices.AccountManagement;
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
// find your user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "USERNAME");
if(user != null)
{
// find the group in question
GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, "ADGROUPNAME");
// if found....
if (group != null)
{
// add user to group
group.Members.Add(user);
group.Save();
}
}
}
You need to create a custom user interface for adding users to the SharePoint Group.
You can use SPGroup
object for adding SPUser
object into the group.
For manipulating Active Directory you can use System.DirectorServices.AccountManagement
namespace. This has GroupPrincipal
object
using (PrincipalContext p = new PrincipalContext(ContextType.Domain, "domainname"))
{
GroupPrincipal g= GroupPrincipal.FindByIdentity(p, "GroupName");
g.Members.Add(p, IdentityType.UserPrincipalName, UserId);
g.Save();
}