public void SetSecurityLevel(ReplicationSecurityLevel securityLevel)
        {
            CheckIfDisposed();
            if (securityLevel < ReplicationSecurityLevel.NegotiatePassThrough || securityLevel > ReplicationSecurityLevel.MutualAuthentication)
            {
                throw new InvalidEnumArgumentException(nameof(securityLevel), (int)securityLevel, typeof(ReplicationSecurityLevel));
            }

            try
            {
                DirectoryEntry configEntry = _directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.ConfigurationNamingContext);
                configEntry.Properties[PropertyManager.MsDSReplAuthenticationMode].Value = (int)securityLevel;
                configEntry.CommitChanges();
            }
            catch (COMException e)
            {
                throw ExceptionHelper.GetExceptionFromCOMException(_context, e);
            }

            // invalidate the cached entry
            _cachedSecurityLevel = (ReplicationSecurityLevel)(-1);
        }
Exemple #2
0
        private ArrayList GetSites()
        {
            ArrayList      sites      = new ArrayList();
            DirectoryEntry sitesEntry = _directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.SitesContainer);

            // search for all the "site" objects
            // (one-level search is good enough)
            // setup the directory searcher object
            string filter = "(" + PropertyManager.ObjectCategory + "=site)";

            string[] propertiesToLoad = new string[1];

            propertiesToLoad[0] = PropertyManager.Cn;

            ADSearcher             searcher = new ADSearcher(sitesEntry, filter, propertiesToLoad, SearchScope.OneLevel);
            SearchResultCollection?resCol   = null;

            try
            {
                resCol = searcher.FindAll();

                foreach (SearchResult res in resCol)
                {
                    // an existing site
                    sites.Add(new ActiveDirectorySite(_context, (string)PropertyManager.GetSearchResultPropertyValue(res, PropertyManager.Cn) !, true));
                }
            }
            catch (COMException e)
            {
                throw ExceptionHelper.GetExceptionFromCOMException(_context, e);
            }
            finally
            {
                // call dispose on search result collection
                resCol?.Dispose();
            }
            return(sites);
        }
 public void Save()
 {
     if (this.disposed)
     {
         throw new ObjectDisposedException(base.GetType().Name);
     }
     try
     {
         if (this.existing)
         {
             if (this.site == null)
             {
                 if (this.cachedEntry.Properties.Contains("siteObject"))
                 {
                     this.cachedEntry.Properties["siteObject"].Clear();
                 }
             }
             else
             {
                 this.cachedEntry.Properties["siteObject"].Value = this.site.cachedEntry.Properties["distinguishedName"][0];
             }
             this.cachedEntry.CommitChanges();
         }
         else
         {
             if (this.Site != null)
             {
                 this.cachedEntry.Properties["siteObject"].Add(this.site.cachedEntry.Properties["distinguishedName"][0]);
             }
             this.cachedEntry.CommitChanges();
             this.existing = true;
         }
     }
     catch (COMException exception)
     {
         throw ExceptionHelper.GetExceptionFromCOMException(this.context, exception);
     }
 }
 private void InitializeCrossRef(string distinguishedName)
 {
     if (this.crossRefEntry == null)
     {
         DirectoryEntry directoryEntry = null;
         try
         {
             directoryEntry = DirectoryEntryManager.GetDirectoryEntry(Utils.GetNewDirectoryContext(this.GetNamingRoleOwner(), DirectoryContextType.DirectoryServer, base.context), WellKnownDN.PartitionsContainer);
             string name = "CN={" + Guid.NewGuid() + "}";
             this.crossRefEntry = directoryEntry.Children.Add(name, "crossRef");
             string adamHostNameAndPortsFromNTDSA = null;
             if (this.appType == ApplicationPartitionType.ADAMApplicationPartition)
             {
                 DirectoryEntry cachedDirectoryEntry = base.directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.RootDSE);
                 string         dn = (string)PropertyManager.GetPropertyValue(base.context, cachedDirectoryEntry, PropertyManager.DsServiceName);
                 adamHostNameAndPortsFromNTDSA = Utils.GetAdamHostNameAndPortsFromNTDSA(base.context, dn);
             }
             else
             {
                 adamHostNameAndPortsFromNTDSA = base.context.Name;
             }
             this.crossRefEntry.Properties[PropertyManager.DnsRoot].Value = adamHostNameAndPortsFromNTDSA;
             this.crossRefEntry.Properties[PropertyManager.Enabled].Value = false;
             this.crossRefEntry.Properties[PropertyManager.NCName].Value  = distinguishedName;
         }
         catch (COMException exception)
         {
             throw ExceptionHelper.GetExceptionFromCOMException(base.context, exception);
         }
         finally
         {
             if (directoryEntry != null)
             {
                 directoryEntry.Dispose();
             }
         }
     }
 }
        private System.DirectoryServices.ActiveDirectory.ForestMode GetForestMode()
        {
            System.DirectoryServices.ActiveDirectory.ForestMode mode;
            DirectoryEntry directoryEntry = DirectoryEntryManager.GetDirectoryEntry(this.context, WellKnownDN.RootDSE);

            try
            {
                if (!directoryEntry.Properties.Contains(PropertyManager.ForestFunctionality))
                {
                    return(System.DirectoryServices.ActiveDirectory.ForestMode.Windows2000Forest);
                }
                return((System.DirectoryServices.ActiveDirectory.ForestMode) int.Parse((string)directoryEntry.Properties[PropertyManager.ForestFunctionality].Value, NumberFormatInfo.InvariantInfo));
            }
            catch (COMException exception)
            {
                throw ExceptionHelper.GetExceptionFromCOMException(this.context, exception);
            }
            finally
            {
                directoryEntry.Dispose();
            }
            return(mode);
        }
        public DomainController DisableGlobalCatalog()
        {
            base.CheckIfDisposed();
            this.CheckIfDisabled();
            DirectoryEntry cachedDirectoryEntry = base.directoryEntryMgr.GetCachedDirectoryEntry(base.NtdsaObjectName);
            int            num = 0;

            try
            {
                if (cachedDirectoryEntry.Properties[PropertyManager.Options].Value != null)
                {
                    num = (int)cachedDirectoryEntry.Properties[PropertyManager.Options].Value;
                }
                cachedDirectoryEntry.Properties[PropertyManager.Options].Value = num & -2;
                cachedDirectoryEntry.CommitChanges();
            }
            catch (COMException exception)
            {
                throw ExceptionHelper.GetExceptionFromCOMException(base.context, exception);
            }
            this.disabled = true;
            return(new DomainController(base.context, base.Name));
        }
