Exemple #1
0
        private IEnumerable <ActiveDirectoryComputerViewModel> ShowComputers(string DomainName, string Container, out string error)
        {
            IList <ActiveDirectoryComputerViewModel> computers = new List <ActiveDirectoryComputerViewModel>();

            try
            {
                //string stringDomainName = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;
                int intCounter = 0;
                PrincipalContext  PrincipalContext1  = new PrincipalContext(ContextType.Domain, DomainName, Container);
                ComputerPrincipal ComputerPrincipal1 = new ComputerPrincipal(PrincipalContext1);
                PrincipalSearcher search             = new PrincipalSearcher(ComputerPrincipal1);
                foreach (ComputerPrincipal result in search.FindAll())
                {
                    ActiveDirectoryComputerViewModel Computer1 = new ActiveDirectoryComputerViewModel();
                    Computer1.SamAccountName = result.SamAccountName;
                    Computer1.DisplayName    = result.DisplayName;
                    Computer1.Name           = result.Name;
                    Computer1.Description    = result.Description;
                    Computer1.Enabled        = result.Enabled;
                    Computer1.LastLogon      = result.LastLogon.HasValue ? ((DateTime)result.LastLogon).ToString("yyyy/MM/dd HH:mm:ss") : null;

                    computers.Add(Computer1);
                    intCounter++;
                }
                search.Dispose();
                error = null;
            }
            catch (Exception ex)
            {
                error = ex.Message;
            }
            return(computers);
        }
Exemple #2
0
 //search Active directory for computers
 static public string GetComputer(string name)
 {
     //domain connection
     using (var pc = new PrincipalContext(ContextType.Domain, "Domain Name"))
     {
         //search through all computer objects in ad for matching name
         ComputerPrincipal computer = ComputerPrincipal.FindByIdentity(pc, IdentityType.Name, name);
         if (computer != null)
         {
             DataTable tempTable = new DataTable();
             //save computer name & last logon for table
             tempTable.Columns.Add("Name", typeof(string));
             tempTable.Columns.Add("LastLogon", typeof(DateTime));
             //convert time to est
             DateTime easternTime = Utils.ConvertUTCToEST(computer.LastLogon.Value);
             tempTable.Rows.Add(computer.Name, easternTime);
             //finalize string for webpage
             return(Utils.ConvertDataTableToHTML(tempTable, "adComputer"));
         }
         else
         {
             return("<br>Computer not found in AD<br><br>");
         }
     }
 }
Exemple #3
0
        private bool MemberEnumeration(Domain enumDomain)
        {
            Status("Enumerating member servers");
            try
            {
                PrincipalContext  _pContext   = new PrincipalContext(ContextType.Domain, enumDomain.Name);
                ComputerPrincipal _cPrincipal = new ComputerPrincipal(_pContext);
                PrincipalSearcher _pSearcher  = new PrincipalSearcher();

                _cPrincipal.Name       = "*";
                _pSearcher.QueryFilter = _cPrincipal;

                PrincipalSearchResult <Principal> _pResults = _pSearcher.FindAll();
                foreach (ComputerPrincipal _member in _pResults)
                {
                    if (!checkNode(_DomainControllers, $"{_member.Name}.{enumDomain.Name}"))
                    {
                        _MemberServers.Nodes.Add($"{_member.Name}.{enumDomain.Name}").Tag = _member;
                    }
                }
            }
            catch (Exception _ex)
            {
                Status($"Error enumerating member services - PROVIDE TO SUPPORT - UNKNKOWN ({_ex.GetType().Name}:{_ex.HResult})");
                return(false);
            }
            Status("Enumerated member servers");
            return(true);
        }
