Ejemplo n.º 1
0
        public void RaiseForestFunctionalityLevel(int forestMode)
        {
            CheckIfDisposed();

            // check new functional level is valid or not
            if (forestMode < 0)
            {
                throw new ArgumentException(SR.InvalidMode, nameof(forestMode));
            }

            // new functional level should be higher than the old one
            if (forestMode <= ForestModeLevel)
            {
                throw new ArgumentException(SR.InvalidMode, nameof(forestMode));
            }

            // set the forest mode on AD
            DirectoryEntry partitionsEntry = DirectoryEntryManager.GetDirectoryEntry(_context, _directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.PartitionsContainer));

            // NOTE:
            // If the domain is a W2K domain (W2K schema) then the msDS-Behavior-Version attribute will not be present.
            // If that is the case, the forest functionality cannot be raised.
            try
            {
                partitionsEntry.Properties[PropertyManager.MsDSBehaviorVersion].Value = forestMode;
                partitionsEntry.CommitChanges();
            }
            catch (System.Runtime.InteropServices.COMException e)
            {
                if (e.ErrorCode == unchecked ((int)0x8007200A))
                {
                    throw new ArgumentException(SR.NoW2K3DCsInForest, nameof(forestMode));
                }
                else
                {
                    throw ExceptionHelper.GetExceptionFromCOMException(_context, e);
                }
            }
            finally
            {
                partitionsEntry.Dispose();
            }

            // at this point the raise forest function has succeeded
            // invalidate the cached entry so that we will go to the server next time
            _forestModeLevel = -1;
        }
        internal static AdamInstance FindAnyAdamInstance(DirectoryContext context)
        {
            if (context.ContextType != DirectoryContextType.ConfigurationSet)
            {
                DirectoryEntryManager directoryEntryMgr    = new DirectoryEntryManager(context);
                DirectoryEntry        cachedDirectoryEntry = directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.RootDSE);
                if (!Utils.CheckCapability(cachedDirectoryEntry, Capability.ActiveDirectoryApplicationMode))
                {
                    directoryEntryMgr.RemoveIfExists(directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.RootDSE));
                    throw new ArgumentException(Res.GetString("TargetShouldBeServerORConfigSet"), "context");
                }
                return(new AdamInstance(context, (string)PropertyManager.GetPropertyValue(context, cachedDirectoryEntry, PropertyManager.DnsHostName), directoryEntryMgr));
            }
            DirectoryEntry searchRootEntry   = GetSearchRootEntry(Forest.GetCurrentForest());
            ArrayList      adamInstanceNames = new ArrayList();

            try
            {
                string        text1   = (string)searchRootEntry.Properties["distinguishedName"].Value;
                StringBuilder builder = new StringBuilder(15);
                builder.Append("(&(");
                builder.Append(PropertyManager.ObjectCategory);
                builder.Append("=serviceConnectionPoint)");
                builder.Append("(");
                builder.Append(PropertyManager.Keywords);
                builder.Append("=1.2.840.113556.1.4.1851)(");
                builder.Append(PropertyManager.Keywords);
                builder.Append("=");
                builder.Append(Utils.GetEscapedFilterValue(context.Name));
                builder.Append("))");
                string     filter           = builder.ToString();
                string[]   propertiesToLoad = new string[] { PropertyManager.ServiceBindingInformation };
                ADSearcher searcher         = new ADSearcher(searchRootEntry, filter, propertiesToLoad, SearchScope.Subtree, false, false);
                using (SearchResultCollection results = searcher.FindAll())
                {
                    foreach (SearchResult result in results)
                    {
                        string strB = "ldap://";
                        foreach (string str4 in result.Properties[PropertyManager.ServiceBindingInformation])
                        {
                            if ((str4.Length > strB.Length) && (string.Compare(str4.Substring(0, strB.Length), strB, StringComparison.OrdinalIgnoreCase) == 0))
                            {
                                adamInstanceNames.Add(str4.Substring(strB.Length));
                            }
                        }
                    }
                }
            }
            catch (COMException exception)
            {
                throw ExceptionHelper.GetExceptionFromCOMException(context, exception);
            }
            finally
            {
                searchRootEntry.Dispose();
            }
            return(FindAliveAdamInstance(null, context, adamInstanceNames));
        }