Exemple #7
0
        public static object GetSearchResultPropertyValue(SearchResult res, string propertyName)
        {
            Debug.Assert(res != null, "PropertyManager::GetSearchResultPropertyValue - res is null");

            Debug.Assert(propertyName != null, "PropertyManager::GetSearchResultPropertyValue - propertyName is null");

            ResultPropertyValueCollection propertyValues = null;

            try
            {
                propertyValues = res.Properties[propertyName];
                if ((propertyValues == null) || (propertyValues.Count < 1))
                {
                    throw new ActiveDirectoryOperationException(SR.Format(SR.PropertyNotFound, propertyName));
                }
            }
            catch (COMException e)
            {
                throw ExceptionHelper.GetExceptionFromCOMException(e);
            }

            return(propertyValues[0]);
        }
        public void Delete()
        {
            base.CheckIfDisposed();
            if (!this.committed)
            {
                throw new InvalidOperationException(Res.GetString("CannotPerformOperationOnUncommittedObject"));
            }
            DirectoryEntry directoryEntry = DirectoryEntryManager.GetDirectoryEntry(base.context, base.directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.PartitionsContainer));

            try
            {
                this.GetCrossRefEntry();
                directoryEntry.Children.Remove(this.crossRefEntry);
            }
            catch (COMException exception)
            {
                throw ExceptionHelper.GetExceptionFromCOMException(base.context, exception);
            }
            finally
            {
                directoryEntry.Dispose();
            }
        }
        protected override void OnRemoveComplete(int index, object value)
        {
            ActiveDirectorySubnet subnet = (ActiveDirectorySubnet)value;
            string key = (string)PropertyManager.GetPropertyValue(subnet.context, subnet.cachedEntry, PropertyManager.DistinguishedName);

            try
            {
                if (this.changeList.Contains(key))
                {
                    ((DirectoryEntry)this.changeList[key]).Properties["siteObject"].Clear();
                }
                else
                {
                    DirectoryEntry directoryEntry = DirectoryEntryManager.GetDirectoryEntry(this.context, this.MakePath(key));
                    directoryEntry.Properties["siteObject"].Clear();
                    this.changeList.Add(key, directoryEntry);
                }
            }
            catch (COMException exception)
            {
                throw ExceptionHelper.GetExceptionFromCOMException(this.context, exception);
            }
        }
Exemple #10
0
        public void Delete()
        {
            if (_disposed)
            {
                throw new ObjectDisposedException(GetType().Name);
            }

            if (!existing)
            {
                throw new InvalidOperationException(Res.GetString(Res.CannotDelete));
            }
            else
            {
                try
                {
                    cachedEntry.Parent.Children.Remove(cachedEntry);
                }
                catch (COMException e)
                {
                    throw ExceptionHelper.GetExceptionFromCOMException(context, e);
                }
            }
        }
        protected override void OnRemoveComplete(int index, object value)
        {
            ActiveDirectorySubnet subnet = (ActiveDirectorySubnet)value;
            string dn = (string)PropertyManager.GetPropertyValue(subnet.context, subnet.cachedEntry, PropertyManager.DistinguishedName);

            try
            {
                if (changeList.Contains(dn))
                {
                    ((DirectoryEntry)changeList[dn]).Properties["siteObject"].Clear();
                }
                else
                {
                    DirectoryEntry de = DirectoryEntryManager.GetDirectoryEntry(_context, MakePath(dn));
                    de.Properties["siteObject"].Clear();
                    changeList.Add(dn, de);
                }
            }
            catch (COMException e)
            {
                throw ExceptionHelper.GetExceptionFromCOMException(_context, e);
            }
        }
