コード例 #1
0
ファイル: Form1.cs プロジェクト: vildar82/AD-Computers-Users
 private static void SearchComp(List<CompData> comps, string domainName)
 {
     using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domainName))
      {
     foreach (var comp in comps)
     {
        if (comp.CompName == null)
        {
           var sp = new ComputerPrincipal(ctx);
           sp.Description = comp.User.Name;
           var searcher = new PrincipalSearcher(sp);
           var res = searcher.FindAll();
           foreach (var p in res)
           {
              if (p is ComputerPrincipal)
              {
                 var findComp = (ComputerPrincipal)p;
                 comp.CompName = findComp.Name;
                 comp.CompPath = findComp.DistinguishedName;
              }
           }
        }
     }
      }
 }
コード例 #2
0
ファイル: AdComputer.cs プロジェクト: UAResLife/AdApiService
        /// <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;
        }
コード例 #3
0
        private void CreateNewComputer(string computerName, string computerOUPath)
        {
            try
            {
                // Set default Directory OU Path
                PrincipalContext setOU = new PrincipalContext(ContextType.Domain, null, computerOUPath);

                // Create new Computer object
                ComputerPrincipal newComputerObject = new ComputerPrincipal(setOU, computerName, "password", enabled: true);

                // Set Extra Computer Info
                newComputerObject.DisplayName = computerName;

                // Save settings
                using (newComputerObject)
                {
                    newComputerObject.Save();
                }

                // Close Connection
                newComputerObject.Dispose();

            }
            catch (Exception ex)
            {

                Console.WriteLine("Some error to create computer object" + ex.Message);
                throw;
            }
        }
コード例 #4
0
ファイル: SDSUtils.cs プロジェクト: wanglibo2016/corefx
        static internal Principal SearchResultToPrincipal(SearchResult sr, PrincipalContext owningContext, Type principalType)
        {
            Principal p;

            // Construct an appropriate Principal object.
            // Make* constructs a Principal that is marked persisted
            // and not loaded (p.unpersisted = false, p.loaded = false).

            // Since there should be no more multistore contexts, the owning context IS
            // the specific context

            // If we know the type we should just construct it ourselves so that we don't need to incur the costs of reflection.
            // If this is an extension type then we must reflect teh constructor to create the object.

            if (typeof(UserPrincipal) == principalType)
            {
                p = UserPrincipal.MakeUser(owningContext);
            }
            else if (typeof(ComputerPrincipal) == principalType)
            {
                p = ComputerPrincipal.MakeComputer(owningContext);
            }
            else if (typeof(GroupPrincipal) == principalType)
            {
                p = GroupPrincipal.MakeGroup(owningContext);
            }
            else if (null == principalType ||
                     typeof(AuthenticablePrincipal) == principalType ||
                     typeof(Principal) == principalType)
            {
                if (SDSUtils.IsOfObjectClass(sr, "computer"))
                {
                    p = ComputerPrincipal.MakeComputer(owningContext);
                }
                else if (SDSUtils.IsOfObjectClass(sr, "user"))
                {
                    p = UserPrincipal.MakeUser(owningContext);
                }
                else if (SDSUtils.IsOfObjectClass(sr, "group"))
                {
                    p = GroupPrincipal.MakeGroup(owningContext);
                }
                else
                {
                    p = AuthenticablePrincipal.MakeAuthenticablePrincipal(owningContext);
                }
            }
            else
            {
                p = Principal.MakePrincipal(owningContext, principalType);
            }

            // The DirectoryEntry we're constructing the Principal from
            // will serve as the underlying object for that Principal.
            p.UnderlyingSearchObject = sr;

            // It's up to our caller to assign an appropriate StoreKey.
            // Caller must also populate the underlyingObject field if the P is to be used R/W
            return(p);
        }
コード例 #5
0
        internal static ComputerPrincipal MakeComputer(PrincipalContext ctx)
        {
            ComputerPrincipal computerPrincipal = new ComputerPrincipal(ctx);

            computerPrincipal.unpersisted = false;
            return(computerPrincipal);
        }
