Sunday 30 November 2014

C# Active Directory fuctions

//Check user exist in a group
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;
 
       }
//Check if group exist
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;
            }
 
 
        }
//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;
            }
 
 
        }

//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;
        }
//set home directory 
public static string setHomeDir(string username, string homeDir)
        {
            PrincipalContext ctx = new PrincipalContext(ContextType.Domain,
                                         "",
                                         "",
                                         "");
 
            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");
 
 
        }
//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",
                                                       "");
                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 = "";
                moveOU(getDN(username), studentOU);
 
         }
        }

// create ou
public static void createou(string ou, string rootou)
        {
            string rootOU = rootou;
            DirectoryEntry objAD = new DirectoryEntry(rootOU, "i", "");
            DirectoryEntry objOU = objAD.Children.Add(ou, "OrganizationalUnit");
            objOU.CommitChanges();
        }

//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);
            }
 
 
        }

//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);
 
        }

//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;
            }
 
 
        }

// 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");
        }

//get Distinguish Name
public static string getDN(string username)
        {
            PrincipalContext ctx = new PrincipalContext(ContextType.Domain,
                                           "",
                                           "",
                                           "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";
            }
 
 
 
        }
//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";
 
        }
//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;
        }
//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);
            }
        }
 

No comments:

Post a Comment