Exemple #12
0
 protected override void OnRemoveComplete(int index, object value)
 {
     if (this.isBound)
     {
         if (this.classEntry == null)
         {
             this.classEntry = this.schemaClass.GetSchemaClassDirectoryEntry();
         }
         string name = ((ActiveDirectorySchemaProperty)value).Name;
         try
         {
             if (!this.classEntry.Properties[this.propertyName].Contains(name))
             {
                 throw new ActiveDirectoryOperationException(Res.GetString("ValueCannotBeModified"));
             }
             this.classEntry.Properties[this.propertyName].Remove(name);
         }
         catch (COMException exception)
         {
             throw ExceptionHelper.GetExceptionFromCOMException(this.context, exception);
         }
     }
 }
 public void Save()
 {
     if (this.disposed)
     {
         throw new ObjectDisposedException(base.GetType().Name);
     }
     try
     {
         this.cachedEntry.CommitChanges();
     }
     catch (COMException exception)
     {
         throw ExceptionHelper.GetExceptionFromCOMException(this.context, exception);
     }
     if (this.existing)
     {
         this.siteRetrieved = false;
     }
     else
     {
         this.existing = true;
     }
 }
        private AdamInstance GetRoleOwner(AdamRole role)
        {
            DirectoryEntry cachedDirectoryEntry     = null;
            string         adamDnsHostNameFromNTDSA = null;

            using (cachedDirectoryEntry)
            {
                try
                {
                    AdamRole adamRole = role;
                    switch (adamRole)
                    {
                    case AdamRole.SchemaRole:
                    {
                        cachedDirectoryEntry = this.directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.SchemaNamingContext);
                        break;
                    }

                    case AdamRole.NamingRole:
                    {
                        cachedDirectoryEntry = this.directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.PartitionsContainer);
                        break;
                    }
                    }
                    cachedDirectoryEntry.RefreshCache();
                    adamDnsHostNameFromNTDSA = Utils.GetAdamDnsHostNameFromNTDSA(this.context, (string)PropertyManager.GetPropertyValue(this.context, cachedDirectoryEntry, PropertyManager.FsmoRoleOwner));
                }
                catch (COMException cOMException1)
                {
                    COMException cOMException = cOMException1;
                    throw ExceptionHelper.GetExceptionFromCOMException(this.context, cOMException);
                }
            }
            DirectoryContext newDirectoryContext = Utils.GetNewDirectoryContext(adamDnsHostNameFromNTDSA, DirectoryContextType.DirectoryServer, this.context);

            return(new AdamInstance(newDirectoryContext, adamDnsHostNameFromNTDSA));
        }
Exemple #15
0
        public void SeizeRoleOwnership(AdamRole role)
        {
            string str = null;

            base.CheckIfDisposed();
            AdamRole adamRole = role;

            if (adamRole == AdamRole.SchemaRole)
            {
                str = this.directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.SchemaNamingContext);
            }
            else if (adamRole == AdamRole.NamingRole)
            {
                str = this.directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.PartitionsContainer);
            }
            else
            {
                throw new InvalidEnumArgumentException("role", (int)role, typeof(AdamRole));
            }
            DirectoryEntry directoryEntry = null;

            using (directoryEntry)
            {
                try
                {
                    directoryEntry = DirectoryEntryManager.GetDirectoryEntry(this.context, str);
                    directoryEntry.Properties[PropertyManager.FsmoRoleOwner].Value = this.NtdsaObjectName;
                    directoryEntry.CommitChanges();
                }
                catch (COMException cOMException1)
                {
                    COMException cOMException = cOMException1;
                    throw ExceptionHelper.GetExceptionFromCOMException(this.context, cOMException);
                }
            }
            this.cachedRoles = null;
        }
Exemple #16
0
 public void TransferRoleOwnership(AdamRole role)
 {
     base.CheckIfDisposed();
     if (role < AdamRole.SchemaRole || role > AdamRole.NamingRole)
     {
         throw new InvalidEnumArgumentException("role", (int)role, typeof(AdamRole));
     }
     else
     {
         try
         {
             DirectoryEntry cachedDirectoryEntry = this.directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.RootDSE);
             cachedDirectoryEntry.Properties[this.becomeRoleOwnerAttrs[(int)role]].Value = 1;
             cachedDirectoryEntry.CommitChanges();
         }
         catch (COMException cOMException1)
         {
             COMException cOMException = cOMException1;
             throw ExceptionHelper.GetExceptionFromCOMException(this.context, cOMException);
         }
         this.cachedRoles = null;
         return;
     }
 }
 public void Save()
 {
     if (!this.disposed)
     {
         try
         {
             this.cachedDirectoryEntry.CommitChanges();
         }
         catch (COMException cOMException1)
         {
             COMException cOMException = cOMException1;
             throw ExceptionHelper.GetExceptionFromCOMException(this.context, cOMException);
         }
         if (!this.existingConnection)
         {
             this.existingConnection = true;
         }
         return;
     }
     else
     {
         throw new ObjectDisposedException(this.GetType().Name);
     }
 }
 public void SetSecurityLevel(ReplicationSecurityLevel securityLevel)
 {
     this.CheckIfDisposed();
     if (securityLevel < ReplicationSecurityLevel.NegotiatePassThrough || securityLevel > ReplicationSecurityLevel.MutualAuthentication)
     {
         throw new InvalidEnumArgumentException("securityLevel", (int)securityLevel, typeof(ReplicationSecurityLevel));
     }
     else
     {
         try
         {
             DirectoryEntry cachedDirectoryEntry = this.directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.ConfigurationNamingContext);
             cachedDirectoryEntry.Properties[PropertyManager.MsDSReplAuthenticationMode].Value = (int)securityLevel;
             cachedDirectoryEntry.CommitChanges();
         }
         catch (COMException cOMException1)
         {
             COMException cOMException = cOMException1;
             throw ExceptionHelper.GetExceptionFromCOMException(this.context, cOMException);
         }
         this.cachedSecurityLevel = ReplicationSecurityLevel.MutualAuthentication | ReplicationSecurityLevel.Negotiate;
         return;
     }
 }
        public void TransferRoleOwnership(AdamRole role)
        {
            CheckIfDisposed();

            if (role < AdamRole.SchemaRole || role > AdamRole.NamingRole)
            {
                throw new InvalidEnumArgumentException(nameof(role), (int)role, typeof(AdamRole));
            }

            // set the appropriate attribute on the root dse
            try
            {
                DirectoryEntry rootDSE = directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.RootDSE);
                rootDSE.Properties[_becomeRoleOwnerAttrs[(int)role]].Value = 1;
                rootDSE.CommitChanges();
            }
            catch (COMException e)
            {
                throw ExceptionHelper.GetExceptionFromCOMException(context, e);
            }

            // invalidate the role collection so that it gets loaded again next time
            _cachedRoles = null;
        }
        protected override void OnRemoveComplete(int index, object value)
        {
            ActiveDirectorySubnet activeDirectorySubnet = (ActiveDirectorySubnet)value;
            string propertyValue = (string)PropertyManager.GetPropertyValue(activeDirectorySubnet.context, activeDirectorySubnet.cachedEntry, PropertyManager.DistinguishedName);

            try
            {
                if (!this.changeList.Contains(propertyValue))
                {
                    DirectoryEntry directoryEntry = DirectoryEntryManager.GetDirectoryEntry(this.context, this.MakePath(propertyValue));
                    directoryEntry.Properties["siteObject"].Clear();
                    this.changeList.Add(propertyValue, directoryEntry);
                }
                else
                {
                    ((DirectoryEntry)this.changeList[propertyValue]).Properties["siteObject"].Clear();
                }
            }
            catch (COMException cOMException1)
            {
                COMException cOMException = cOMException1;
                throw ExceptionHelper.GetExceptionFromCOMException(this.context, cOMException);
            }
        }