Ejemplo n.º 3
0
        internal static string ExpandWellKnownDN(DirectoryContext context, WellKnownDN dn)
        {
            string      propertyValue = null;
            WellKnownDN wellKnownDN   = dn;

            if (wellKnownDN == WellKnownDN.RootDSE)
            {
                propertyValue = "RootDSE";
            }
            else if (wellKnownDN == WellKnownDN.DefaultNamingContext)
            {
                DirectoryEntry directoryEntry = DirectoryEntryManager.GetDirectoryEntry(context, "RootDSE");
                try
                {
                    propertyValue = (string)PropertyManager.GetPropertyValue(context, directoryEntry, PropertyManager.DefaultNamingContext);
                }
                finally
                {
                    directoryEntry.Dispose();
                }
            }
            else if (wellKnownDN == WellKnownDN.SchemaNamingContext)
            {
                DirectoryEntry directoryEntry1 = DirectoryEntryManager.GetDirectoryEntry(context, "RootDSE");
                try
                {
                    propertyValue = (string)PropertyManager.GetPropertyValue(context, directoryEntry1, PropertyManager.SchemaNamingContext);
                }
                finally
                {
                    directoryEntry1.Dispose();
                }
            }
            else if (wellKnownDN == WellKnownDN.ConfigurationNamingContext)
            {
                DirectoryEntry directoryEntry2 = DirectoryEntryManager.GetDirectoryEntry(context, "RootDSE");
                try
                {
                    propertyValue = (string)PropertyManager.GetPropertyValue(context, directoryEntry2, PropertyManager.ConfigurationNamingContext);
                }
                finally
                {
                    directoryEntry2.Dispose();
                }
            }
            else if (wellKnownDN == WellKnownDN.PartitionsContainer)
            {
                propertyValue = string.Concat("CN=Partitions,", DirectoryEntryManager.ExpandWellKnownDN(context, WellKnownDN.ConfigurationNamingContext));
            }
            else if (wellKnownDN == WellKnownDN.SitesContainer)
            {
                propertyValue = string.Concat("CN=Sites,", DirectoryEntryManager.ExpandWellKnownDN(context, WellKnownDN.ConfigurationNamingContext));
            }
            else if (wellKnownDN == WellKnownDN.SystemContainer)
            {
                propertyValue = string.Concat("CN=System,", DirectoryEntryManager.ExpandWellKnownDN(context, WellKnownDN.DefaultNamingContext));
            }
            else if (wellKnownDN == WellKnownDN.RidManager)
            {
                propertyValue = string.Concat("CN=RID Manager$,", DirectoryEntryManager.ExpandWellKnownDN(context, WellKnownDN.SystemContainer));
            }
            else if (wellKnownDN == WellKnownDN.Infrastructure)
            {
                propertyValue = string.Concat("CN=Infrastructure,", DirectoryEntryManager.ExpandWellKnownDN(context, WellKnownDN.DefaultNamingContext));
            }
            else if (wellKnownDN == WellKnownDN.RootDomainNamingContext)
            {
                DirectoryEntry directoryEntry3 = DirectoryEntryManager.GetDirectoryEntry(context, "RootDSE");
                try
                {
                    propertyValue = (string)PropertyManager.GetPropertyValue(context, directoryEntry3, PropertyManager.RootDomainNamingContext);
                }
                finally
                {
                    directoryEntry3.Dispose();
                }
            }
            else
            {
                throw new InvalidEnumArgumentException("dn", (int)dn, typeof(WellKnownDN));
            }
            return(propertyValue);
        }
Ejemplo n.º 4
0
 internal static DirectoryEntry GetDirectoryEntry(DirectoryContext context, WellKnownDN dn)
 {
     return(DirectoryEntryManager.GetDirectoryEntry(context, DirectoryEntryManager.ExpandWellKnownDN(context, dn)));
 }
Ejemplo n.º 5
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;
                }
            }
        }
Ejemplo n.º 6
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));
        }
Ejemplo n.º 7
0
		internal static AdamInstance FindAnyAdamInstance(DirectoryContext context)
		{
			if (context.ContextType == DirectoryContextType.ConfigurationSet)
			{
				DirectoryEntry searchRootEntry = ConfigurationSet.GetSearchRootEntry(Forest.GetCurrentForest());
				ArrayList arrayLists = new ArrayList();
				try
				{
					try
					{
						StringBuilder stringBuilder = new StringBuilder(15);
						stringBuilder.Append("(&(");
						stringBuilder.Append(PropertyManager.ObjectCategory);
						stringBuilder.Append("=serviceConnectionPoint)");
						stringBuilder.Append("(");
						stringBuilder.Append(PropertyManager.Keywords);
						stringBuilder.Append("=1.2.840.113556.1.4.1851)(");
						stringBuilder.Append(PropertyManager.Keywords);
						stringBuilder.Append("=");
						stringBuilder.Append(Utils.GetEscapedFilterValue(context.Name));
						stringBuilder.Append("))");
						string str = stringBuilder.ToString();
						string[] serviceBindingInformation = new string[1];
						serviceBindingInformation[0] = PropertyManager.ServiceBindingInformation;
						ADSearcher aDSearcher = new ADSearcher(searchRootEntry, str, serviceBindingInformation, SearchScope.Subtree, false, false);
						SearchResultCollection searchResultCollections = aDSearcher.FindAll();
						try
						{
							foreach (SearchResult item in searchResultCollections)
							{
								string str1 = "ldap://";
								IEnumerator enumerator = item.Properties[PropertyManager.ServiceBindingInformation].GetEnumerator();
								try
								{
									while (enumerator.MoveNext())
									{
										string str2 = item.ToString ();
										if (str2.Length <= str1.Length || string.Compare(str2.Substring(0, str1.Length), str1, StringComparison.OrdinalIgnoreCase) != 0)
										{
											continue;
										}
										arrayLists.Add(str2.Substring(str1.Length));
									}
								}
								finally
								{
									IDisposable disposable = enumerator as IDisposable;
									if (disposable != null)
									{
										disposable.Dispose();
									}
								}
							}
						}
						finally
						{
							searchResultCollections.Dispose();
						}
					}
					catch (COMException cOMException1)
					{
						COMException cOMException = cOMException1;
						throw ExceptionHelper.GetExceptionFromCOMException(context, cOMException);
					}
				}
				finally
				{
					searchRootEntry.Dispose();
				}
				return ConfigurationSet.FindAliveAdamInstance(null, context, arrayLists);
			}
			else
			{
				DirectoryEntryManager directoryEntryManager = new DirectoryEntryManager(context);
				DirectoryEntry cachedDirectoryEntry = directoryEntryManager.GetCachedDirectoryEntry(WellKnownDN.RootDSE);
				if (Utils.CheckCapability(cachedDirectoryEntry, Capability.ActiveDirectoryApplicationMode))
				{
					string propertyValue = (string)PropertyManager.GetPropertyValue(context, cachedDirectoryEntry, PropertyManager.DnsHostName);
					return new AdamInstance(context, propertyValue, directoryEntryManager);
				}
				else
				{
					directoryEntryManager.RemoveIfExists(directoryEntryManager.ExpandWellKnownDN(WellKnownDN.RootDSE));
					throw new ArgumentException(Res.GetString("TargetShouldBeServerORConfigSet"), "context");
				}
			}
		}