Exemple #4
0
 public static List <Computer> QueryAllMachinesAD(string searchText, Category type)
 {
     using (PrincipalContext context = new PrincipalContext(ContextType.Domain, ADContext.DomainSimpleName))
     {
         ComputerPrincipal comp = new ComputerPrincipal(context);
         if (type == Category.Name)
         {
             comp.Name = "*" + searchText + "*";
         }
         if (type == Category.Description)
         {
             comp.Description = "*" + searchText + "*";
         }
         PrincipalSearcher searcher = new PrincipalSearcher();
         searcher.QueryFilter = comp;
         try
         {
             List <Computer>     computers = new List <Computer>();
             var                 results   = searcher.FindAll().Cast <ComputerPrincipal>();
             ComputerPrincipal[] comps     = results.ToArray();
             for (int i = 0; i < comps.Length; i++)
             {
                 computers.Add(new Computer(comps[i].Name, comps[i].Description));
             }
             return(computers);
         }
         catch (Exception e)
         {
             MessageBox.Show(e.Message);
             return(null);
         }
     }
 }
        public void TestConstructors()
        {
            using var context = new PrincipalContext(ContextType.Machine);

            using (var principal = new ComputerPrincipal(context))
            {
                Assert.Same(context, principal.Context);
                Assert.Empty(principal.ServicePrincipalNames);
                Assert.Equal(ContextType.Machine, principal.ContextType);
            }
            Assert.Throws <ArgumentException>(() => new ComputerPrincipal(null));
            Assert.Throws <ArgumentException>(() => new ComputerPrincipal(null, "samAccountName", "password", true));
            Assert.Throws <ArgumentException>(() => new ComputerPrincipal(context, null, "password", true));
            Assert.Throws <ArgumentException>(() => new ComputerPrincipal(context, "samAccountName", null, true));

            using (var principal = new UserPrincipal(context))
            {
                Assert.Same(context, principal.Context);
                Assert.Equal(ContextType.Machine, principal.ContextType);
            }
            Assert.Throws <ArgumentException>(() => new UserPrincipal(null));
            Assert.Throws <ArgumentException>(() => new UserPrincipal(null, "samAccountName", "password", true));
            Assert.Throws <ArgumentException>(() => new UserPrincipal(context, null, "password", true));
            Assert.Throws <ArgumentException>(() => new UserPrincipal(context, "samAccountName", null, true));

            using (var principal = new GroupPrincipal(context))
            {
                Assert.Same(context, principal.Context);
                Assert.Equal(ContextType.Machine, principal.ContextType);
            }
            Assert.Throws <ArgumentException>(() => new GroupPrincipal(null));
            Assert.Throws <ArgumentException>(() => new GroupPrincipal(null, "samAccountName"));
            Assert.Throws <ArgumentException>(() => new GroupPrincipal(context, null));
        }
Exemple #6
0
        private void tbpAdvanced_Enter(object sender, EventArgs e)
        {
            Thread thloadAdvanced = new Thread(() =>
            {
                try
                {
                    Thread.CurrentThread.Name = "thloadAdvanced";
                    this.Invoke((MethodInvoker) delegate { pBoxProgressAdvanced.Visible = true; });

                    ADLib LdapHelper           = new ADLib();
                    ComputerPrincipal computer = ComputerPrincipal.FindByIdentity(new PrincipalContext(ContextType.Domain, frmMain.domainAccountData[0], frmMain.domainAccountData[1], frmMain.domainAccountData[2]), this.machineToQuery);
                    System.DirectoryServices.DirectoryEntry underField = computer.GetUnderlyingObject() as System.DirectoryServices.DirectoryEntry;
                    DataTable advancedData = LdapHelper.FillDataTableFromADContainer(underField);
                    this.Invoke((MethodInvoker) delegate
                    {
                        dGridAdvanced.DataSource       = advancedData;
                        dGridAdvanced.Columns[1].Width = 300;
                        pBoxProgressAdvanced.Visible   = false;
                    });
                }
                catch { Thread.CurrentThread.Abort(); }
            });

            thloadAdvanced.Start();
        }
Exemple #7
0
        /// <summary>
        ///     Gets the search computer data.
        /// </summary>
        /// <param name="principalContext">The principal context.</param>
        /// <returns>IEnumerable&lt;ExpandoObject&gt;.</returns>
        /// TODO Edit XML Comment Template for GetSearchComputerData
        private IEnumerable <ExpandoObject> GetSearchComputerData(
            PrincipalContext principalContext)
        {
            var data = new List <ExpandoObject>();

            using (var principal = new ComputerPrincipal(principalContext))
            {
                principal.Name = Asterisk + SearchText + Asterisk;
                using (var principalSearcher = new PrincipalSearcher(principal))
                    using (var principalSearchResult = principalSearcher.FindAll())
                    {
                        foreach (var computerPrincipal in principalSearchResult
                                 .GetComputerPrincipals())
                        {
                            CancellationToken.ThrowIfCancellationRequested();
                            data.Add(
                                DataPreparer.PrepareData(
                                    DefaultComputerProperties,
                                    computerPrincipal));
                        }
                    }
            }

            return(data);
        }