Exemple #21
0
        public ReadOnlyActiveDirectorySchemaPropertyCollection FindAllProperties()
        {
            CheckIfDisposed();
            CheckIfDisabled();

            // create an ActiveDirectorySchema object
            if (_schema == null)
            {
                string?schemaNC = null;
                try
                {
                    schemaNC = directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.SchemaNamingContext);
                }
                catch (COMException e)
                {
                    throw ExceptionHelper.GetExceptionFromCOMException(context, e);
                }
                _       = Utils.GetNewDirectoryContext(Name, DirectoryContextType.DirectoryServer, context);
                _schema = new ActiveDirectorySchema(context, schemaNC);
            }

            // return the global catalog replicated properties
            return(_schema.FindAllProperties(PropertyTypes.InGlobalCatalog));
        }
Exemple #22
0
        public static ActiveDirectorySchema GetSchema(DirectoryContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            // contexttype should be Forest, DirectoryServer or ConfigurationSet
            if ((context.ContextType != DirectoryContextType.Forest) &&
                (context.ContextType != DirectoryContextType.ConfigurationSet) &&
                (context.ContextType != DirectoryContextType.DirectoryServer))
            {
                throw new ArgumentException(SR.NotADOrADAM, nameof(context));
            }

            if ((context.Name == null) && (!context.isRootDomain()))
            {
                throw new ActiveDirectoryObjectNotFoundException(SR.ContextNotAssociatedWithDomain, typeof(ActiveDirectorySchema), null);
            }

            if (context.Name != null)
            {
                // the target should be a valid forest name or a server
                if (!((context.isRootDomain()) || (context.isADAMConfigSet()) || (context.isServer())))
                {
                    if (context.ContextType == DirectoryContextType.Forest)
                    {
                        throw new ActiveDirectoryObjectNotFoundException(SR.ForestNotFound, typeof(ActiveDirectorySchema), context.Name);
                    }
                    else if (context.ContextType == DirectoryContextType.ConfigurationSet)
                    {
                        throw new ActiveDirectoryObjectNotFoundException(SR.ConfigSetNotFound, typeof(ActiveDirectorySchema), context.Name);
                    }
                    else
                    {
                        throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.ServerNotFound, context.Name), typeof(ActiveDirectorySchema), null);
                    }
                }
            }

            //  work with copy of the context
            context = new DirectoryContext(context);

            DirectoryEntryManager directoryEntryMgr = new DirectoryEntryManager(context);
            string schemaNC = null;

            try
            {
                DirectoryEntry rootDSE = directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.RootDSE);

                if ((context.isServer()) && (!Utils.CheckCapability(rootDSE, Capability.ActiveDirectoryOrADAM)))
                {
                    throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.ServerNotFound, context.Name), typeof(ActiveDirectorySchema), null);
                }

                schemaNC = (string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.SchemaNamingContext);
            }
            catch (COMException e)
            {
                int errorCode = e.ErrorCode;

                if (errorCode == unchecked ((int)0x8007203a))
                {
                    if (context.ContextType == DirectoryContextType.Forest)
                    {
                        throw new ActiveDirectoryObjectNotFoundException(SR.ForestNotFound, typeof(ActiveDirectorySchema), context.Name);
                    }
                    else if (context.ContextType == DirectoryContextType.ConfigurationSet)
                    {
                        throw new ActiveDirectoryObjectNotFoundException(SR.ConfigSetNotFound, typeof(ActiveDirectorySchema), context.Name);
                    }
                    else
                    {
                        throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.ServerNotFound, context.Name), typeof(ActiveDirectorySchema), null);
                    }
                }
                else
                {
                    throw ExceptionHelper.GetExceptionFromCOMException(context, e);
                }
            }
            catch (ActiveDirectoryObjectNotFoundException)
            {
                if (context.ContextType == DirectoryContextType.ConfigurationSet)
                {
                    // this is the case where the context is a config set and we could not find an ADAM instance in that config set
                    throw new ActiveDirectoryObjectNotFoundException(SR.ConfigSetNotFound, typeof(ActiveDirectorySchema), context.Name);
                }
                else
                {
                    throw;
                }
            }

            return(new ActiveDirectorySchema(context, schemaNC, directoryEntryMgr));
        }
