1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public static bool IfUserExistInGroup(string username, string groupname)
       {
           PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "DOMAINNAME");
           // find a user
           UserPrincipal user = UserPrincipal.FindByIdentity(ctx, username);
           // find the group in question
           GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, groupname);
           // check if user is member of that group
           if (user.IsMemberOf(group))
           {
               return true;
           }
           else
               return false;
       }

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public static bool ifGroupExist(string groupname)
        {
            PrincipalContext ctx = new PrincipalContext(ContextType.Domain,
                                           "domain",
                                           "admin",
                                           "Password");
            GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx,
                                                       IdentityType.SamAccountName,
                                                       groupname);
            if (grp != null)
            {
                grp.Dispose();
                ctx.Dispose();
                return true;
            }
            else
            {
                ctx.Dispose();
                return false;
            }
        }

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
//if user exist
 public static bool ifUserExist(string username)
        {
            PrincipalContext ctx = new PrincipalContext(ContextType.Domain,
                                           "domain",
                                           "admin",
                                           "password");
            UserPrincipal usr = UserPrincipal.FindByIdentity(ctx,
                                                       IdentityType.SamAccountName,
                                                       username);
            if (usr != null)
            {
                usr.Dispose();
                ctx.Dispose();
                return true;
            }
            else
            {
                ctx.Dispose();
                return false;
            }
        }

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//Find if user is administrator
public static bool IsAdministrator()
        {
            WindowsIdentity identity = WindowsIdentity.GetCurrent();
            if (null != identity)
            {
                WindowsPrincipal principal = new WindowsPrincipal(identity);
                return principal.IsInRole(WindowsBuiltInRole.Administrator);
            }
            return false;
        }

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
//set home directory
public static string setHomeDir(string username, string homeDir)
        {
            PrincipalContext ctx = new PrincipalContext(ContextType.Domain,
                                         "<domain>",
                                         "<admin>",
                                         "<password>");
            UserPrincipal usr = UserPrincipal.FindByIdentity(ctx,
                                                       IdentityType.SamAccountName,
                                                       username);
            if (usr != null)
            {
                if (usr.Enabled == false)
                    usr.Enabled = true;
                usr.HomeDirectory = homeDir;
                try
                {
                    usr.Save();
                }
                catch (Exception e)
                {
                    return e.ToString();
                }
                usr.Dispose();
            }
            else { return "cant find user"; }
            ctx.Dispose();
            return ("succssful");
        }

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
//Create user
public static void createUser(string username, string password, string firstname, string surname, string yearlevel, string homegroup)
        {
            if (ifUserExist(username))
                writeToLogs("user:" + username + " already exist", ADUserlogs);
            else
            {
                PrincipalContext pc = new PrincipalContext(ContextType.Domain,
                                                       "DomainName",
                                                       "AdminName",
                                                       "<Password>");
                UserPrincipal up = new UserPrincipal(pc);
                up.SamAccountName = username;
                up.HomeDirectory = "\\\\FileServer$\\" + username;
                if (!Directory.Exists(up.HomeDirectory))
                {
                    Directory.CreateDirectory(up.HomeDirectory);
                    AddDirectorySecurity(up.HomeDirectory, username, FileSystemRights.FullControl);
                }
                up.EmailAddress = username + "@Email.com";
                up.SetPassword(password);
                up.Enabled = true;
                up.ExpirePasswordNow();
                up.GivenName = firstname;
                up.Surname = surname;
                up.DisplayName = firstname + " " + firstname;
                up.HomeDrive = "U:";
                up.Description = "Year " + yearlevel + " 2014";
                try
                {
                    up.Save();
                    up.Dispose();
                    pc.Dispose();
                }
                catch (Exception E)
                {
                    Console.WriteLine(E.ToString());
                    up.Dispose();
                    pc.Dispose();
                }
                writeToLogs("user:" + username + "at yearlevel:" + yearlevel + "successfully created with password:" + password, ADUserlogs);
                string studentOU;
                if (homegroup != "condition1")
                    studentOU = "OU1"
                else
                    studentOU = "<OU2>";
                moveOU(getDN(username), studentOU);
         }
        }

 