Exemple #8
0
        /// <summary>
        /// Constructor that instantiates an AdComputer object with values of the attributes of the
        /// specified ComputerPrincipal object.
        /// </summary>
        /// <param name="computer"></param>
        public AdComputer(ComputerPrincipal computer)
        {
            this.AccountExpirationDate = computer.AccountExpirationDate.ToString();
            this.AccountLockouttime    = computer.AccountLockoutTime.ToString();
            this.BadLogonCount         = computer.BadLogonCount;
            this.DelegationPermitted   = computer.DelegationPermitted;
            this.Description           = computer.Description;
            this.DisplayName           = computer.DisplayName;
            this.DistinguishedName     = computer.DistinguishedName;
            this.Enabled                = computer.Enabled;
            this.Guid                   = computer.Guid.ToString();
            this.HomeDirectory          = computer.HomeDirectory;
            this.HomeDrive              = computer.HomeDrive;
            this.LastBadPasswordAttempt = computer.LastBadPasswordAttempt.ToString();
            this.Name                   = computer.Name;
            this.PasswordNeverExpires   = computer.PasswordNeverExpires;
            this.PasswordNotRequired    = computer.PasswordNotRequired;
            this.SamAccountName         = computer.SamAccountName;
            this.ScriptPath             = computer.ScriptPath;

            List <string> svcPNs = new List <string>();

            foreach (var spn in computer.ServicePrincipalNames)
            {
                svcPNs.Add(spn);
            }
            this.ServicePrincipalNames = svcPNs;

            this.Sid = computer.Sid.Value;
            this.SmartcardLogonRequired   = computer.SmartcardLogonRequired;
            this.UserCannotChangePassword = computer.UserCannotChangePassword;
            this.UserPrincipalName        = computer.UserPrincipalName;
        }
Exemple #9
0
 /// <summary>
 /// Retire une machine dans un groupe donné.
 /// </summary>
 /// <param name="groupName"></param>
 /// <param name="computerName"></param>
 public void RemoveComputerToGroup(string groupName, string computerName)
 {
     try
     {
         using (GroupPrincipal group = GroupPrincipal.FindByIdentity(_adConnection, IdentityType.Name, groupName))
         {
             if (group != null)
             {
                 ComputerPrincipal computer = ComputerPrincipal.FindByIdentity(_adConnection, IdentityType.Name, computerName);
                 if (computer != null)
                 {
                     Logger?.Info("Ajout de PC : " + computerName + " dans le groupe " + groupName);
                     group.Members.Remove(computer);
                     group.Save();
                 }
                 else
                 {
                     Logger?.Warn("Le PC : " + computerName + " n'existe pas !");
                 }
             }
             else
             {
                 Logger?.Warn("Le groupe : " + groupName + " n'existe pas !");
             }
         }
     }
     catch (Exception exception)
     {
         Logger?.Error("Error RemoveComputerToGroup - groupName : " + groupName
                       + " - computerName : " + computerName, exception);
     }
 }
        /// <summary>
        /// AD Sunucusundan kayıtlı tüm bilgisayar listesini getirir.
        /// </summary>
        /// <returns> Bilgisayar Listesini döner </returns>
        public IEnumerable <ComputersProperties> GetAllComputers()
        {
            List <ComputersProperties> computerPropertiesList = new List <ComputersProperties>();

            try
            {
                using (var principialContext = _computer.SetPrincipialContext())
                    using (var computerPrincipial = _computer.SetComputerPrincipial(principialContext))
                        using (var principialSearcher = _computer.SetPrincipialSearcher())
                        {
                            computerPrincipial.Name        = "*";
                            principialSearcher.QueryFilter = computerPrincipial;
                            PrincipalSearchResult <Principal> _computerSearchResult = principialSearcher.FindAll();
                            foreach (var p in _computerSearchResult)
                            {
                                ComputerPrincipal pc       = (ComputerPrincipal)p;
                                string            ipAdress = GetComputerIpAddress(p.Name);
                                var computerPro            = new ComputersProperties(pc.Name, pc.Sid.ToString(), ipAdress, pc.LastPasswordSet.ToString(), pc.LastBadPasswordAttempt.ToString());
                                computerPropertiesList.Add(computerPro);
                            }
                        }
            }

            catch (Exception ex)
            {
                errorMessage = ex.Message;
            }

            return(computerPropertiesList);
        }