コード例 #6
0
        internal static Principal SearchResultToPrincipal(SearchResult sr, PrincipalContext owningContext, Type principalType)
        {
            Principal principal;

            if (typeof(UserPrincipal) != principalType)
            {
                if (typeof(ComputerPrincipal) != principalType)
                {
                    if (typeof(GroupPrincipal) != principalType)
                    {
                        if (null == principalType || typeof(AuthenticablePrincipal) == principalType || typeof(Principal) == principalType)
                        {
                            if (!SDSUtils.IsOfObjectClass(sr, "computer"))
                            {
                                if (!SDSUtils.IsOfObjectClass(sr, "user"))
                                {
                                    if (!SDSUtils.IsOfObjectClass(sr, "group"))
                                    {
                                        principal = AuthenticablePrincipal.MakeAuthenticablePrincipal(owningContext);
                                    }
                                    else
                                    {
                                        principal = GroupPrincipal.MakeGroup(owningContext);
                                    }
                                }
                                else
                                {
                                    principal = UserPrincipal.MakeUser(owningContext);
                                }
                            }
                            else
                            {
                                principal = ComputerPrincipal.MakeComputer(owningContext);
                            }
                        }
                        else
                        {
                            principal = Principal.MakePrincipal(owningContext, principalType);
                        }
                    }
                    else
                    {
                        principal = GroupPrincipal.MakeGroup(owningContext);
                    }
                }
                else
                {
                    principal = ComputerPrincipal.MakeComputer(owningContext);
                }
            }
            else
            {
                principal = UserPrincipal.MakeUser(owningContext);
            }
            principal.UnderlyingSearchObject = sr;
            return(principal);
        }
コード例 #7
0
        internal static Principal DirectoryEntryToPrincipal(DirectoryEntry de, PrincipalContext owningContext, Type principalType)
        {
            Principal principal;

            if (typeof(UserPrincipal) != principalType)
            {
                if (typeof(ComputerPrincipal) != principalType)
                {
                    if (typeof(GroupPrincipal) != principalType)
                    {
                        if (null == principalType || typeof(AuthenticablePrincipal) == principalType || typeof(Principal) == principalType)
                        {
                            if (!SDSUtils.IsOfObjectClass(de, "computer"))
                            {
                                if (!SDSUtils.IsOfObjectClass(de, "user"))
                                {
                                    if (!SDSUtils.IsOfObjectClass(de, "group"))
                                    {
                                        principal = AuthenticablePrincipal.MakeAuthenticablePrincipal(owningContext);
                                    }
                                    else
                                    {
                                        principal = GroupPrincipal.MakeGroup(owningContext);
                                    }
                                }
                                else
                                {
                                    principal = UserPrincipal.MakeUser(owningContext);
                                }
                            }
                            else
                            {
                                principal = ComputerPrincipal.MakeComputer(owningContext);
                            }
                        }
                        else
                        {
                            principal = Principal.MakePrincipal(owningContext, principalType);
                        }
                    }
                    else
                    {
                        principal = GroupPrincipal.MakeGroup(owningContext);
                    }
                }
                else
                {
                    principal = ComputerPrincipal.MakeComputer(owningContext);
                }
            }
            else
            {
                principal = UserPrincipal.MakeUser(owningContext);
            }
            principal.UnderlyingObject = de;
            return(principal);
        }