1
2
3
4
5
6
7
8
// create ou
public static void createou(string ou, string rootou)
        {
            string rootOU = rootou;
            DirectoryEntry objAD = new DirectoryEntry(rootOU, "<adminName>i", "<Password>");
            DirectoryEntry objOU = objAD.Children.Add(ou, "OrganizationalUnit");
            objOU.CommitChanges();
        }

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//Change group scope
public static void changeGroupScope(string s, GroupScope gp)
        {
            try
            {
                PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
                // find the group in question
                GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, s);
                group.GroupScope = gp;
                group.Save();
            }
            catch (Exception E)
            {
                writeToLogs(E.ToString() + " --- when try to make changes on group name: " + s, ADGrouplogs);
            }
        }

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//Remove Directory Security
 public static void RemoveDirectorySecurity(string FileName, string Account, FileSystemRights Rights, AccessControlType ControlType)
        {
            // Create a new DirectoryInfo object.
            DirectoryInfo dInfo = new DirectoryInfo(FileName);
            // Get a DirectorySecurity object that represents the 
            // current security settings.
            DirectorySecurity dSecurity = dInfo.GetAccessControl();
            // Add the FileSystemAccessRule to the security settings.
            dSecurity.RemoveAccessRule(new FileSystemAccessRule(Account,
                                                            Rights,
                                                            ControlType));
            // Set the new access settings.
            dInfo.SetAccessControl(dSecurity);
        }

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
//Add  AD security
public static bool AddDirectorySecurity(string FileName, string Account, FileSystemRights Rights)
        {
            try
            {
                // Create a new DirectoryInfo object.
                DirectoryInfo dInfo = new DirectoryInfo(FileName);
                // Get a DirectorySecurity object that represents the 
                // current security settings.
                DirectorySecurity dSecurity = dInfo.GetAccessControl();
                // Add the FileSystemAccessRule to the security settings.
                dSecurity.ResetAccessRule(new FileSystemAccessRule(Account,
           Rights, AccessControlType.Allow));
                dSecurity.AddAccessRule(new FileSystemAccessRule(Account,
            Rights,
            InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
            PropagationFlags.InheritOnly,
            AccessControlType.Allow));
                /*
                dSecurity.AddAccessRule(new FileSystemAccessRule(Account,
                                                                Rights,
                                                                ControlType));
                */
                // Set the new access settings.
                dInfo.SetAccessControl(dSecurity);
                return true;
            }
            catch (Exception E)
            {
                return false;
            }
        }

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// move OU
 public static string moveOU(string userDN, string ou)
        {
            try
            {
                DirectoryEntry NewUser = new DirectoryEntry("LDAP://" + userDN);
                // Use the MoveTo property to define the new container you want to move the object to.
                NewUser.MoveTo(new DirectoryEntry("LDAP://" + ou));
            }
            catch (Exception e)
            {
                writeToLogs("when move :" + userDN + " to " + ou + " , this happened" + e.ToString(), ADOUlogs);
            }
            return ("success");
        }

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
//get Distinguish Name
public static string getDN(string username)
        {
            PrincipalContext ctx = new PrincipalContext(ContextType.Domain,
                                           "<domain Name>",
                                           "<AdminName>",
                                           "Password");
            UserPrincipal usr = UserPrincipal.FindByIdentity(ctx,
                                                       IdentityType.SamAccountName,
                                                       username);
            if (usr != null)
            {
                string temp = usr.DistinguishedName.ToString();
                usr.Dispose();
                ctx.Dispose();
                return temp;
            }
            else
            {
                ctx.Dispose();
                return "cant find user";
            }
        }

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
//add user to a group
public static string AddUserToGroup(string userId, string groupName)
        {
            if (ifUserExist(userId))
            {
                if (!IfUserExistInGroup(userId, groupName))
                {
                    try
                    {
                        PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
                        // find the group in question
                        GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, groupName);
                        UserPrincipal user = UserPrincipal.FindByIdentity(ctx, userId);
                        group.Members.Add(user);
                        group.Save();
                        group.Dispose();
                        user.Dispose();
                        ctx.Dispose();
                    }
                    catch (System.DirectoryServices.AccountManagement.PrincipalExistsException)
                    {
                        return userId + " is already a member of " + groupName;
                    }
                    catch (System.DirectoryServices.DirectoryServicesCOMException E)
                    {
                        return E.Message.ToString() + "WHen try to add: " + userId + " to group:" + groupName;
                    }
                    return userId + " is successfully added to " + groupName;
                }
                else
                    return userId + " is already a member of " + groupName;
            }
            else
                return userId + " is not exist";
        }

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
//empty active directory group
 public static string emptyGroup(string groupname)
        {
            string output = "Empty Group started";
            PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
            // find the group in question
            GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, groupname);
            // if found....
            if (group != null)
            {
                // iterate over members
                foreach (Principal p in group.GetMembers())
                {
                    UserPrincipal theUser = p as UserPrincipal;
                    if (theUser != null)
                    {
                        group.Members.Remove(theUser);
                        try
                        {
                            group.Save();
                        }
                        catch (Exception e)
                        {
                            output = e.ToString();
                        }
                        finally { }
                    }
                }
            }
            return output;
        }

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//create active directory group
public static string createGroup(string Path, string name)
        {
            if (!DirectoryEntry.Exists(Path))
            {
                try
                {
                    DirectoryEntry entry = new DirectoryEntry(Path);
                    DirectoryEntry group = entry.Children.Add("CN=" + name, "group");
                    group.Properties["sAmAccountName"].Value = name;
                    group.CommitChanges();
                    return "group: " + name + " has been created ";
                }
                catch (Exception e)
                {
                    return e.Message.ToString();
                }
            }
            else
            {
                return emptyGroup(name);
            }
        }

 

Advertisements