Exemple #23
0
        public ActiveDirectorySiteLink(DirectoryContext context, string siteLinkName, ActiveDirectoryTransportType transport, ActiveDirectorySchedule schedule)
        {
            ValidateArgument(context, siteLinkName, transport);

            //  work with copy of the context
            context = new DirectoryContext(context);

            this.context = context;
            _name        = siteLinkName;
            _transport   = transport;

            // bind to the rootdse to get the configurationnamingcontext
            DirectoryEntry de;

            try
            {
                de = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE);
                string config = (string)PropertyManager.GetPropertyValue(context, de, PropertyManager.ConfigurationNamingContext);

                string parentDN = null;
                if (transport == ActiveDirectoryTransportType.Rpc)
                {
                    parentDN = "CN=IP,CN=Inter-Site Transports,CN=Sites," + config;
                }
                else
                {
                    parentDN = "CN=SMTP,CN=Inter-Site Transports,CN=Sites," + config;
                }

                de = DirectoryEntryManager.GetDirectoryEntry(context, parentDN);
            }
            catch (COMException e)
            {
                throw ExceptionHelper.GetExceptionFromCOMException(context, e);
            }
            catch (ActiveDirectoryObjectNotFoundException)
            {
                // this is the case where the context is a config set and we could not find an ADAM instance in that config set
                throw new ActiveDirectoryOperationException(String.Format(CultureInfo.CurrentCulture, SR.ADAMInstanceNotFoundInConfigSet, context.Name));
            }

            try
            {
                string rdn = "cn=" + _name;
                rdn         = Utils.GetEscapedPath(rdn);
                cachedEntry = de.Children.Add(rdn, "siteLink");
                cachedEntry.Properties["cost"].Value         = appDefaultCost;
                cachedEntry.Properties["replInterval"].Value = appDefaultInterval;
                if (schedule != null)
                {
                    cachedEntry.Properties["schedule"].Value = schedule.GetUnmanagedSchedule();
                }
            }
            catch (COMException e)
            {
                if (e.ErrorCode == unchecked ((int)0x80072030))
                {
                    // if it is ADAM and transport type is SMTP, throw NotSupportedException.
                    DirectoryEntry tmpDE = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE);
                    if (Utils.CheckCapability(tmpDE, Capability.ActiveDirectoryApplicationMode) && transport == ActiveDirectoryTransportType.Smtp)
                    {
                        throw new NotSupportedException(SR.NotSupportTransportSMTP);
                    }
                }

                throw ExceptionHelper.GetExceptionFromCOMException(context, e);
            }
            finally
            {
                de.Dispose();
            }
        }
Exemple #24
0
        public static ActiveDirectorySubnet FindByName(DirectoryContext context, string subnetName)
        {
            ValidateArgument(context, subnetName);

            //  work with copy of the context
            context = new DirectoryContext(context);

            // bind to the rootdse to get the configurationnamingcontext
            DirectoryEntry de;

            try
            {
                de = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE);
                string config   = (string)PropertyManager.GetPropertyValue(context, de, PropertyManager.ConfigurationNamingContext);
                string subnetdn = "CN=Subnets,CN=Sites," + config;
                de = DirectoryEntryManager.GetDirectoryEntry(context, subnetdn);
            }
            catch (COMException e)
            {
                throw ExceptionHelper.GetExceptionFromCOMException(context, e);
            }
            catch (ActiveDirectoryObjectNotFoundException)
            {
                // this is the case where the context is a config set and we could not find an ADAM instance in that config set
                throw new ActiveDirectoryOperationException(Res.GetString(Res.ADAMInstanceNotFoundInConfigSet, context.Name));
            }

            try
            {
                ADSearcher adSearcher = new ADSearcher(de,
                                                       "(&(objectClass=subnet)(objectCategory=subnet)(name=" + Utils.GetEscapedFilterValue(subnetName) + "))",
                                                       new string[] { "distinguishedName" },
                                                       SearchScope.OneLevel,
                                                       false, /* don't need paged search */
                                                       false /* don't need to cache result */);
                SearchResult srchResult = adSearcher.FindOne();
                if (srchResult == null)
                {
                    // no such subnet object
                    Exception e = new ActiveDirectoryObjectNotFoundException(Res.GetString(Res.DSNotFound), typeof(ActiveDirectorySubnet), subnetName);
                    throw e;
                }
                else
                {
                    string         siteName        = null;
                    DirectoryEntry connectionEntry = srchResult.GetDirectoryEntry();
                    // try to get the site that this subnet lives in
                    if (connectionEntry.Properties.Contains("siteObject"))
                    {
                        NativeComInterfaces.IAdsPathname pathCracker = (NativeComInterfaces.IAdsPathname) new NativeComInterfaces.Pathname();
                        // need to turn off the escaping for name
                        pathCracker.EscapedMode = NativeComInterfaces.ADS_ESCAPEDMODE_OFF_EX;

                        string tmp = (string)connectionEntry.Properties["siteObject"][0];
                        // escaping manipulation
                        pathCracker.Set(tmp, NativeComInterfaces.ADS_SETTYPE_DN);
                        string rdn = pathCracker.Retrieve(NativeComInterfaces.ADS_FORMAT_LEAF);
                        Debug.Assert(rdn != null && Utils.Compare(rdn, 0, 3, "CN=", 0, 3) == 0);
                        siteName = rdn.Substring(3);
                    }

                    // it is an existing subnet object
                    ActiveDirectorySubnet subnet = null;
                    if (siteName == null)
                    {
                        subnet = new ActiveDirectorySubnet(context, subnetName, null, true);
                    }
                    else
                    {
                        subnet = new ActiveDirectorySubnet(context, subnetName, siteName, true);
                    }

                    subnet.cachedEntry = connectionEntry;
                    return(subnet);
                }
            }
            catch (COMException e)
            {
                if (e.ErrorCode == unchecked ((int)0x80072030))
                {
                    // object is not found since we cannot even find the container in which to search
                    throw new ActiveDirectoryObjectNotFoundException(Res.GetString(Res.DSNotFound), typeof(ActiveDirectorySubnet), subnetName);
                }
                else
                {
                    throw ExceptionHelper.GetExceptionFromCOMException(context, e);
                }
            }
            finally
            {
                if (de != null)
                {
                    de.Dispose();
                }
            }
        }