コード例 #8
0
ファイル: SDSUtils.cs プロジェクト: wanglibo2016/corefx
        // Used to implement StoreCtx.GetAsPrincipal for AD and SAM
        static internal Principal DirectoryEntryToPrincipal(DirectoryEntry de, PrincipalContext owningContext, Type principalType)
        {
            Principal p;

            // Construct an appropriate Principal object.
            // Make* constructs a Principal that is marked persisted
            // and not loaded (p.unpersisted = false, p.loaded = false).

            // Since there should be no more multistore contexts, the owning context IS
            // the specific context

            if (typeof(UserPrincipal) == principalType)
            {
                p = UserPrincipal.MakeUser(owningContext);
            }
            else if (typeof(ComputerPrincipal) == principalType)
            {
                p = ComputerPrincipal.MakeComputer(owningContext);
            }
            else if (typeof(GroupPrincipal) == principalType)
            {
                p = GroupPrincipal.MakeGroup(owningContext);
            }
            else if (null == principalType ||
                     typeof(AuthenticablePrincipal) == principalType ||
                     typeof(Principal) == principalType)
            {
                if (SDSUtils.IsOfObjectClass(de, "computer"))
                {
                    p = ComputerPrincipal.MakeComputer(owningContext);
                }
                else if (SDSUtils.IsOfObjectClass(de, "user"))
                {
                    p = UserPrincipal.MakeUser(owningContext);
                }
                else if (SDSUtils.IsOfObjectClass(de, "group"))
                {
                    p = GroupPrincipal.MakeGroup(owningContext);
                }
                else
                {
                    p = AuthenticablePrincipal.MakeAuthenticablePrincipal(owningContext);
                }
            }
            else
            {
                p = Principal.MakePrincipal(owningContext, principalType);
            }
            // The DirectoryEntry we're constructing the Principal from
            // will serve as the underlying object for that Principal.
            p.UnderlyingObject = de;

            // It's up to our caller to assign an appropriate StoreKey.

            return(p);
        }
コード例 #9
0
        /// <summary>
        /// Seeks one computer account in Active Directory whose name exactly matches the parameter.
        /// </summary>
        /// <param name="computerName">The name of the computer account to look for.</param>        
        /// <returns>Returns a computer model of the computer found, or an empty model.</returns>
        public static Computer GetADComputerByName(string computerName)
        {
            using (var context = new PrincipalContext(ContextType.Domain, Properties.Resources.DC1UPN, Properties.Resources.DomainRootOU, Properties.Resources.DomainAccount, Properties.Resources.domain))
            {
                try
                {
                    var searchPrinciple = new ComputerPrincipal(context){Name = computerName};
                    var search = new PrincipalSearcher(searchPrinciple);
                    var searchResult = (ComputerPrincipal)search.FindOne();

                    return searchResult != null ? PrincipalToADComputer(searchResult) : null;
                }
                catch (Exception ex)
                {
                    throw new Exception("GetADComputerByName.\n" + ex.Message);
                }
            }
        }
コード例 #10
0
ファイル: ADTools.aspx.cs プロジェクト: jlam916/ServiceDesk
 protected void Page_Load(object sender, EventArgs e)
 {
     UserPanel.Visible = false;
     ComputerPanel.Visible = false;
     PrincipalContext pc = new PrincipalContext( ContextType.Domain, "ITSERVICES" );
     ComputerPrincipal computer = new ComputerPrincipal( pc );
     computer.Name = "*"; //reg expression
     PrincipalSearcher ps = new PrincipalSearcher();
     ps.QueryFilter = computer;
     ((System.DirectoryServices.DirectorySearcher)ps.GetUnderlyingSearcher()).PageSize = 500;
     PrincipalSearchResult<Principal> psr = ps.FindAll();
     AD_Computers = new string[psr.Count()];
     int i = 0;
     foreach ( ComputerPrincipal cp in psr )
     {
         AD_Computers[i++] = cp.Name;
     }
 }
コード例 #11
0
        /// <summary>
        /// Deletes all computer accounts from Active Directory that end with a hyphen, plus asset tag.
        /// </summary>
        /// <param name="asset">The asset tag of the computer to be deleted.</param>
        /// <param name="whatif">Runs only the logic without actually deleting the account.</param>
        /// <returns>Returns true if the accounts were (or would have been -- if whatif is true) deleted, otherwise false.</returns>
        public static bool DeleteComputersByAsset(string asset, bool whatif = false)
        {
            using (var context = new PrincipalContext(ContextType.Domain, Properties.Resources.DC1UPN, Properties.Resources.DomainRootOU, Properties.Resources.DomainAccount, Properties.Resources.domain))
            {
                var searchPrinciple = new ComputerPrincipal(context) {Name = $"*-{asset}" };

                try
                {
                    var search = new PrincipalSearcher(searchPrinciple);
                    var searchResult = search.FindAll().Select(ps => ps as ComputerPrincipal).ToList();

                    foreach (var curComputer in searchResult)
                    {
                        if (!whatif) curComputer.Delete();
                    }
                    return true;
                }
                catch (Exception ex)
                {
                    var newException = new Exception("Exception in Global.cs -> DeleteComputersByAsset.\n" + ex.Message);
                    throw newException;
                }
            }
        }