Ejemplo n.º 8
0
        public static ApplicationPartition FindByName(DirectoryContext context, string distinguishedName)
        {
            ApplicationPartition partition = null;
            DirectoryEntryManager directoryEntryMgr = null;
            DirectoryContext appNCContext = null;

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

            if ((context.Name == null) && (!context.isRootDomain()))
            {
                throw new ArgumentException(Res.GetString(Res.ContextNotAssociatedWithDomain), "context");
            }

            if (context.Name != null)
            {
                // the target should be a valid forest name, configset name or a server
                if (!((context.isRootDomain()) || (context.isADAMConfigSet()) || context.isServer()))
                {
                    throw new ArgumentException(Res.GetString(Res.NotADOrADAM), "context");
                }
            }

            // check that the distingushed name of the application partition is not null or empty
            if (distinguishedName == null)
                throw new ArgumentNullException("distinguishedName");

            if (distinguishedName.Length == 0)
                throw new ArgumentException(Res.GetString(Res.EmptyStringParameter), "distinguishedName");

            if (!Utils.IsValidDNFormat(distinguishedName))
                throw new ArgumentException(Res.GetString(Res.InvalidDNFormat), "distinguishedName");

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

            // search in the partitions container of the forest for 
            // crossRef objects that have their nCName set to the specified distinguishedName
            directoryEntryMgr = new DirectoryEntryManager(context);
            DirectoryEntry partitionsEntry = null;

            try
            {
                partitionsEntry = DirectoryEntryManager.GetDirectoryEntry(context, directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.PartitionsContainer));
            }
            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));
            }

            // build the filter
            StringBuilder str = new StringBuilder(15);
            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("))(");
            str.Append(PropertyManager.NCName);
            str.Append("=");
            str.Append(Utils.GetEscapedFilterValue(distinguishedName));
            str.Append("))");

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

            propertiesToLoad[0] = PropertyManager.DnsRoot;
            propertiesToLoad[1] = PropertyManager.NCName;

            ADSearcher searcher = new ADSearcher(partitionsEntry, filter, propertiesToLoad, SearchScope.OneLevel, false /*not paged search*/, false /*no cached results*/);
            SearchResult res = null;

            try
            {
                res = searcher.FindOne();
            }
            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.AppNCNotFound), typeof(ApplicationPartition), distinguishedName);
                }
                else
                {
                    throw ExceptionHelper.GetExceptionFromCOMException(context, e);
                }
            }
            finally
            {
                partitionsEntry.Dispose();
            }

            if (res == null)
            {
                // the specified application partition could not be found in the given forest
                throw new ActiveDirectoryObjectNotFoundException(Res.GetString(Res.AppNCNotFound), typeof(ApplicationPartition), distinguishedName);
            }

            string appNCDnsName = null;
            try
            {
                appNCDnsName = (res.Properties[PropertyManager.DnsRoot].Count > 0) ? (string)res.Properties[PropertyManager.DnsRoot][0] : null;
            }
            catch (COMException e)
            {
                throw ExceptionHelper.GetExceptionFromCOMException(context, e);
            }

            // verify that if the target is a server, then this partition is a naming context on it
            ApplicationPartitionType appType = GetApplicationPartitionType(context);
            if (context.ContextType == DirectoryContextType.DirectoryServer)
            {
                bool hostsCurrentPartition = false;
                DistinguishedName appNCDN = new DistinguishedName(distinguishedName);
                DirectoryEntry rootDSE = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE);

                try
                {
                    foreach (string namingContext in rootDSE.Properties[PropertyManager.NamingContexts])
                    {
                        DistinguishedName dn = new DistinguishedName(namingContext);

                        if (dn.Equals(appNCDN))
                        {
                            hostsCurrentPartition = true;
                            break;
                        }
                    }
                }
                catch (COMException e)
                {
                    throw ExceptionHelper.GetExceptionFromCOMException(context, e);
                }
                finally
                {
                    rootDSE.Dispose();
                }

                if (!hostsCurrentPartition)
                {
                    throw new ActiveDirectoryObjectNotFoundException(Res.GetString(Res.AppNCNotFound), typeof(ApplicationPartition), distinguishedName);
                }

                appNCContext = context;
            }
            else
            {
                // we need to find a server which hosts this application partition
                if (appType == ApplicationPartitionType.ADApplicationPartition)
                {
                    int errorCode = 0;
                    DomainControllerInfo domainControllerInfo;

                    errorCode = Locator.DsGetDcNameWrapper(null, appNCDnsName, null, (long)PrivateLocatorFlags.OnlyLDAPNeeded, out domainControllerInfo);

                    if (errorCode == NativeMethods.ERROR_NO_SUCH_DOMAIN)
                    {
                        throw new ActiveDirectoryObjectNotFoundException(Res.GetString(Res.AppNCNotFound), typeof(ApplicationPartition), distinguishedName);
                    }
                    else if (errorCode != 0)
                    {
                        throw ExceptionHelper.GetExceptionFromErrorCode(errorCode);
                    }

                    Debug.Assert(domainControllerInfo.DomainControllerName.Length > 2, "ApplicationPartition:FindByName - domainControllerInfo.DomainControllerName.Length <= 2");
                    string serverName = domainControllerInfo.DomainControllerName.Substring(2);
                    appNCContext = Utils.GetNewDirectoryContext(serverName, DirectoryContextType.DirectoryServer, context);
                }
                else
                {
                    // this will find an adam instance that hosts this partition and which is alive and responding.
                    string adamInstName = ConfigurationSet.FindOneAdamInstance(context.Name, context, distinguishedName, null).Name;
                    appNCContext = Utils.GetNewDirectoryContext(adamInstName, DirectoryContextType.DirectoryServer, context);
                }
            }
            partition = new ApplicationPartition(appNCContext, (string)PropertyManager.GetSearchResultPropertyValue(res, PropertyManager.NCName), appNCDnsName, appType, directoryEntryMgr);

            return partition;
        }
 internal static AdamInstance FindAnyAdamInstance(DirectoryContext context)
 {
     if (context.ContextType != DirectoryContextType.ConfigurationSet)
     {
         DirectoryEntryManager directoryEntryMgr = new DirectoryEntryManager(context);
         DirectoryEntry cachedDirectoryEntry = directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.RootDSE);
         if (!Utils.CheckCapability(cachedDirectoryEntry, Capability.ActiveDirectoryApplicationMode))
         {
             directoryEntryMgr.RemoveIfExists(directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.RootDSE));
             throw new ArgumentException(Res.GetString("TargetShouldBeServerORConfigSet"), "context");
         }
         return new AdamInstance(context, (string) PropertyManager.GetPropertyValue(context, cachedDirectoryEntry, PropertyManager.DnsHostName), directoryEntryMgr);
     }
     DirectoryEntry searchRootEntry = GetSearchRootEntry(Forest.GetCurrentForest());
     ArrayList adamInstanceNames = new ArrayList();
     try
     {
         string text1 = (string) searchRootEntry.Properties["distinguishedName"].Value;
         StringBuilder builder = new StringBuilder(15);
         builder.Append("(&(");
         builder.Append(PropertyManager.ObjectCategory);
         builder.Append("=serviceConnectionPoint)");
         builder.Append("(");
         builder.Append(PropertyManager.Keywords);
         builder.Append("=1.2.840.113556.1.4.1851)(");
         builder.Append(PropertyManager.Keywords);
         builder.Append("=");
         builder.Append(Utils.GetEscapedFilterValue(context.Name));
         builder.Append("))");
         string filter = builder.ToString();
         string[] propertiesToLoad = new string[] { PropertyManager.ServiceBindingInformation };
         ADSearcher searcher = new ADSearcher(searchRootEntry, filter, propertiesToLoad, SearchScope.Subtree, false, false);
         using (SearchResultCollection results = searcher.FindAll())
         {
             foreach (SearchResult result in results)
             {
                 string strB = "ldap://";
                 foreach (string str4 in result.Properties[PropertyManager.ServiceBindingInformation])
                 {
                     if ((str4.Length > strB.Length) && (string.Compare(str4.Substring(0, strB.Length), strB, StringComparison.OrdinalIgnoreCase) == 0))
                     {
                         adamInstanceNames.Add(str4.Substring(strB.Length));
                     }
                 }
             }
         }
     }
     catch (COMException exception)
     {
         throw ExceptionHelper.GetExceptionFromCOMException(context, exception);
     }
     finally
     {
         searchRootEntry.Dispose();
     }
     return FindAliveAdamInstance(null, context, adamInstanceNames);
 }