Exemple #11
0
        public void EnumerateDomainShares()
        {
            var domain    = System.DirectoryServices.ActiveDirectory.Domain.GetComputerDomain().ToString();
            var computers = new List <string>();

            using (var context = new PrincipalContext(ContextType.Domain, domain))
            {
                using (var searcher = new PrincipalSearcher(new ComputerPrincipal(context)))
                {
                    foreach (var result in searcher.FindAll())
                    {
                        ComputerPrincipal cp = result as ComputerPrincipal;
                        computers.Add(cp.Name);
                    }
                }
            }

            Logger.WriteLine(String.Format("[*] Found {0} computers in the domain, enumerating shares...", computers.Count));
            ThreadPool.SetMaxThreads(10, 10);
            List <Thread> threads = new List <Thread>();

            foreach (var c in computers)
            {
                Thread t = new Thread(() => EnumNetShares(c));
                t.Start();
                threads.Add(t);
            }

            foreach (var t in threads)
            {
                t.Join();
            }
        }
Exemple #12
0
        public void Check()
        {
            try
            {
                var builder    = new StringBuilder();
                var domainName = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;
                if (string.IsNullOrWhiteSpace(domainName))
                {
                    Message = "\tNot domain joined";
                    return;
                }

                ComputerPrincipal principal = ComputerPrincipal.FindByIdentity(new PrincipalContext(ContextType.Domain, domainName), Dns.GetHostName());
                foreach (GroupPrincipal group in principal.GetGroups())
                {
                    builder.AppendLine(string.Format("\t{0}", group));
                }

                Message = builder.ToString();
            }
            catch
            {
                Message = "\tCheck failed [*]";
            }
        }
Exemple #13
0
        /// <summary>
        /// Searching for all computers in domain.
        /// </summary>
        /// <returns> List of Computers.</returns>
        public List <ComputersProperties> SearchComputer()
        {
            List <ComputersProperties> computerProList = new List <ComputersProperties>();

            try
            {
                using (var principialCtx = new PrincipalContext(ContextType.Domain, domainServer))
                    using (var computerPricipial = new ComputerPrincipal(principialCtx))
                        using (var priSearcher = new PrincipalSearcher(computerPricipial))
                        {
                            computerPricipial.Name  = "*";
                            priSearcher.QueryFilter = computerPricipial;
                            PrincipalSearchResult <Principal> computerList = priSearcher.FindAll();

                            foreach (var p in computerList)
                            {
                                ComputerPrincipal pc       = (ComputerPrincipal)p;
                                string            ipAdress = GetComputerIpAddress(p.Name);
                                var computerPro            = new ComputersProperties(pc.Name, pc.Sid.ToString(), ipAdress, pc.LastPasswordSet.ToString(), pc.LastBadPasswordAttempt.ToString());
                                computerProList.Add(computerPro);
                            }
                        }
            }
            catch (Exception e)
            {
                throw;
            }

            return(computerProList);
        }
Exemple #14
0
        /// <summary>
        /// This method receives a string containing the server name, and deletes it's computer account.
        /// </summary>
        /// <param name="serverName">a string containing the server name.</param>
        /// <returns>A ComputerAccountResult containing the action performed, a success/failure message,
        /// the name of the server which the computer account belongs to and the path of the object in AD.</returns>
        public static ComputerAccountResult DeleteComputerAccount(string serverName)
        {
            // Set up the result object.
            ComputerAccountResult result = new ComputerAccountResult()
            {
                action       = "delete",
                message      = string.Empty,
                serverName   = serverName,
                objectADPath = string.Empty
            };

            // Set up domain context.
            PrincipalContext pc = new PrincipalContext(ContextType.Domain, Domain);

            // Check if an existing computer account exists in AD.
            ComputerPrincipal computer = ComputerPrincipal.FindByIdentity(pc, serverName);

            if (computer != null)
            {
                result.objectADPath = computer.DistinguishedName;
                computer.Delete();
                result.message = "Computer Account deleted successfully.";
            }
            else
            {
                result.message = "No such Computer Account.";
            }

            return(result);
        }