Exemple #25
0
        public static GlobalCatalog GetGlobalCatalog(DirectoryContext context)
        {
            string?gcDnsName       = null;
            bool   isGlobalCatalog = false;
            DirectoryEntryManager?directoryEntryMgr = null;

            // check that the context argument is not null
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            // target should be GC
            if (context.ContextType != DirectoryContextType.DirectoryServer)
            {
                throw new ArgumentException(SR.TargetShouldBeGC, nameof(context));
            }

            // target should be a server
            if (!(context.isServer()))
            {
                throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.GCNotFound, context.Name), typeof(GlobalCatalog), context.Name);
            }

            //  work with copy of the context
            context = new DirectoryContext(context);

            try
            {
                // Get dns name of the dc
                // by binding to root dse and getting the "dnsHostName" attribute
                // (also check that the "isGlobalCatalogReady" attribute is true)
                directoryEntryMgr = new DirectoryEntryManager(context);
                DirectoryEntry rootDSE = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE);
                if (!Utils.CheckCapability(rootDSE, Capability.ActiveDirectory))
                {
                    throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.GCNotFound, context.Name), typeof(GlobalCatalog), context.Name);
                }

                gcDnsName       = (string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.DnsHostName) !;
                isGlobalCatalog = (bool)bool.Parse((string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.IsGlobalCatalogReady) !);
                if (!isGlobalCatalog)
                {
                    throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.GCNotFound, context.Name), typeof(GlobalCatalog), context.Name);
                }
            }
            catch (COMException e)
            {
                int errorCode = e.ErrorCode;

                if (errorCode == unchecked ((int)0x8007203a))
                {
                    throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.GCNotFound, context.Name), typeof(GlobalCatalog), context.Name);
                }
                else
                {
                    throw ExceptionHelper.GetExceptionFromCOMException(context, e);
                }
            }

            return(new GlobalCatalog(context, gcDnsName, directoryEntryMgr));
        }
Exemple #26
0
        internal static new GlobalCatalog FindOneWithCredentialValidation(DirectoryContext context, string?siteName, LocatorOptions flag)
        {
            GlobalCatalog gc;
            bool          retry          = false;
            bool          credsValidated = false;

            //  work with copy of the context
            context = new DirectoryContext(context);

            // authenticate against this GC to validate the credentials
            gc = FindOneInternal(context, context.Name, siteName, flag);
            try
            {
                ValidateCredential(gc, context);
                credsValidated = true;
            }
            catch (COMException e)
            {
                if (e.ErrorCode == unchecked ((int)0x8007203a))
                {
                    // server is down , so try again with force rediscovery if the flags did not already contain force rediscovery
                    if ((flag & LocatorOptions.ForceRediscovery) == 0)
                    {
                        retry = true;
                    }
                    else
                    {
                        throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.GCNotFoundInForest, context.Name), typeof(GlobalCatalog), null);
                    }
                }
                else
                {
                    throw ExceptionHelper.GetExceptionFromCOMException(context, e);
                }
            }
            finally
            {
                if (!credsValidated)
                {
                    gc.Dispose();
                }
            }

            if (retry)
            {
                credsValidated = false;
                gc             = FindOneInternal(context, context.Name, siteName, flag | LocatorOptions.ForceRediscovery);
                try
                {
                    ValidateCredential(gc, context);
                    credsValidated = true;
                }
                catch (COMException e)
                {
                    if (e.ErrorCode == unchecked ((int)0x8007203a))
                    {
                        // server is down
                        throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.GCNotFoundInForest, context.Name), typeof(GlobalCatalog), null);
                    }
                    else
                    {
                        throw ExceptionHelper.GetExceptionFromCOMException(context, e);
                    }
                }
                finally
                {
                    if (!credsValidated)
                    {
                        gc.Dispose();
                    }
                }
            }

            return(gc);
        }