コード例 #12
0
 public bool Contains(ComputerPrincipal computer)
 {
     return(this.Contains(computer));
 }
コード例 #13
0
 /// <summary>
 /// Converts an AD computer object to an AD computer Model.
 /// </summary>
 /// <param name="computerPrincipal">The AD computer object to convert.</param>
 /// <returns>Returns the converted computer model, or null if it couldn't.</returns>
 private static Computer PrincipalToADComputer(ComputerPrincipal computerPrincipal)
 {
     try
     {
         return new Computer()
         {
             DistinguishedName = computerPrincipal.DistinguishedName,
             Name = computerPrincipal.Name
         };
     }
     catch
     {
         return null;
     }
 }
コード例 #14
0
ファイル: Computer.cs プロジェクト: chcosta/corefx
        //
        // Internal "constructor": Used for constructing Computer returned by a query
        //
        static internal ComputerPrincipal MakeComputer(PrincipalContext ctx)
        {
            ComputerPrincipal computer = new ComputerPrincipal(ctx);
            computer.unpersisted = false;

            return computer;
        }
コード例 #15
0
ファイル: Adws.svc.cs プロジェクト: sghaida/ADWS
        /// <summary>
        /// ADD Active Directory Computer Obbject
        /// </summary>
        /// <param name="computerInfo">ADComputerRequest</param>
        /// <returns>ResponseMessage</returns>
        public ResponseMessage AddMachine( RequestComputerCreate computerInfo )
        {
            ResponseMessage status = new ResponseMessage();

            status.IsSuccessful = false;
            status.Message = string.Empty;

            Session stat = ValidateSession( computerInfo.DomainInfo.SessionKey );

            if ( stat.IsAuthenticated == true )
            {

                string uri = FixADURI( computerInfo.DomainInfo.ADHost , computerInfo.DomainInfo.ContainerPath );

                if ( string.IsNullOrWhiteSpace( uri ) )
                {
                    status.Message = status.Message = "AD Host is not allowed to be empty, kindly provide the AD Host";
                    return status;
                }

                bool isAllowWite = CheckWriteOermission( uri , computerInfo.DomainInfo.BindingUserName , computerInfo.DomainInfo.BindingUserPassword );

                try
                {
                    ComputerPrincipal computer = FindADComputer( computerInfo.SamAccountName , computerInfo.DomainInfo );

                    if ( computer != null )
                    {

                        status.Message = @"There is a existing computer with the provided name, kindly choose another name";

                        return status;
                    }
                    else
                    {
                        var principalContext = new PrincipalContext( ContextType.Domain , computerInfo.DomainInfo.DomainName , computerInfo.DomainInfo.ContainerPath , computerInfo.DomainInfo.BindingUserName , computerInfo.DomainInfo.BindingUserPassword );

                        computer = new ComputerPrincipal( principalContext );
                        computer.DisplayName = computerInfo.DisplayName;
                        computer.Description = computerInfo.Description;
                        computer.SamAccountName = computerInfo.SamAccountName;
                        computer.Enabled = true;
                        computer.SetPassword( GenerateADPassword( uri , computerInfo.DomainInfo.BindingUserName , computerInfo.DomainInfo.BindingUserPassword ) );
                        computer.Save();

                        status.Message = @"Computer has been added successfully ";
                        status.IsSuccessful = true;
                        return status;
                    }
                }
                catch ( Exception ex )
                {
                    status.Message = status.Message = "error has accured while adding the desgnated group" + ex;
                    return status;
                }
            }
            else
            {
                status.Message = "Kindly authenticate first";
                return status;
            }
        }
コード例 #16
0
 public bool Remove(ComputerPrincipal computer)
 {
     return(this.Remove(computer));
 }