Exemple #15
0
        }                   // Moves a Computer from one OU to another

        public void UpdateDescription(string building, string room, string type)
        {
            try
            {
                //Locate Machine LDAP location and create LDAP prinipal object for the computer
                PrincipalContext  Computer_Search_Context = new PrincipalContext(ContextType.Domain);
                ComputerPrincipal Local_Computer          = new ComputerPrincipal(Computer_Search_Context);
                Local_Computer.Name = System.Environment.MachineName;

                PrincipalSearcher Search_Results = new PrincipalSearcher(Local_Computer);

                var Local_Computer_Principal = Search_Results.FindOne();


                //Open a directory connection for the current machine obejct
                DirectoryEntry Computers_Current_Location = new DirectoryEntry("LDAP://" + Local_Computer_Principal.DistinguishedName, Properties.Resources.ServiceAccountUserName, Properties.Resources.ServiceAccountPassword);
                Computers_Current_Location.UsePropertyCache = false;    //insures changes to machine description are commited immdately.

                //Build new Description for the computer from supplied arguments
                string NewDecsription = building + "," + room + "," + type;

                //perform changes to machine description
                Computers_Current_Location.Properties["description"].Value = NewDecsription;
            }
            catch
            {
                throw new SystemException("Could not SET Machine Description in AD");
            }
        }   // Updates a Computer Objects Description with the building, room, and type argument information
Exemple #16
0
        private ComputerPrincipal GetComputerPrincipal(string ComputerName)
        {
            PrincipalContext  pc       = GetPrincipalContext();
            ComputerPrincipal computer = ComputerPrincipal.FindByIdentity(pc, ComputerName);

            return(computer);
        }
Exemple #17
0
        public void ComputerPrincipalConstructorTest()
        {
            ComputerPrincipal computer = new ComputerPrincipal(domainContext);

            computer.Dispose();
            Assert.Inconclusive("TODO: Implement code to verify target");
        }
Exemple #18
0
        private void BtnDelete_Click(object sender, EventArgs e)
        {
            DialogResult dialogResult = System.Windows.Forms.MessageBox.Show("Are you sure you want to permanently delete this computer from active directory?", "Warning!", MessageBoxButtons.YesNo);

            if (dialogResult == DialogResult.Yes)
            {
                DialogResult dialogResult1 = System.Windows.Forms.MessageBox.Show("Are you sure? This action cannot be undone!", "Warning!", MessageBoxButtons.YesNo);

                if (dialogResult1 == DialogResult.Yes)
                {
                    try
                    {
                        PrincipalContext  ctx      = new PrincipalContext(ContextType.Domain);
                        ComputerPrincipal computer = ComputerPrincipal.FindByIdentity(ctx, tbSearch.Text);
                        if (computer != null)
                        {
                            computer.Delete();
                        }
                        else
                        {
                            return;
                        }
                    }

                    catch (Exception)
                    {
                    }
                }
            }
        }
Exemple #19
0
        /// <summary>
        ///     Gets the computers summaries data.
        /// </summary>
        /// <returns>IEnumerable&lt;ExpandoObject&gt;.</returns>
        /// TODO Edit XML Comment Template for GetComputersSummariesData
        private IEnumerable <ExpandoObject> GetComputersSummariesData()
        {
            var data = new List <ExpandoObject>();

            foreach (var distinguishedName in DistinguishedNames)
            {
                CancellationToken.ThrowIfCancellationRequested();
                using (var principalContext = GetPrincipalContext())
                    using (var computerPrincipal = ComputerPrincipal.FindByIdentity(
                               principalContext,
                               IdentityType.DistinguishedName,
                               distinguishedName))
                    {
                        if (computerPrincipal == null)
                        {
                            continue;
                        }

                        data.Add(
                            DataPreparer.PrepareData(
                                DefaultComputerProperties,
                                computerPrincipal));
                    }
            }

            return(data);
        }
Exemple #20
0
        private void TbSearch_TextChanged(object sender, EventArgs e)
        {
            try
            {
                using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
                {
                    ComputerPrincipal computer = ComputerPrincipal.FindByIdentity(ctx, tbSearch.Text);

                    if (computer != null)
                    {
                        tbSearch.ForeColor = Color.Green;
                        btnDelete.Enabled  = true;
                    }
                    else
                    {
                        tbSearch.ForeColor = Color.Red;
                        btnDelete.Enabled  = false;
                    }
                }
            }

            catch (Exception)
            {
            }
        }