Exemple #27
0
        public void MoveToAnotherSite(string siteName)
        {
            CheckIfDisposed();

            // validate siteName
            if (siteName == null)
            {
                throw new ArgumentNullException("siteName");
            }

            if (siteName.Length == 0)
            {
                throw new ArgumentException(SR.EmptyStringParameter, "siteName");
            }

            // the dc is really being moved to a different site
            if (Utils.Compare(SiteName, siteName) != 0)
            {
                DirectoryEntry newParentEntry = null;
                try
                {
                    // Bind to the target site's server container
                    // Get the distinguished name for the site
                    string parentDN = "CN=Servers,CN=" + siteName + "," + directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.SitesContainer);
                    newParentEntry = DirectoryEntryManager.GetDirectoryEntry(context, parentDN);

                    string serverName = (this is DomainController) ? ((DomainController)this).ServerObjectName : ((AdamInstance)this).ServerObjectName;

                    DirectoryEntry serverEntry = directoryEntryMgr.GetCachedDirectoryEntry(serverName);

                    // force binding (needed otherwise S.DS throw an exception while releasing the COM interface pointer)
                    string dn = (string)PropertyManager.GetPropertyValue(context, serverEntry, PropertyManager.DistinguishedName);

                    // move the object to the servers container of the target site
                    serverEntry.MoveTo(newParentEntry);
                }
                catch (COMException e)
                {
                    throw ExceptionHelper.GetExceptionFromCOMException(context, e);
                }
                finally
                {
                    if (newParentEntry != null)
                    {
                        newParentEntry.Dispose();
                    }
                }

                // remove stale cached directory entries
                // invalidate the cached properties that get affected by this
                siteInfoModified = true;
                cachedSiteName   = null;

                if (cachedSiteObjectName != null)
                {
                    directoryEntryMgr.RemoveIfExists(cachedSiteObjectName);
                    cachedSiteObjectName = null;
                }

                if (cachedServerObjectName != null)
                {
                    directoryEntryMgr.RemoveIfExists(cachedServerObjectName);
                    cachedServerObjectName = null;
                }

                if (cachedNtdsaObjectName != null)
                {
                    directoryEntryMgr.RemoveIfExists(cachedNtdsaObjectName);
                    cachedNtdsaObjectName = null;
                }
            }
        }
Exemple #28
0
        public static ConfigurationSet GetConfigurationSet(DirectoryContext context)
        {
            // check that the argument is not null
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            // target should ConfigurationSet or DirectoryServer
            if ((context.ContextType != DirectoryContextType.ConfigurationSet) &&
                (context.ContextType != DirectoryContextType.DirectoryServer))
            {
                throw new ArgumentException(SR.TargetShouldBeServerORConfigSet, nameof(context));
            }

            // target should be an adam config set or server
            if (((!context.isServer()) && (!context.isADAMConfigSet())))
            {
                // the target should be a server or an ADAM Config Set
                if (context.ContextType == DirectoryContextType.ConfigurationSet)
                {
                    throw new ActiveDirectoryObjectNotFoundException(SR.ConfigSetNotFound, typeof(ConfigurationSet), context.Name);
                }
                else
                {
                    throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.AINotFound, context.Name), typeof(ConfigurationSet), null);
                }
            }

            //  work with copy of the context
            context = new DirectoryContext(context);

            //
            // bind to rootdse of an adam instance (if target is already a server, verify that it is an adam instance)
            //
            DirectoryEntryManager directoryEntryMgr = new DirectoryEntryManager(context);
            DirectoryEntry        rootDSE           = null;
            string configSetName = null;

            try
            {
                rootDSE = directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.RootDSE);
                if ((context.isServer()) && (!Utils.CheckCapability(rootDSE, Capability.ActiveDirectoryApplicationMode)))
                {
                    throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.AINotFound, context.Name), typeof(ConfigurationSet), null);
                }

                configSetName = (string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.ConfigurationNamingContext);
            }
            catch (COMException e)
            {
                int errorCode = e.ErrorCode;

                if (errorCode == unchecked ((int)0x8007203a))
                {
                    if (context.ContextType == DirectoryContextType.ConfigurationSet)
                    {
                        throw new ActiveDirectoryObjectNotFoundException(SR.ConfigSetNotFound, typeof(ConfigurationSet), context.Name);
                    }
                    else
                    {
                        throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.AINotFound, context.Name), typeof(ConfigurationSet), null);
                    }
                }
                else
                {
                    throw ExceptionHelper.GetExceptionFromCOMException(context, e);
                }
            }
            catch (ActiveDirectoryObjectNotFoundException)
            {
                if (context.ContextType == DirectoryContextType.ConfigurationSet)
                {
                    // this is the case when we could not find an ADAM instance in that config set
                    throw new ActiveDirectoryObjectNotFoundException(SR.ConfigSetNotFound, typeof(ConfigurationSet), context.Name);
                }
                else
                {
                    throw;
                }
            }

            // return config set object
            return(new ConfigurationSet(context, configSetName, directoryEntryMgr));
        }