コード例 #17
0
        private void btn_createPC_Click(object sender, RoutedEventArgs e)
        {
            if (currentPC == null || currentBranch == null)
            {
                MessageBox.Show("Before createing new PC, you must select Current Branch and generate free PC name!", "Error", MessageBoxButton.OK, MessageBoxImage.Stop);
                return;
            }
            MessageBoxResult mbr = MessageBox.Show(String.Format("Create new PC with name {0} in OU {1}", currentPC, currentBranch), "Agree or disagree?", MessageBoxButton.YesNo,
                MessageBoxImage.Question);
            if (mbr == MessageBoxResult.No) return;
            if (mbr == MessageBoxResult.Yes)
            {
                try
                {
                    pcx = new PrincipalContext(ContextType.Domain, "bin.bank", String.Format("OU={0},OU=BIN BRANCHES,DC=BIN,DC=BANK", currentBranch), username, password);
                    ComputerPrincipal comp = new ComputerPrincipal(pcx, currentPC, "", true);

                    if (ckbx_description.IsChecked == true)
                    {
                        string diskrip = Interaction.InputBox("Input a description if needed.", "Description for " + currentPC, "Иванов И. В.");
                        comp.Description = (diskrip == "") ? null : diskrip;
                    }
                    comp.Save();
                    MessageBox.Show("Successfully!", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                catch (Exception ex) { MessageBox.Show(ex.Message); }
                finally { pcx.Dispose(); }
            }
        }
コード例 #18
0
 public void Add(ComputerPrincipal computer)
 {
     this.Add(computer);
 }
コード例 #19
0
 public void ComputerPrincipalConstructorTest()
 {
     ComputerPrincipal computer = new ComputerPrincipal(domainContext);
     computer.Dispose();
     Assert.Inconclusive("TODO: Implement code to verify target");
 }
コード例 #20
0
 internal override Principal CreatePrincipal(PrincipalContext context, string name)
 {
     ComputerPrincipal computer = new ComputerPrincipal(context);
     computer.Name = name;
     return computer;
 }
コード例 #21
0
ファイル: PrincipalCollection.cs プロジェクト: xuanmu/corefx
 public bool Contains(ComputerPrincipal computer)
 {
     return(Contains((Principal)computer));
 }
コード例 #22
0
ファイル: AdToolkit.cs プロジェクト: UAResLife/AdApiService
 /// <summary>
 /// Creates a computer with the specified name and description in the specified location.
 /// </summary>
 /// <param name="name">The name of the new computer.</param>
 /// <param name="location">The distinguished name of the OU in which the computer should be created.</param>
 /// <param name="description">The description of the new computer.</param>
 /// <returns>A ComputerPrincipal object representing the new computer.</returns>
 public static ComputerPrincipal CreateComputer(string name, string location, string description)
 {
     ComputerPrincipal newComputer = new ComputerPrincipal(GetPrincipalContext(location), name, GetRandomPassword(), true);
     newComputer.Description = description;
     newComputer.DisplayName = name;
     newComputer.Name = name;
     newComputer.Save();
     return newComputer;
 }
コード例 #23
0
ファイル: PrincipalCollection.cs プロジェクト: xuanmu/corefx
 public void Add(ComputerPrincipal computer)
 {
     Add((Principal)computer);
 }
コード例 #24
0
ファイル: PrincipalCollection.cs プロジェクト: xuanmu/corefx
 public bool Remove(ComputerPrincipal computer)
 {
     return(Remove((Principal)computer));
 }
コード例 #25
-1
ファイル: ADTools.aspx.cs プロジェクト: jlam916/ServiceDesk
    protected void fillBtn_Click(object sender, EventArgs e)
    {
        if ( isNull() )
            return;

        using ( PrincipalContext context = new PrincipalContext( ContextType.Domain, "ITSERVICES" ) )
        {
            ComputerPrincipal computer = new ComputerPrincipal( context );
            computer.Name = ComputerTextBox.Text;
            using ( PrincipalSearcher searcher = new PrincipalSearcher( computer ) )
            {
                Principal result = searcher.FindOne();

                AuthenticablePrincipal auth = result as AuthenticablePrincipal;
                if ( auth != null )
                {
                    lblName.Text = auth.Name;
                    lblLastLogon.Text = auth.LastLogon.ToString();
                    lblEnabled.Text = auth.Enabled.ToString();
                    lblDistinguishedName.Text = auth.DistinguishedName;
                }
            }
        }
        ComputerPanel.Visible = true;
    }