Exemple #21
0
        public static List <string> GetComputerGroups(string computerName)
        {
            List <string> Groups = new List <string>();

            using (PrincipalContext corp = new PrincipalContext(ContextType.Domain))
            {
                ComputerPrincipal comp = new ComputerPrincipal(corp);
                comp.Name = computerName;
                PrincipalSearcher search = new PrincipalSearcher();
                search.QueryFilter = comp;
                try
                {
                    StringBuilder groupList = new StringBuilder();
                    Principal     result    = search.FindOne();
                    foreach (Principal group in result.GetGroups())
                    {
                        Groups.Add(group.ToString());
                    }
                    return(Groups);
                }
                catch (Exception exception)
                {
                    MessageBox.Show(exception.Message);
                    return(null);
                }
            }
        }
Exemple #22
0
        /// <summary>
        /// Unlocks the specified principal, which can be either a user or computer.
        /// </summary>
        /// <param name="principal">A unique identifier of a user or computer.</param>
        /// <returns>True if success, false otherwise.</returns>
        public static Boolean Unlock(string principal)
        {
            Principal p = Principal.FindByIdentity(GetPrincipalContext(), principal);

            try
            {
                if (p is UserPrincipal)
                {
                    UserPrincipal u = p as UserPrincipal;
                    u.UnlockAccount();
                    u.Save();
                }
                else if (p is ComputerPrincipal)
                {
                    ComputerPrincipal c = p as ComputerPrincipal;
                    c.UnlockAccount();
                    c.Save();
                }
                return(true);
            }
            catch
            {
                return(false);
            }
        }
        public void Ctor_MachineContext_NoException()
        {
            var context   = new PrincipalContext(ContextType.Machine);
            var principal = new ComputerPrincipal(context, "samAccountName", "password", enabled: true);

            Assert.Equal(ContextType.Machine, principal.ContextType);
        }
Exemple #24
0
        /// <summary>
        /// Expires the specified user or computer's password, forcing it to be required to be reset.
        /// </summary>
        /// <param name="name">The unique identifier of the user or computer.</param>
        /// <returns>True if the password was expired successfully, false otherwise.</returns>
        public static Boolean ExpirePassword(string name)
        {
            Boolean result = false;

            try
            {
                Principal p = Principal.FindByIdentity(GetPrincipalContext(), name);

                if ((p != null) && (p is UserPrincipal))
                {
                    UserPrincipal u = p as UserPrincipal;
                    u.ExpirePasswordNow();
                    u.Save();
                    result = true;
                }
                else if ((p != null) && (p is ComputerPrincipal))
                {
                    ComputerPrincipal c = p as ComputerPrincipal;
                    c.ExpirePasswordNow();
                    c.Save();
                    result = true;
                }
            }
            catch
            {
                result = false;
            }
            return(result);
        }
 public void TestComputerContext()
 {
     using (PrincipalContext context = DomainContext)
     {
         using (ComputerPrincipal cp = new ComputerPrincipal(context))
         {
             cp.Name = "*";
             PrincipalSearcher ps = new PrincipalSearcher();
             ps.QueryFilter = cp;
             using (ComputerPrincipal r1 = ps.FindOne() as ComputerPrincipal)
                 using (ComputerPrincipal r2 = ComputerPrincipal.FindByIdentity(context, r1.Name))
                 {
                     Assert.Equal(r2.AccountExpirationDate, r1.AccountExpirationDate);
                     Assert.Equal(r2.Description, r1.Description);
                     Assert.Equal(r2.DisplayName, r1.DisplayName);
                     Assert.Equal(r2.DistinguishedName, r1.DistinguishedName);
                     Assert.Equal(r2.Guid, r1.Guid);
                     Assert.Equal(r2.HomeDirectory, r1.HomeDirectory);
                     Assert.Equal(r2.HomeDrive, r1.HomeDrive);
                     Assert.Equal(r2.SamAccountName, r1.SamAccountName);
                     Assert.Equal(r2.Sid, r1.Sid);
                     Assert.Equal(r2.UserPrincipalName, r1.UserPrincipalName);
                 }
         }
     }
 }