Exemple #29
0
        private ArrayList GetApplicationPartitions()
        {
            ArrayList      appNCs          = new ArrayList();
            DirectoryEntry rootDSE         = _directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.RootDSE);
            DirectoryEntry partitionsEntry = _directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.PartitionsContainer);

            // search for all the "crossRef" objects that have the
            // ADS_SYSTEMFLAG_CR_NTDS_NC set and the SYSTEMFLAG_CR_NTDS_DOMAIN flag not set
            // (one-level search is good enough)
            // setup the directory searcher object

            // build the filter
            StringBuilder str = new StringBuilder(100);

            str.Append("(&(");
            str.Append(PropertyManager.ObjectCategory);
            str.Append("=crossRef)(");
            str.Append(PropertyManager.SystemFlags);
            str.Append(":1.2.840.113556.1.4.804:=");
            str.Append((int)SystemFlag.SystemFlagNtdsNC);
            str.Append(")(!(");
            str.Append(PropertyManager.SystemFlags);
            str.Append(":1.2.840.113556.1.4.803:=");
            str.Append((int)SystemFlag.SystemFlagNtdsDomain);
            str.Append(")))");

            string filter = str.ToString();

            string[] propertiesToLoad = new string[2];
            propertiesToLoad[0] = PropertyManager.NCName;
            propertiesToLoad[1] = PropertyManager.MsDSNCReplicaLocations;

            ADSearcher             searcher = new ADSearcher(partitionsEntry, filter, propertiesToLoad, SearchScope.OneLevel);
            SearchResultCollection resCol   = null;

            try
            {
                resCol = searcher.FindAll();

                string schemaNamingContext        = (string)PropertyManager.GetPropertyValue(_context, rootDSE, PropertyManager.SchemaNamingContext);
                string configurationNamingContext = (string)PropertyManager.GetPropertyValue(_context, rootDSE, PropertyManager.ConfigurationNamingContext);

                foreach (SearchResult res in resCol)
                {
                    // add the name of the appNC only if it is not
                    // the Schema or Configuration partition
                    string nCName = (string)PropertyManager.GetSearchResultPropertyValue(res, PropertyManager.NCName);

                    if ((!(nCName.Equals(schemaNamingContext))) && (!(nCName.Equals(configurationNamingContext))))
                    {
                        ResultPropertyValueCollection replicaLocations = res.Properties[PropertyManager.MsDSNCReplicaLocations];
                        if (replicaLocations.Count > 0)
                        {
                            string           replicaName  = Utils.GetAdamDnsHostNameFromNTDSA(_context, (string)replicaLocations[Utils.GetRandomIndex(replicaLocations.Count)]);
                            DirectoryContext appNCContext = Utils.GetNewDirectoryContext(replicaName, DirectoryContextType.DirectoryServer, _context);
                            appNCs.Add(new ApplicationPartition(appNCContext, nCName, null, ApplicationPartitionType.ADAMApplicationPartition, new DirectoryEntryManager(appNCContext)));
                        }
                    }
                }
            }
            catch (COMException e)
            {
                throw ExceptionHelper.GetExceptionFromCOMException(_context, e);
            }
            finally
            {
                if (resCol != null)
                {
                    // call dispose on search result collection
                    resCol.Dispose();
                }
            }
            return(appNCs);
        }
Exemple #30
0
        internal static AdamInstance FindAnyAdamInstance(DirectoryContext context)
        {
            if (context.ContextType != DirectoryContextType.ConfigurationSet)
            {
                // assuming it's an ADAM Instance
                // check that it is an ADAM server only (not AD)
                DirectoryEntryManager directoryEntryMgr = new DirectoryEntryManager(context);
                DirectoryEntry        rootDSE           = directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.RootDSE);

                if (!Utils.CheckCapability(rootDSE, Capability.ActiveDirectoryApplicationMode))
                {
                    directoryEntryMgr.RemoveIfExists(directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.RootDSE));
                    throw new ArgumentException(SR.TargetShouldBeServerORConfigSet, nameof(context));
                }

                string dnsHostName = (string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.DnsHostName);

                return(new AdamInstance(context, dnsHostName, directoryEntryMgr));
            }

            // Now this is the case where context is a Config Set
            // Here we need to search for the service connection points in the forest
            // (if the forest object was created by specifying the server, we stick to that, else search in a GC)
            DirectoryEntry rootEntry         = GetSearchRootEntry(Forest.GetCurrentForest());
            ArrayList      adamInstanceNames = new ArrayList();

            try
            {
                string entryName = (string)rootEntry.Properties["distinguishedName"].Value;

                // Search for computer "serviceConnectionObjects" where the keywords attribute
                // contains the specified keyword
                // set up the searcher object

                // build the filter
                StringBuilder str = new StringBuilder(15);
                str.Append("(&(");
                str.Append(PropertyManager.ObjectCategory);
                str.Append("=serviceConnectionPoint)");
                str.Append("(");
                str.Append(PropertyManager.Keywords);
                str.Append("=1.2.840.113556.1.4.1851)(");
                str.Append(PropertyManager.Keywords);
                str.Append("=");
                str.Append(Utils.GetEscapedFilterValue(context.Name)); // target = config set name
                str.Append("))");

                string   filter           = str.ToString();
                string[] propertiesToLoad = new string[1];

                propertiesToLoad[0] = PropertyManager.ServiceBindingInformation;

                ADSearcher             searcher = new ADSearcher(rootEntry, filter, propertiesToLoad, SearchScope.Subtree, false /*not paged search*/, false /*no cached results*/);
                SearchResultCollection resCol   = searcher.FindAll();

                try
                {
                    foreach (SearchResult res in resCol)
                    {
                        // the binding info contains two values
                        // "ldap://hostname:ldapport"
                        // and "ldaps://hostname:sslport"
                        // we need the "hostname:ldapport" value
                        string prefix = "ldap://";

                        foreach (string bindingInfo in res.Properties[PropertyManager.ServiceBindingInformation])
                        {
                            if ((bindingInfo.Length > prefix.Length) && (string.Equals(bindingInfo.Substring(0, prefix.Length), prefix, StringComparison.OrdinalIgnoreCase)))
                            {
                                adamInstanceNames.Add(bindingInfo.Substring(prefix.Length));
                            }
                        }
                    }
                }
                finally
                {
                    resCol.Dispose();
                }
            }
            catch (COMException e)
            {
                throw ExceptionHelper.GetExceptionFromCOMException(context, e);
            }
            finally
            {
                rootEntry.Dispose();
            }

            //
            // we have all the adam instance names in teh form of server:port from the scp
            // now we need to find one that is alive
            //
            return(FindAliveAdamInstance(null, context, adamInstanceNames));
        }