Ejemplo n.º 10
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(Res.GetString(Res.TargetShouldBeServerORConfigSet), "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.Compare(bindingInfo.Substring(0, prefix.Length), prefix, StringComparison.OrdinalIgnoreCase) == 0))
                            {
                                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);
        }
Ejemplo n.º 11
0
		public static ApplicationPartition FindByName(DirectoryContext context, string distinguishedName)
		{
			DomainControllerInfo domainControllerInfo = null;
			string item;
			DirectoryContext newDirectoryContext = null;
			if (context != null)
			{
				if (context.Name != null || context.isRootDomain())
				{
					if (context.Name == null || context.isRootDomain() || context.isADAMConfigSet() || context.isServer())
					{
						if (distinguishedName != null)
						{
							if (distinguishedName.Length != 0)
							{
								if (Utils.IsValidDNFormat(distinguishedName))
								{
									context = new DirectoryContext(context);
									DirectoryEntryManager directoryEntryManager = new DirectoryEntryManager(context);
									DirectoryEntry directoryEntry = null;
									try
									{
										directoryEntry = DirectoryEntryManager.GetDirectoryEntry(context, directoryEntryManager.ExpandWellKnownDN(WellKnownDN.PartitionsContainer));
									}
									catch (COMException cOMException1)
									{
										COMException cOMException = cOMException1;
										throw ExceptionHelper.GetExceptionFromCOMException(context, cOMException);
									}
									catch (ActiveDirectoryObjectNotFoundException activeDirectoryObjectNotFoundException)
									{
										object[] name = new object[1];
										name[0] = context.Name;
										throw new ActiveDirectoryOperationException(Res.GetString("ADAMInstanceNotFoundInConfigSet", name));
									}
									StringBuilder stringBuilder = new StringBuilder(15);
									stringBuilder.Append("(&(");
									stringBuilder.Append(PropertyManager.ObjectCategory);
									stringBuilder.Append("=crossRef)(");
									stringBuilder.Append(PropertyManager.SystemFlags);
									stringBuilder.Append(":1.2.840.113556.1.4.804:=");
									stringBuilder.Append(1);
									stringBuilder.Append(")(!(");
									stringBuilder.Append(PropertyManager.SystemFlags);
									stringBuilder.Append(":1.2.840.113556.1.4.803:=");
									stringBuilder.Append(2);
									stringBuilder.Append("))(");
									stringBuilder.Append(PropertyManager.NCName);
									stringBuilder.Append("=");
									stringBuilder.Append(Utils.GetEscapedFilterValue(distinguishedName));
									stringBuilder.Append("))");
									string str = stringBuilder.ToString();
									string[] dnsRoot = new string[2];
									dnsRoot[0] = PropertyManager.DnsRoot;
									dnsRoot[1] = PropertyManager.NCName;
									ADSearcher aDSearcher = new ADSearcher(directoryEntry, str, dnsRoot, SearchScope.OneLevel, false, false);
									SearchResult searchResult = null;
									try
									{
										try
										{
											searchResult = aDSearcher.FindOne();
										}
										catch (COMException cOMException3)
										{
											COMException cOMException2 = cOMException3;
											if (cOMException2.ErrorCode != -2147016656)
											{
												throw ExceptionHelper.GetExceptionFromCOMException(context, cOMException2);
											}
											else
											{
												throw new ActiveDirectoryObjectNotFoundException(Res.GetString("AppNCNotFound"), typeof(ApplicationPartition), distinguishedName);
											}
										}
									}
									finally
									{
										directoryEntry.Dispose();
									}
									if (searchResult != null)
									{
										string str1 = null;
										try
										{
											if (searchResult.Properties[PropertyManager.DnsRoot].Count > 0)
											{
												item = (string)searchResult.Properties[PropertyManager.DnsRoot][0];
											}
											else
											{
												item = null;
											}
											str1 = item;
										}
										catch (COMException cOMException5)
										{
											COMException cOMException4 = cOMException5;
											throw ExceptionHelper.GetExceptionFromCOMException(context, cOMException4);
										}
										ApplicationPartitionType applicationPartitionType = ApplicationPartition.GetApplicationPartitionType(context);
										if (context.ContextType != DirectoryContextType.DirectoryServer)
										{
											if (applicationPartitionType != ApplicationPartitionType.ADApplicationPartition)
											{
												string name1 = ConfigurationSet.FindOneAdamInstance(context.Name, context, distinguishedName, null).Name;
												newDirectoryContext = Utils.GetNewDirectoryContext(name1, DirectoryContextType.DirectoryServer, context);
											}
											else
											{
												int num = Locator.DsGetDcNameWrapper(null, str1, null, (long)0x8000, out domainControllerInfo);
												if (num != 0x54b)
												{
													if (num == 0)
													{
														string str2 = domainControllerInfo.DomainControllerName.Substring(2);
														newDirectoryContext = Utils.GetNewDirectoryContext(str2, DirectoryContextType.DirectoryServer, context);
													}
													else
													{
														throw ExceptionHelper.GetExceptionFromErrorCode(num);
													}
												}
												else
												{
													throw new ActiveDirectoryObjectNotFoundException(Res.GetString("AppNCNotFound"), typeof(ApplicationPartition), distinguishedName);
												}
											}
										}
										else
										{
											bool flag = false;
											DistinguishedName distinguishedName1 = new DistinguishedName(distinguishedName);
											DirectoryEntry directoryEntry1 = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE);
											try
											{
												try
												{
													foreach (string item1 in directoryEntry1.Properties[PropertyManager.NamingContexts])
													{
														DistinguishedName distinguishedName2 = new DistinguishedName(item1);
														if (!distinguishedName2.Equals(distinguishedName1))
														{
															continue;
														}
														flag = true;
														break;
													}
												}
												catch (COMException cOMException7)
												{
													COMException cOMException6 = cOMException7;
													throw ExceptionHelper.GetExceptionFromCOMException(context, cOMException6);
												}
											}
											finally
											{
												directoryEntry1.Dispose();
											}
											if (flag)
											{
												newDirectoryContext = context;
											}
											else
											{
												throw new ActiveDirectoryObjectNotFoundException(Res.GetString("AppNCNotFound"), typeof(ApplicationPartition), distinguishedName);
											}
										}
										ApplicationPartition applicationPartition = new ApplicationPartition(newDirectoryContext, (string)PropertyManager.GetSearchResultPropertyValue(searchResult, PropertyManager.NCName), str1, applicationPartitionType, directoryEntryManager);
										return applicationPartition;
									}
									else
									{
										throw new ActiveDirectoryObjectNotFoundException(Res.GetString("AppNCNotFound"), typeof(ApplicationPartition), distinguishedName);
									}
								}
								else
								{
									throw new ArgumentException(Res.GetString("InvalidDNFormat"), "distinguishedName");
								}
							}
							else
							{
								throw new ArgumentException(Res.GetString("EmptyStringParameter"), "distinguishedName");
							}
						}
						else
						{
							throw new ArgumentNullException("distinguishedName");
						}
					}
					else
					{
						throw new ArgumentException(Res.GetString("NotADOrADAM"), "context");
					}
				}
				else
				{
					throw new ArgumentException(Res.GetString("ContextNotAssociatedWithDomain"), "context");
				}
			}
			else
			{
				throw new ArgumentNullException("context");
			}
		}