Exemple #26
0
        /// <summary>
        /// Public method for verifying if a given principal (user or machine) is a member of a given group.
        /// </summary>
        /// <param name="principalName">string</param>
        /// <param name="type">PrincipalType</param>
        /// <param name="groupName">string</param>
        /// <returns>bool</returns>
        public static bool IsMemberOf(string principalName, PrincipalType type, string groupName)
        {
            bool             returnValue = false;
            PrincipalContext context     = new PrincipalContext(ContextType.Domain);

            try
            {
                switch (type)
                {
                case PrincipalType.Machine:
                    using (var comp = ComputerPrincipal.FindByIdentity(context, principalName))
                    {
                        returnValue = IsMemberOf(groupName, comp);
                    }
                    break;

                case PrincipalType.User:
                    using (var user = UserPrincipal.FindByIdentity(context, principalName))
                    {
                        returnValue = IsMemberOf(groupName, user);
                    }
                    break;
                }

                return(returnValue);
            }
            catch
            {
                throw;
            }
            finally
            {
                context = null;
            }
        }
Exemple #27
0
        internal override Principal CreatePrincipal(PrincipalContext context, string name)
        {
            ComputerPrincipal computer = new ComputerPrincipal(context);

            computer.Name = name;
            return(computer);
        }
Exemple #28
0
        private void buttonMovePC_Click(object sender, EventArgs e)
        {
            try
            {
                using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domain))
                {
                    // find a computer
                    ComputerPrincipal computer = ComputerPrincipal.FindByIdentity(ctx, computername);

                    DirectoryEntry de = (DirectoryEntry)computer.GetUnderlyingObject();
                    de.MoveTo(new DirectoryEntry("LDAP://" + comboBoxOUList.Text));
                    de.CommitChanges();
                    de.Dispose();
                    computer.Dispose();
                }
                System.Windows.Forms.MessageBox.Show(computername + " has been moved to " + comboBoxOUList.Text, "Moving computer to OU", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.Close();
            }
            catch (SystemException err)
            {
                System.Windows.Forms.MessageBox.Show(err.Message.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error,
                                                     MessageBoxDefaultButton.Button1,
                                                     MessageBoxOptions.DefaultDesktopOnly);
                this.Close();
            }
        }
        /// <summary>
        /// Fetch and Return Active Directory computer List List against given Domain name
        /// </summary>
        /// <param name="stringDomainName"></param>
        /// <returns></returns>
        public static List <Computer> FindComputersList(string stringDomainName)
        {
            List <Computer> LstComputers = new List <Computer>();

            if (string.IsNullOrWhiteSpace(stringDomainName))
            {
                stringDomainName = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;
            }
            if (stringDomainName != null)
            {
                PrincipalContext PrincipalContext1 = new PrincipalContext(ContextType.Domain, stringDomainName);

                ComputerPrincipal ComputerPrincipal1 = new ComputerPrincipal(PrincipalContext1);
                PrincipalSearcher searchComputer     = new PrincipalSearcher(ComputerPrincipal1);
                foreach (ComputerPrincipal result in searchComputer.FindAll())
                {
                    Computer Computer1 = new Computer(result.SamAccountName, result.DisplayName, result.Name, result.Description, result.Enabled, result.LastLogon);
                    LstComputers.Add(Computer1);
                }
                searchComputer.Dispose();
            }
            else
            {
                //  File.WriteAllText(string.Format(System.Environment.CurrentDirectory + "\\Error.csv"), "This computer is not a member of domain");
            }
            return(LstComputers);
        }
Exemple #30
0
        /// <summary>
        /// Returns all <see cref="ComputerPrincipal"/> objects that match the filter.
        /// By default all <see cref="ComputerPrincipal"/> objects in the current user's domain are returned.
        /// </summary>
        /// <param name="filter">The filter for the results.</param>
        /// <param name="pageSize">The page size of the searched results.</param>
        /// <returns>All <see cref="ComputerPrincipal"/> objects that match the filter. By default all computers in the current user's domain are returned.</returns>
        /// <see cref="https://docs.microsoft.com/en-us/previous-versions/bb384378(v=vs.90)">Filter example</see>
        public IEnumerable <ComputerPrincipal> GetComputers(ComputerPrincipal filter = null, int pageSize = 1000)
        {
            PrincipalSearcher searcher = GetComputerSearcher(filter, pageSize);
            PrincipalSearchResult <Principal> result = searcher.FindAll();

            return(result.Cast <ComputerPrincipal>().Where(computer => computer != null));
        }