Ejemplo n.º 12
0
 internal static AdamInstance FindAnyAdamInstance(DirectoryContext context)
 {
     if (context.ContextType == DirectoryContextType.ConfigurationSet)
     {
         DirectoryEntry searchRootEntry = ConfigurationSet.GetSearchRootEntry(Forest.GetCurrentForest());
         ArrayList      arrayLists      = new ArrayList();
         try
         {
             try
             {
                 StringBuilder stringBuilder = new StringBuilder(15);
                 stringBuilder.Append("(&(");
                 stringBuilder.Append(PropertyManager.ObjectCategory);
                 stringBuilder.Append("=serviceConnectionPoint)");
                 stringBuilder.Append("(");
                 stringBuilder.Append(PropertyManager.Keywords);
                 stringBuilder.Append("=1.2.840.113556.1.4.1851)(");
                 stringBuilder.Append(PropertyManager.Keywords);
                 stringBuilder.Append("=");
                 stringBuilder.Append(Utils.GetEscapedFilterValue(context.Name));
                 stringBuilder.Append("))");
                 string   str = stringBuilder.ToString();
                 string[] serviceBindingInformation = new string[1];
                 serviceBindingInformation[0] = PropertyManager.ServiceBindingInformation;
                 ADSearcher             aDSearcher = new ADSearcher(searchRootEntry, str, serviceBindingInformation, SearchScope.Subtree, false, false);
                 SearchResultCollection searchResultCollections = aDSearcher.FindAll();
                 try
                 {
                     foreach (SearchResult item in searchResultCollections)
                     {
                         string      str1       = "ldap://";
                         IEnumerator enumerator = item.Properties[PropertyManager.ServiceBindingInformation].GetEnumerator();
                         try
                         {
                             while (enumerator.MoveNext())
                             {
                                 string str2 = item.ToString();
                                 if (str2.Length <= str1.Length || string.Compare(str2.Substring(0, str1.Length), str1, StringComparison.OrdinalIgnoreCase) != 0)
                                 {
                                     continue;
                                 }
                                 arrayLists.Add(str2.Substring(str1.Length));
                             }
                         }
                         finally
                         {
                             IDisposable disposable = enumerator as IDisposable;
                             if (disposable != null)
                             {
                                 disposable.Dispose();
                             }
                         }
                     }
                 }
                 finally
                 {
                     searchResultCollections.Dispose();
                 }
             }
             catch (COMException cOMException1)
             {
                 COMException cOMException = cOMException1;
                 throw ExceptionHelper.GetExceptionFromCOMException(context, cOMException);
             }
         }
         finally
         {
             searchRootEntry.Dispose();
         }
         return(ConfigurationSet.FindAliveAdamInstance(null, context, arrayLists));
     }
     else
     {
         DirectoryEntryManager directoryEntryManager = new DirectoryEntryManager(context);
         DirectoryEntry        cachedDirectoryEntry  = directoryEntryManager.GetCachedDirectoryEntry(WellKnownDN.RootDSE);
         if (Utils.CheckCapability(cachedDirectoryEntry, Capability.ActiveDirectoryApplicationMode))
         {
             string propertyValue = (string)PropertyManager.GetPropertyValue(context, cachedDirectoryEntry, PropertyManager.DnsHostName);
             return(new AdamInstance(context, propertyValue, directoryEntryManager));
         }
         else
         {
             directoryEntryManager.RemoveIfExists(directoryEntryManager.ExpandWellKnownDN(WellKnownDN.RootDSE));
             throw new ArgumentException(Res.GetString("TargetShouldBeServerORConfigSet"), "context");
         }
     }
 }
 public static ApplicationPartition FindByName(DirectoryContext context, string distinguishedName)
 {
     DirectoryEntryManager directoryEntryMgr = null;
     DirectoryContext context2 = null;
     if (context == null)
     {
         throw new ArgumentNullException("context");
     }
     if ((context.Name == null) && !context.isRootDomain())
     {
         throw new ArgumentException(Res.GetString("ContextNotAssociatedWithDomain"), "context");
     }
     if (((context.Name != null) && !context.isRootDomain()) && (!context.isADAMConfigSet() && !context.isServer()))
     {
         throw new ArgumentException(Res.GetString("NotADOrADAM"), "context");
     }
     if (distinguishedName == null)
     {
         throw new ArgumentNullException("distinguishedName");
     }
     if (distinguishedName.Length == 0)
     {
         throw new ArgumentException(Res.GetString("EmptyStringParameter"), "distinguishedName");
     }
     if (!Utils.IsValidDNFormat(distinguishedName))
     {
         throw new ArgumentException(Res.GetString("InvalidDNFormat"), "distinguishedName");
     }
     context = new DirectoryContext(context);
     directoryEntryMgr = new DirectoryEntryManager(context);
     DirectoryEntry searchRoot = null;
     try
     {
         searchRoot = DirectoryEntryManager.GetDirectoryEntry(context, directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.PartitionsContainer));
     }
     catch (COMException exception)
     {
         throw ExceptionHelper.GetExceptionFromCOMException(context, exception);
     }
     catch (ActiveDirectoryObjectNotFoundException)
     {
         throw new ActiveDirectoryOperationException(Res.GetString("ADAMInstanceNotFoundInConfigSet", new object[] { context.Name }));
     }
     StringBuilder builder = new StringBuilder(15);
     builder.Append("(&(");
     builder.Append(PropertyManager.ObjectCategory);
     builder.Append("=crossRef)(");
     builder.Append(PropertyManager.SystemFlags);
     builder.Append(":1.2.840.113556.1.4.804:=");
     builder.Append(1);
     builder.Append(")(!(");
     builder.Append(PropertyManager.SystemFlags);
     builder.Append(":1.2.840.113556.1.4.803:=");
     builder.Append(2);
     builder.Append("))(");
     builder.Append(PropertyManager.NCName);
     builder.Append("=");
     builder.Append(Utils.GetEscapedFilterValue(distinguishedName));
     builder.Append("))");
     string filter = builder.ToString();
     string[] propertiesToLoad = new string[] { PropertyManager.DnsRoot, PropertyManager.NCName };
     ADSearcher searcher = new ADSearcher(searchRoot, filter, propertiesToLoad, SearchScope.OneLevel, false, false);
     SearchResult res = null;
     try
     {
         res = searcher.FindOne();
     }
     catch (COMException exception2)
     {
         if (exception2.ErrorCode == -2147016656)
         {
             throw new ActiveDirectoryObjectNotFoundException(Res.GetString("AppNCNotFound"), typeof(ApplicationPartition), distinguishedName);
         }
         throw ExceptionHelper.GetExceptionFromCOMException(context, exception2);
     }
     finally
     {
         searchRoot.Dispose();
     }
     if (res == null)
     {
         throw new ActiveDirectoryObjectNotFoundException(Res.GetString("AppNCNotFound"), typeof(ApplicationPartition), distinguishedName);
     }
     string domainName = null;
     try
     {
         domainName = (res.Properties[PropertyManager.DnsRoot].Count > 0) ? ((string) res.Properties[PropertyManager.DnsRoot][0]) : null;
     }
     catch (COMException exception3)
     {
         throw ExceptionHelper.GetExceptionFromCOMException(context, exception3);
     }
     ApplicationPartitionType applicationPartitionType = GetApplicationPartitionType(context);
     if (context.ContextType != DirectoryContextType.DirectoryServer)
     {
         if (applicationPartitionType == ApplicationPartitionType.ADApplicationPartition)
         {
             DomainControllerInfo info;
             int errorCode = 0;
             errorCode = Locator.DsGetDcNameWrapper(null, domainName, null, 0x8000L, out info);
             if (errorCode == 0x54b)
             {
                 throw new ActiveDirectoryObjectNotFoundException(Res.GetString("AppNCNotFound"), typeof(ApplicationPartition), distinguishedName);
             }
             if (errorCode != 0)
             {
                 throw ExceptionHelper.GetExceptionFromErrorCode(errorCode);
             }
             context2 = Utils.GetNewDirectoryContext(info.DomainControllerName.Substring(2), DirectoryContextType.DirectoryServer, context);
         }
         else
         {
             context2 = Utils.GetNewDirectoryContext(ConfigurationSet.FindOneAdamInstance(context.Name, context, distinguishedName, null).Name, DirectoryContextType.DirectoryServer, context);
         }
         goto Label_03FC;
     }
     bool flag = false;
     DistinguishedName dn = new DistinguishedName(distinguishedName);
     DirectoryEntry directoryEntry = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE);
     try
     {
         foreach (string str3 in directoryEntry.Properties[PropertyManager.NamingContexts])
         {
             DistinguishedName name2 = new DistinguishedName(str3);
             if (name2.Equals(dn))
             {
                 flag = true;
                 goto Label_0352;
             }
         }
     }
     catch (COMException exception4)
     {
         throw ExceptionHelper.GetExceptionFromCOMException(context, exception4);
     }
     finally
     {
         directoryEntry.Dispose();
     }
 Label_0352:
     if (!flag)
     {
         throw new ActiveDirectoryObjectNotFoundException(Res.GetString("AppNCNotFound"), typeof(ApplicationPartition), distinguishedName);
     }
     context2 = context;
 Label_03FC:
     return new ApplicationPartition(context2, (string) PropertyManager.GetSearchResultPropertyValue(res, PropertyManager.NCName), domainName, applicationPartitionType, directoryEntryMgr);
 }
        public static ApplicationPartition FindByName(DirectoryContext context, string distinguishedName)
        {
            DirectoryEntryManager directoryEntryMgr = null;
            DirectoryContext      context2          = null;

            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if ((context.Name == null) && !context.isRootDomain())
            {
                throw new ArgumentException(Res.GetString("ContextNotAssociatedWithDomain"), "context");
            }
            if (((context.Name != null) && !context.isRootDomain()) && (!context.isADAMConfigSet() && !context.isServer()))
            {
                throw new ArgumentException(Res.GetString("NotADOrADAM"), "context");
            }
            if (distinguishedName == null)
            {
                throw new ArgumentNullException("distinguishedName");
            }
            if (distinguishedName.Length == 0)
            {
                throw new ArgumentException(Res.GetString("EmptyStringParameter"), "distinguishedName");
            }
            if (!Utils.IsValidDNFormat(distinguishedName))
            {
                throw new ArgumentException(Res.GetString("InvalidDNFormat"), "distinguishedName");
            }
            context           = new DirectoryContext(context);
            directoryEntryMgr = new DirectoryEntryManager(context);
            DirectoryEntry searchRoot = null;

            try
            {
                searchRoot = DirectoryEntryManager.GetDirectoryEntry(context, directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.PartitionsContainer));
            }
            catch (COMException exception)
            {
                throw ExceptionHelper.GetExceptionFromCOMException(context, exception);
            }
            catch (ActiveDirectoryObjectNotFoundException)
            {
                throw new ActiveDirectoryOperationException(Res.GetString("ADAMInstanceNotFoundInConfigSet", new object[] { context.Name }));
            }
            StringBuilder builder = new StringBuilder(15);

            builder.Append("(&(");
            builder.Append(PropertyManager.ObjectCategory);
            builder.Append("=crossRef)(");
            builder.Append(PropertyManager.SystemFlags);
            builder.Append(":1.2.840.113556.1.4.804:=");
            builder.Append(1);
            builder.Append(")(!(");
            builder.Append(PropertyManager.SystemFlags);
            builder.Append(":1.2.840.113556.1.4.803:=");
            builder.Append(2);
            builder.Append("))(");
            builder.Append(PropertyManager.NCName);
            builder.Append("=");
            builder.Append(Utils.GetEscapedFilterValue(distinguishedName));
            builder.Append("))");
            string filter = builder.ToString();

            string[]     propertiesToLoad = new string[] { PropertyManager.DnsRoot, PropertyManager.NCName };
            ADSearcher   searcher         = new ADSearcher(searchRoot, filter, propertiesToLoad, SearchScope.OneLevel, false, false);
            SearchResult res = null;

            try
            {
                res = searcher.FindOne();
            }
            catch (COMException exception2)
            {
                if (exception2.ErrorCode == -2147016656)
                {
                    throw new ActiveDirectoryObjectNotFoundException(Res.GetString("AppNCNotFound"), typeof(ApplicationPartition), distinguishedName);
                }
                throw ExceptionHelper.GetExceptionFromCOMException(context, exception2);
            }
            finally
            {
                searchRoot.Dispose();
            }
            if (res == null)
            {
                throw new ActiveDirectoryObjectNotFoundException(Res.GetString("AppNCNotFound"), typeof(ApplicationPartition), distinguishedName);
            }
            string domainName = null;

            try
            {
                domainName = (res.Properties[PropertyManager.DnsRoot].Count > 0) ? ((string)res.Properties[PropertyManager.DnsRoot][0]) : null;
            }
            catch (COMException exception3)
            {
                throw ExceptionHelper.GetExceptionFromCOMException(context, exception3);
            }
            ApplicationPartitionType applicationPartitionType = GetApplicationPartitionType(context);

            if (context.ContextType != DirectoryContextType.DirectoryServer)
            {
                if (applicationPartitionType == ApplicationPartitionType.ADApplicationPartition)
                {
                    DomainControllerInfo info;
                    int errorCode = 0;
                    errorCode = Locator.DsGetDcNameWrapper(null, domainName, null, 0x8000L, out info);
                    if (errorCode == 0x54b)
                    {
                        throw new ActiveDirectoryObjectNotFoundException(Res.GetString("AppNCNotFound"), typeof(ApplicationPartition), distinguishedName);
                    }
                    if (errorCode != 0)
                    {
                        throw ExceptionHelper.GetExceptionFromErrorCode(errorCode);
                    }
                    context2 = Utils.GetNewDirectoryContext(info.DomainControllerName.Substring(2), DirectoryContextType.DirectoryServer, context);
                }
                else
                {
                    context2 = Utils.GetNewDirectoryContext(ConfigurationSet.FindOneAdamInstance(context.Name, context, distinguishedName, null).Name, DirectoryContextType.DirectoryServer, context);
                }
                goto Label_03FC;
            }
            bool flag                        = false;
            DistinguishedName dn             = new DistinguishedName(distinguishedName);
            DirectoryEntry    directoryEntry = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE);

            try
            {
                foreach (string str3 in directoryEntry.Properties[PropertyManager.NamingContexts])
                {
                    DistinguishedName name2 = new DistinguishedName(str3);
                    if (name2.Equals(dn))
                    {
                        flag = true;
                        goto Label_0352;
                    }
                }
            }
            catch (COMException exception4)
            {
                throw ExceptionHelper.GetExceptionFromCOMException(context, exception4);
            }
            finally
            {
                directoryEntry.Dispose();
            }
Label_0352:
            if (!flag)
            {
                throw new ActiveDirectoryObjectNotFoundException(Res.GetString("AppNCNotFound"), typeof(ApplicationPartition), distinguishedName);
            }
            context2 = context;
Label_03FC:
            return(new ApplicationPartition(context2, (string)PropertyManager.GetSearchResultPropertyValue(res, PropertyManager.NCName), domainName, applicationPartitionType, directoryEntryMgr));
        }