示例#1
0
        public IIsSite(DirectoryEntry SiteEntry, DirectoryEntry RootEntry)
        {
            if (SiteEntry.SchemaClassName == IIsHelper.SiteSchemaClassName & RootEntry.SchemaClassName == IIsHelper.VirtualDirectorySchemaClassName)
            {

                _SiteEntry = SiteEntry;
                _SiteEntry.RefreshCache();

                _RootEntry = RootEntry;
                _RootEntry.RefreshCache();
            }

            else
            {

                if (SiteEntry.SchemaClassName != IIsHelper.SiteSchemaClassName)
                {

                    IIsHelper.ConstructorEx(IIsHelper.SiteSchemaClassName);

                }

                if (RootEntry.SchemaClassName != IIsHelper.VirtualDirectorySchemaClassName)
                {

                    IIsHelper.ConstructorEx(IIsHelper.VirtualDirectorySchemaClassName);

                }

            }
        }
示例#2
0
        public static object GetProperty(string PropertyName, DirectoryEntry DirEntry)
        {
            try
            {

                DirEntry.RefreshCache();

                if ((DirEntry.Properties[PropertyName].Value != null))
                {

                    return DirEntry.Properties[PropertyName].Value;
                }

                else
                {

                    return null;

                }
            }

            catch (Exception ex)
            {

                GetPropertyEx(PropertyName, ex);
                return null;

            }
        }
示例#3
0
        /// <summary>
        /// 取用户所对应的用户组
        /// </summary>
        /// <param name="userName">用户名称</param>
        /// <param name="domain">域</param>
        /// <param name="adusername">登陆用户</param>
        /// <param name="adpassword">登陆密码</param>
        /// <returns></returns>
        public static List<string> GetADGroups(string userName,string domain,string adusername,string adpassword)
        {
            List<string> groups = new List<string>();
            try
            {
                var entry = new DirectoryEntry(string.Format("LDAP://{0}", domain), adusername, adpassword);
                entry.RefreshCache();

                DirectorySearcher search = new DirectorySearcher(entry);
                search.PropertiesToLoad.Add("memberof");
                search.Filter = string.Format("sAMAccountName={0}", userName);
                SearchResult result = search.FindOne();

                if (result != null)
                {
                    ResultPropertyValueCollection c = result.Properties["memberof"];
                    foreach (var a in c)
                    {
                        string temp = a.ToString();
                        Match match = Regex.Match(temp, @"CN=\s*(?<g>\w*)\s*.");
                        groups.Add(match.Groups["g"].Value);
                    }
                }
            }
            catch
            {

            }
            return groups;
        }
示例#4
0
        public IIsService()
        {
            String ServiceName = FirstServiceName();
            String AppPoolsName = FirstAppPoolsName();

            if (ServiceName == string.Empty)
            {

                throw new Exception("No IIS Web Service Metabase entry found on this machine.");
            }

            else
            {

                _ServiceEntry = new DirectoryEntry(IIsHelper.IIsProviderPath + "/" + ServiceName);
                _ServiceEntry.RefreshCache();

            }

            if (AppPoolsName == string.Empty)
            {

                throw new Exception("No Application Pools Metabase entry found on this machine.");
            }

            else
            {

                _ApplicationPoolsEntry = new DirectoryEntry(IIsHelper.IIsProviderPath + "/" + ServiceName + "/" + AppPoolsName);
                _ApplicationPoolsEntry.RefreshCache();

            }
        }
示例#5
0
 public static bool ValidateUserThroughAD(string empNo, string password)
 {
     string msg = string.Empty;
     try
     {
         const string ldapPath = "LDAP://192.168.1.1/CN=glpi,CN=users,DC=powergrid,DC=net";
         var userIo = new DirectoryEntry(ldapPath);
         if (IsUserInAD(empNo, ldapPath, userIo, password))
         {
             userIo.Username = empNo;
             userIo.Password = password;
             userIo.RefreshCache();
             msg = "VALIDATED";
         }
         else
         {
             msg = "VALIDATED";
         }
     }
     catch (Exception)
     {
         msg = "WRONG";
     }
     return msg == "VALIDATED";
 }
示例#6
0
        /// <summary>
        /// populate all active directory groups in to list box
        /// </summary>
        private void LoadADGroups()
        {
            using (var context = new PrincipalContext(ContextType.Domain, Form1._Domain, Form1._AdminUser, Form1._Password))
            {
                DirectoryEntry objADAM = default(DirectoryEntry);
                DirectoryEntry objGroupEntry = default(DirectoryEntry);
                DirectorySearcher objSearchADAM = default(DirectorySearcher);
                SearchResultCollection objSearchResults = default(SearchResultCollection);
                string strPath = null;
                List<string> result = new List<string>();

                strPath = "LDAP://" + Form1._Domain;

                try
                {
                    objADAM = new DirectoryEntry(strPath, Form1._AdminUser, Form1._Password);
                    objADAM.RefreshCache();
                }
                catch (Exception ex)
                {
                    Form1.myForm.lblMessage.Text = ex.Message;
                    Form1.myForm.lblMessage.Show();
                }

                try
                {
                    objSearchADAM = new DirectorySearcher(objADAM);
                    objSearchADAM.Filter = "(&(objectClass=group))";
                    objSearchADAM.SearchScope = SearchScope.Subtree;
                    objSearchResults = objSearchADAM.FindAll();
                }
                catch (Exception)
                {
                    throw;
                }

                try
                {
                    if (objSearchResults.Count != 0)
                    {
                        foreach (SearchResult objResult in objSearchResults)
                        {
                            objGroupEntry = objResult.GetDirectoryEntry();
                            result.Add(objGroupEntry.Name.Replace("CN=",""));
                        }
                        Form1.myForm.lbGroups.DataSource = result;
                        Form1.myForm.lbGroups.SelectedIndex = -1;
                        Form1.myForm.lbUpdateADGroups.DataSource = result;
                        Form1.myForm.lbUpdateADGroups.SelectedIndex = -1;
                    }
                }
                catch (Exception ex)
                {
                    Form1.myForm.lblMessage.Text = ex.Message;
                    Form1.myForm.lblMessage.Show();
                }
            }
        }
示例#7
0
        public static IList<string> GetIis6AppPools()
        {
            List<string> pools = new List<string>();
            using (DirectoryEntry poolRoot = new DirectoryEntry("IIS://localhost/W3SVC/AppPools"))
            {
                poolRoot.RefreshCache();

                pools.AddRange(poolRoot.Children.Cast<DirectoryEntry>().Select(p => p.Name));
            }

            return pools;
        }
示例#8
0
		public IList<string> GetAppPools()
		{
			var pools = new List<string>();
			using (var poolRoot = new DirectoryEntry(ApplicationPoolsEntry))
			{
				poolRoot.RefreshCache();

				pools.AddRange(poolRoot.Children.Cast<DirectoryEntry>().Select(p => p.Name));
			}

			return pools;
		}
示例#9
0
        public IIsFile(DirectoryEntry FileEntry)
        {
            if (FileEntry.SchemaClassName == IIsHelper.FileSchemaClassName)
            {

                _FileEntry = FileEntry;
                _FileEntry.RefreshCache();
            }
            else
            {
                IIsHelper.ConstructorEx(IIsHelper.FileSchemaClassName);
            }
        }
示例#10
0
        public static IList<IisWebSite> GetIis6Sites()
        {
            List<IisWebSite> sites = new List<IisWebSite>();
            using (DirectoryEntry iisRoot = new DirectoryEntry("IIS://localhost/W3SVC"))
            {
                iisRoot.RefreshCache();

                sites.AddRange(iisRoot.Children.Cast<DirectoryEntry>().
                    Where(w => w.SchemaClassName.ToLower(CultureInfo.InvariantCulture) == "iiswebserver").
                    Select(w => new IisWebSite(w.Name, w.Properties["ServerComment"].Value.ToString())));
            }

            return sites;
        }
示例#11
0
 /// <summary>
 /// 验证AD用户是否登陆成功
 /// </summary>
 /// <param name="domain">域名称</param>
 /// <param name="username">用户名</param>
 /// <param name="password">密码</param>
 /// <returns>返回登陆状态</returns>
 public static bool TryAuthenticate(string domain, string username, string password)
 {
     bool isLogin = false;
     try
     {
         DirectoryEntry entry = new DirectoryEntry(string.Format("LDAP://{0}", domain), username, password);
         entry.RefreshCache();
         isLogin = true;
     }
     catch
     {
         isLogin = false;
     }
     return isLogin;
 }
示例#12
0
 /// <summary>
 /// 验证AD用户是否登陆成功
 /// </summary>
 /// <param name="domain">域名称</param>
 /// <param name="username">用户名</param>
 /// <param name="password">密码</param>
 /// <returns>返回登陆状态</returns>
 public bool TryAuthenticate(string Account, string Password)
 {
     bool isLogin = false;
     try
     {
         DirectoryEntry entry = new DirectoryEntry(LDAPPath + Domain, Account, Password);
         entry.RefreshCache();
         isLogin = true;
     }
     catch
     {
         isLogin = false;
     }
     return isLogin;
 }
示例#13
0
        public ADDirectoryEntry RetrieveDirectoryEntry(string DistinguishedName, string[] LoadProperties = null)
        {
            if (string.IsNullOrWhiteSpace(DistinguishedName))
                throw new ArgumentNullException("DistinguishedName");

            if (!DistinguishedName.EndsWith(this.Domain.DistinguishedName, StringComparison.OrdinalIgnoreCase))
                throw new ArgumentException(string.Format("The Distinguished Name ({0}) isn't a member of this domain [{1}]", DistinguishedName, this.Domain.Name), "DistinguishedName");

            var entry = new DirectoryEntry(string.Format(LdapPathTemplate, this.Name, ADHelpers.EscapeDistinguishedName(DistinguishedName)));

            if (LoadProperties != null)
                entry.RefreshCache(LoadProperties);

            return new ADDirectoryEntry(this.Domain, this, entry);
        }
示例#14
0
        public static string DelSite(int siteidon)
        {
            int SiteID = siteidon;
            //if (SiteID == null) return "error:该站点不存在!!";

            DirectoryEntry deRoot = new DirectoryEntry("IIS://localhost/W3SVC");

            DirectoryEntry deVDir = new DirectoryEntry();
            deRoot.RefreshCache();
            deVDir = deRoot.Children.Find("huke8huke", "IIsVirtualDir");
            deRoot.Children.Remove(deVDir);
            //deVDir.Invoke("AppDelete",true);
            deRoot.CommitChanges();
            deRoot.Close();
            return "successful:删除站点成功!";
        }
示例#15
0
        public IIsDirectory(DirectoryEntry DirEntry)
        {
            if (DirEntry.SchemaClassName == IIsHelper.DirectorySchemaClassName)
            {

                _DirectoryEntry = DirEntry;
                _DirectoryEntry.RefreshCache();
            }

            else
            {

                IIsHelper.ConstructorEx(IIsHelper.DirectorySchemaClassName);

            }
        }
示例#16
0
        public IIsApplicationPool(DirectoryEntry ApplicationPoolEntry)
        {
            if (ApplicationPoolEntry.SchemaClassName == IIsHelper.ApplicationPoolSchemaClassName)
            {

                _ApplicationPoolEntry = ApplicationPoolEntry;
                _ApplicationPoolEntry.RefreshCache();
            }

            else
            {

                IIsHelper.ConstructorEx(IIsHelper.ApplicationPoolSchemaClassName);

            }
        }
示例#17
0
        public IIsVirtualDirectory(DirectoryEntry VirtualDirEntry)
        {
            if (VirtualDirEntry.SchemaClassName == IIsHelper.VirtualDirectorySchemaClassName)
            {

                _VirtualDirEntry = VirtualDirEntry;
                _VirtualDirEntry.RefreshCache();
            }

            else
            {

                IIsHelper.ConstructorEx(IIsHelper.VirtualDirectorySchemaClassName);

            }
        }
 private static DirectoryEntry GetDirectoryEntry()
 {
     if (directoryEntry == null)
     {
         lock (typeLock)
         {
             if (directoryEntry == null)
             {
                 DirectoryEntry entry = new DirectoryEntry("LDAP://" + System.ServiceModel.Security.SecurityUtils.GetPrimaryDomain());
                 entry.RefreshCache(new string[] { "name" });
                 Thread.MemoryBarrier();
                 directoryEntry = entry;
             }
         }
     }
     return directoryEntry;
 }
示例#19
0
文件: LDAP.cs 项目: tangck/RTXLDAP
        public static bool connect(string domainName, string userName, string userPwd, out DirectoryEntry domain)
        {
            domain = new DirectoryEntry();
            try
            {
                domain.Path = string.Format("LDAP://{0}", domainName);
                domain.Username = userName;
                domain.Password = userPwd;
                domain.AuthenticationType = AuthenticationTypes.Secure;
                domain.RefreshCache();

                return true;
            }
            catch
            {
                return false;
            }
        }
示例#20
0
        public static String[] GetPropertyA(string PropertyName, DirectoryEntry DirEntry)
        {
            try
            {

                DirEntry.RefreshCache();

                if ((DirEntry.Properties[PropertyName].Value != null))
                {

                    if (DirEntry.Properties[PropertyName].Value.GetType().IsArray)
                    {

                        return (String[])DirEntry.Properties[PropertyName].Value;
                    }

                    else
                    {

                        return new String[] { DirEntry.Properties[PropertyName].Value.ToString() };

                    }
                }

                else
                {

                    return new String[0];

                }
            }

            catch (Exception ex)
            {

                GetPropertyEx(PropertyName, ex);
                return new String[0];

            }
        }
        /// <summary>
        /// Sets the specified property
        /// </summary>
        protected override void ExecuteTask() {
            try {
                // Get the directory entry for the specified path and set the 
                // property.
                using (DirectoryEntry pathRoot = new DirectoryEntry(Path)) {
                    pathRoot.RefreshCache();

                    if (pathRoot.Properties[PropName].Value.GetType().IsArray) {
                        System.Text.StringBuilder sb = new System.Text.StringBuilder();
                        foreach (object propValue in (Array) pathRoot.Properties[PropName].Value) {
                            sb.AppendFormat("{0}" + Environment.NewLine, propValue);
                        }
                        Project.Properties[StoreIn] = sb.ToString();
                    } else {
                        Project.Properties[StoreIn] = pathRoot.Properties[PropName].Value.ToString();
                    }
                }
            } catch (Exception ex) {
                throw new BuildException(string.Format(CultureInfo.InvariantCulture,
                    "Error reading property '{0}'.", PropName), ex);
            }
        }
示例#22
0
        int ConvertSiteNameToSiteNumber(string name)
        {
            var foundWebsites = new List<string>();

            using (var e = new DirectoryEntry("IIS://{0}/W3SVC".FormatWith(ServerName)))
            {
                e.RefreshCache();
                foreach (DirectoryEntry entry in e.Children)
                {
                    if (entry.SchemaClassName != "IIsWebServer")
                    {
                        entry.Close();
                        continue;
                    }

                    foundWebsites.Add(entry.Properties["ServerComment"].Value.ToString());
                    if (!entry.Properties["ServerComment"].Value.Equals(name))
                        continue;


                    var siteNumber = entry.Name;
                    entry.Close();
                    return int.Parse(siteNumber);
                }

            }

            //didn't find anything, gonna hurl now
            var sb = new StringBuilder();
            sb.AppendFormat("Couldn't find the website '{0}'", name);
            sb.AppendLine();
            sb.AppendLine("Found the following web sites:");
            foreach (var site in foundWebsites) sb.AppendFormat("  '{0}'{1}", site, Environment.NewLine);

            throw new Exception(sb.ToString());
        }
示例#23
0
        private bool DeleteAppPool()
        {
            bool bSuccess = false;
            Log.LogMessage(MessageImportance.Normal, "Deleting application pool named {0}/{1}:", IISAppPoolPath, ApplicationPoolName);

            try
            {
                VerifyIISRoot();

                if (mIISVersion == IISVersion.Six)
                {
                    DirectoryEntry appPools = new DirectoryEntry(IISAppPoolPath);
                    appPools.RefreshCache();

                    // Find the application pool
                    DirectoryEntry existingPool = appPools.Children.Find(ApplicationPoolName, "IIsApplicationPool");
                    appPools.Children.Remove(existingPool);
                    appPools.CommitChanges();
                    appPools.Close();

                    bSuccess = true;
                    Log.LogMessage(MessageImportance.Normal, "Done.");
                }
                else
                {
                    Log.LogError("Application Pools are only available in IIS 6.");
                }
            }
            catch (Exception ex)
            {
                Log.LogErrorFromException(ex);
            }

            return bSuccess;
        }
        protected override void ExecuteTask() {
            Log(Level.Info, "Retrieving settings of virtual directory '{0}'"
                + " on '{1}' (website: {2}).", this.VirtualDirectory, 
                this.Server, this.Website);

            // ensure IIS is available on specified host and port
            this.CheckIISSettings();

            try {
                DirectoryEntry folderRoot = new DirectoryEntry(this.ServerPath);
                folderRoot.RefreshCache();
                DirectoryEntry newVirDir = folderRoot.Children.Find(
                    this.VirtualDirectory, folderRoot.SchemaClassName);

                bool supportsPropertyEnumeration;

                try {
                    supportsPropertyEnumeration = newVirDir.Properties.PropertyNames.Count >= 0;
                } catch {
                    supportsPropertyEnumeration = false;
                }

                // the IIS ADSI provider only supports enumeration of properties
                // on IIS6 (and Windows XP SP2, but well ...) or higher
                if (supportsPropertyEnumeration) {
                    foreach (string propertyName in newVirDir.Properties.PropertyNames) {
                        object propertyValue = newVirDir.Properties[propertyName].Value;

                        if (propertyValue.GetType().IsArray) {
                            Log(Level.Info, propertyName + ":");

                            Array propertyValues = (Array) propertyValue;
                            foreach (object value in propertyValues) {
                                Log(Level.Info, '\t' + value.ToString());
                            }
                        } else {
                            Log(Level.Info, propertyName + ": " 
                                + newVirDir.Properties[propertyName].Value.ToString());
                        }
                    }
                } else {
                    Log(Level.Info, "AccessExecute: " + newVirDir.Properties["AccessExecute"].Value.ToString());
                    Log(Level.Info, "AccessFlags: " + newVirDir.Properties["AccessFlags"].Value.ToString());
                    Log(Level.Info, "AccessNoRemoteExecute: " + newVirDir.Properties["AccessNoRemoteExecute"].Value.ToString());
                    Log(Level.Info, "AccessNoRemoteRead: " + newVirDir.Properties["AccessNoRemoteRead"].Value.ToString());
                    Log(Level.Info, "AccessNoRemoteScript: " + newVirDir.Properties["AccessNoRemoteScript"].Value.ToString());
                    Log(Level.Info, "AccessNoRemoteWrite: " + newVirDir.Properties["AccessNoRemoteWrite"].Value.ToString());
                    Log(Level.Info, "AccessRead: " + newVirDir.Properties["AccessRead"].Value.ToString());
                    Log(Level.Info, "AccessSource: " + newVirDir.Properties["AccessSource"].Value.ToString());
                    Log(Level.Info, "AccessScript: " + newVirDir.Properties["AccessScript"].Value.ToString());
                    Log(Level.Info, "AccessSSL: " + newVirDir.Properties["AccessSSL"].Value.ToString());
                    Log(Level.Info, "AccessSSL128: " + newVirDir.Properties["AccessSSL128"].Value.ToString());
                    Log(Level.Info, "AccessSSLFlags: " + newVirDir.Properties["AccessSSLFlags"].Value.ToString());
                    Log(Level.Info, "AccessSSLMapCert: " + newVirDir.Properties["AccessSSLMapCert"].Value.ToString());
                    Log(Level.Info, "AccessSSLNegotiateCert: " + newVirDir.Properties["AccessSSLNegotiateCert"].Value.ToString());
                    Log(Level.Info, "AccessSSLRequireCert: " + newVirDir.Properties["AccessSSLRequireCert"].Value.ToString());
                    Log(Level.Info, "AccessWrite: " + newVirDir.Properties["AccessWrite"].Value.ToString());
                    Log(Level.Info, "AnonymousPasswordSync: " + newVirDir.Properties["AnonymousPasswordSync"].Value.ToString());
                    Log(Level.Info, "AnonymousUserName: "******"AnonymousUserName"].Value.ToString());
                    Log(Level.Info, "AnonymousUserPass: "******"AnonymousUserPass"].Value.ToString());
                    Log(Level.Info, "AppAllowClientDebug: " + newVirDir.Properties["AppAllowClientDebug"].Value.ToString());
                    Log(Level.Info, "AppAllowDebugging: " + newVirDir.Properties["AppAllowDebugging"].Value.ToString());
                    Log(Level.Info, "AppFriendlyName: " + newVirDir.Properties["AppFriendlyName"].Value.ToString());
                    Log(Level.Info, "AppIsolated: " + newVirDir.Properties["AppIsolated"].Value.ToString());
                    Log(Level.Info, "AppOopRecoverLimit: " + newVirDir.Properties["AppOopRecoverLimit"].Value.ToString());
                    Log(Level.Info, "AppPackageID: " + newVirDir.Properties["AppPackageID"].Value.ToString());
                    Log(Level.Info, "AppPackageName: " + newVirDir.Properties["AppPackageName"].Value.ToString());
                    Log(Level.Info, "AppRoot: " + newVirDir.Properties["AppRoot"].Value.ToString());
                    Log(Level.Info, "AppWamClsID: " + newVirDir.Properties["AppWamClsID"].Value.ToString());
                    Log(Level.Info, "AspAllowOutOfProcComponents: " + newVirDir.Properties["AspAllowOutOfProcComponents"].Value.ToString());
                    Log(Level.Info, "AspAllowSessionState: " + newVirDir.Properties["AspAllowSessionState"].Value.ToString());
                    Log(Level.Info, "AspBufferingOn: " + newVirDir.Properties["AspBufferingOn"].Value.ToString());
                    Log(Level.Info, "AspCodepage: " + newVirDir.Properties["AspCodepage"].Value.ToString());
                    Log(Level.Info, "AspEnableApplicationRestart: " + newVirDir.Properties["AspEnableApplicationRestart"].Value.ToString());
                    Log(Level.Info, "AspEnableAspHtmlFallback: " + newVirDir.Properties["AspEnableAspHtmlFallback"].Value.ToString());
                    Log(Level.Info, "AspEnableChunkedEncoding: " + newVirDir.Properties["AspEnableChunkedEncoding"].Value.ToString());
                    Log(Level.Info, "AspEnableParentPaths: " + newVirDir.Properties["AspEnableParentPaths"].Value.ToString());
                    Log(Level.Info, "AspEnableTypelibCache: " + newVirDir.Properties["AspEnableTypelibCache"].Value.ToString());
                    Log(Level.Info, "AspErrorsToNTLog: " + newVirDir.Properties["AspErrorsToNTLog"].Value.ToString());
                    Log(Level.Info, "AspExceptionCatchEnable: " + newVirDir.Properties["AspExceptionCatchEnable"].Value.ToString());
                    Log(Level.Info, "AspLogErrorRequests: " + newVirDir.Properties["AspLogErrorRequests"].Value.ToString());
                    Log(Level.Info, "AspProcessorThreadMax: " + newVirDir.Properties["AspProcessorThreadMax"].Value.ToString());
                    Log(Level.Info, "AspQueueConnectionTestTime: " + newVirDir.Properties["AspQueueConnectionTestTime"].Value.ToString());
                    Log(Level.Info, "AspQueueTimeout: " + newVirDir.Properties["AspQueueTimeout"].Value.ToString());
                    Log(Level.Info, "AspRequestQueueMax: " + newVirDir.Properties["AspRequestQueueMax"].Value.ToString());
                    Log(Level.Info, "AspScriptEngineCacheMax: " + newVirDir.Properties["AspScriptEngineCacheMax"].Value.ToString());
                    Log(Level.Info, "AspScriptErrorMessage: " + newVirDir.Properties["AspScriptErrorMessage"].Value.ToString());
                    Log(Level.Info, "AspScriptErrorSentToBrowser: " + newVirDir.Properties["AspScriptErrorSentToBrowser"].Value.ToString());
                    Log(Level.Info, "AspScriptFileCacheSize: " + newVirDir.Properties["AspScriptFileCacheSize"].Value.ToString());
                    Log(Level.Info, "AspScriptLanguage: " + newVirDir.Properties["AspScriptLanguage"].Value.ToString());
                    Log(Level.Info, "AspScriptTimeout: " + newVirDir.Properties["AspScriptTimeout"].Value.ToString());
                    Log(Level.Info, "AspSessionMax: " + newVirDir.Properties["AspSessionMax"].Value.ToString());
                    Log(Level.Info, "AspSessionTimeout: " + newVirDir.Properties["AspSessionTimeout"].Value.ToString());
                    Log(Level.Info, "AuthAnonymous: " + newVirDir.Properties["AuthAnonymous"].Value.ToString());
                    Log(Level.Info, "AuthBasic: " + newVirDir.Properties["AuthBasic"].Value.ToString());
                    Log(Level.Info, "AuthFlags: " + newVirDir.Properties["AuthFlags"].Value.ToString());
                    Log(Level.Info, "AuthNTLM: " + newVirDir.Properties["AuthNTLM"].Value.ToString());
                    Log(Level.Info, "AuthPersistSingleRequest: " + newVirDir.Properties["AuthPersistSingleRequest"].Value.ToString());
                    Log(Level.Info, "AuthPersistence: " + newVirDir.Properties["AuthPersistence"].Value.ToString());				
                    Log(Level.Info, "CacheControlCustom: " + newVirDir.Properties["CacheControlCustom"].Value.ToString());
                    Log(Level.Info, "CacheControlMaxAge: " + newVirDir.Properties["CacheControlMaxAge"].Value.ToString());
                    Log(Level.Info, "CacheControlNoCache: " + newVirDir.Properties["CacheControlNoCache"].Value.ToString());
                    Log(Level.Info, "CacheISAPI: " + newVirDir.Properties["CacheISAPI"].Value.ToString());
                    Log(Level.Info, "ContentIndexed: " + newVirDir.Properties["ContentIndexed"].Value.ToString());				
                    Log(Level.Info, "CreateCGIWithNewConsole: " + newVirDir.Properties["CreateCGIWithNewConsole"].Value.ToString());
                    Log(Level.Info, "CreateProcessAsUser: "******"CreateProcessAsUser"].Value.ToString());
                    Log(Level.Info, "DefaultDoc: " + newVirDir.Properties["DefaultDoc"].Value.ToString());
                    Log(Level.Info, "DefaultDocFooter: " + newVirDir.Properties["DefaultDocFooter"].Value.ToString());
                    Log(Level.Info, "DefaultLogonDomain: " + newVirDir.Properties["DefaultLogonDomain"].Value.ToString());
                    Log(Level.Info, "DirBrowseFlags: " + newVirDir.Properties["DirBrowseFlags"].Value.ToString());
                    Log(Level.Info, "DirBrowseShowDate: " + newVirDir.Properties["DirBrowseShowDate"].Value.ToString());
                    Log(Level.Info, "DirBrowseShowExtension: " + newVirDir.Properties["DirBrowseShowExtension"].Value.ToString());
                    Log(Level.Info, "DirBrowseShowLongDate: " + newVirDir.Properties["DirBrowseShowLongDate"].Value.ToString());
                    Log(Level.Info, "DirBrowseShowSize: " + newVirDir.Properties["DirBrowseShowSize"].Value.ToString());
                    Log(Level.Info, "DirBrowseShowTime: " + newVirDir.Properties["DirBrowseShowTime"].Value.ToString());
                    Log(Level.Info, "DontLog: " + newVirDir.Properties["DontLog"].Value.ToString());
                    Log(Level.Info, "EnableDefaultDoc: " + newVirDir.Properties["EnableDefaultDoc"].Value.ToString());
                    Log(Level.Info, "EnableDirBrowsing: " + newVirDir.Properties["EnableDirBrowsing"].Value.ToString());
                    Log(Level.Info, "EnableDocFooter: " + newVirDir.Properties["EnableDocFooter"].Value.ToString());
                    Log(Level.Info, "EnableReverseDns: " + newVirDir.Properties["EnableReverseDns"].Value.ToString());
                    Log(Level.Info, "HttpExpires: " + newVirDir.Properties["HttpExpires"].Value.ToString());
                    Log(Level.Info, "HttpRedirect: " + newVirDir.Properties["HttpRedirect"].Value.ToString());
                    Log(Level.Info, "LogonMethod: " + newVirDir.Properties["LogonMethod"].Value.ToString());
                    Log(Level.Info, "Path: " + newVirDir.Properties["Path"].Value.ToString());				
                    Log(Level.Info, "Realm: " + newVirDir.Properties["Realm"].Value.ToString());
                    Log(Level.Info, "UNCPassword: "******"UNCPassword"].Value.ToString());
                    Log(Level.Info, "UNCUserName: "******"UNCUserName"].Value.ToString());
                    Log(Level.Info, "UploadReadAheadSize: " + newVirDir.Properties["UploadReadAheadSize"].Value.ToString());
                    Log(Level.Info, "AspTrackThreadingModel: " + newVirDir.Properties["AspTrackThreadingModel"].Value.ToString());
                    Log(Level.Info, "AuthPersistSingleRequestIfProxy: " + newVirDir.Properties["AuthPersistSingleRequestIfProxy"].Value.ToString());
                    Log(Level.Info, "AuthPersistSingleRequestAlwaysIfProxy: " + newVirDir.Properties["AuthPersistSingleRequestAlwaysIfProxy"].Value.ToString());
                    Log(Level.Info, "PoolIDCTimeout: " + newVirDir.Properties["PoolIDCTimeout"].Value.ToString());
                    Log(Level.Info, "PutReadSize: " + newVirDir.Properties["PutReadSize"].Value.ToString());
                    Log(Level.Info, "RedirectHeaders: " + newVirDir.Properties["RedirectHeaders"].Value.ToString());
                    Log(Level.Info, "SSIExecDisable: " + newVirDir.Properties["SSIExecDisable"].Value.ToString());
                    Log(Level.Info, "UNCAuthenticationPassthrough: " + newVirDir.Properties["UNCAuthenticationPassthrough"].Value.ToString());
                    
                    // these seem to cause problems on Windows XP SP2

                    /*
                    Log(Level.Info, "AspThreadGateEnabled: " + newVirDir.Properties["AspThreadGateEnabled"].Value.ToString());
                    Log(Level.Info, "AspThreadGateLoadHigh: " + newVirDir.Properties["AspThreadGateLoadHigh"].Value.ToString());
                    Log(Level.Info, "AspThreadGateLoadLow: " + newVirDir.Properties["AspThreadGateLoadLow"].Value.ToString());
                    Log(Level.Info, "AspThreadGateSleepDelay: " + newVirDir.Properties["AspThreadGateSleepDelay"].Value.ToString());
                    Log(Level.Info, "AspThreadGateSleepMax: " + newVirDir.Properties["AspThreadGateSleepMax"].Value.ToString());
                    Log(Level.Info, "AspThreadGateTimeSlice: " + newVirDir.Properties["AspThreadGateTimeSlice"].Value.ToString());
                    Log(Level.Info, "CpuAppEnabled: " + newVirDir.Properties["CpuAppEnabled"].Value.ToString());
                    Log(Level.Info, "CpuCgiEnabled: " + newVirDir.Properties["CpuCgiEnabled"].Value.ToString());
                    */
                }

                newVirDir.Close();
                folderRoot.Close();
            } catch (BuildException) {
                // re-throw exception
                throw;
            } catch (Exception ex) {
                throw new BuildException(string.Format(CultureInfo.InvariantCulture,
                    "Error retrieving info for virtual directory '{0}' on '{1}' (website: {2}).", 
                    this.VirtualDirectory, this.Server, this.Website), Location, ex);
            }
        }
		public void DirectoryEntry_RefreshCache_StrArr()
		{			
			de = new DirectoryEntry(configuration.ServerRoot + "cn=Uzi Cohen,cn=Manager" + ((configuration.BaseDn.Length == 0) ? String.Empty : ("," + configuration.BaseDn)));
			de.UsePropertyCache = true;
			
			string[] newValues = new string [] { "Just a manager", "Levi" };
			string[] oldValues = new string [2];
			oldValues [0] = (string)((PropertyValueCollection)de.Properties["description"]).Value;
			oldValues [1] = (string)((PropertyValueCollection)de.Properties["sn"]).Value;
			
			((PropertyValueCollection)de.Properties["description"]).Value = newValues [0];
			((PropertyValueCollection)de.Properties["sn"]).Value = newValues [1];
			
			Assert.AreEqual(((PropertyValueCollection)de.Properties["description"]).Value,newValues [0]);
			Assert.AreEqual(((PropertyValueCollection)de.Properties["sn"]).Value,newValues [1]);

			de.RefreshCache(new string[] {"cn"});

			Assert.AreEqual(((PropertyValueCollection)de.Properties["description"]).Value,newValues [0]);
			Assert.AreEqual(((PropertyValueCollection)de.Properties["sn"]).Value,newValues [1]);

			de.RefreshCache(new string[] {"description","sn"});

			Assert.AreEqual(((PropertyValueCollection)de.Properties["description"]).Value,newValues [0]);
			Assert.AreEqual(((PropertyValueCollection)de.Properties["sn"]).Value,oldValues [1]);	
		}
		public void DirectoryEntry_RefreshCache()
		{
			de = new DirectoryEntry(configuration.ConnectionString);
			de.UsePropertyCache = true;
			
			string newValue = "Just a company";
			string oldValue = (string)((PropertyValueCollection)de.Properties["description"]).Value;
			((PropertyValueCollection)de.Properties["description"]).Value = newValue;
			
			Assert.AreEqual(((PropertyValueCollection)de.Properties["description"]).Value,newValue);

			de.RefreshCache();

			Assert.AreEqual(((PropertyValueCollection)de.Properties["description"]).Value,oldValue);
			
			// call RefeshCache on new entry prior to submitting it to the server shoud fail
			string newEmployeeDN = configuration.ServerRoot + "cn=New Employee,ou=Human Resources,ou=people" + ((configuration.BaseDn.Length == 0) ? String.Empty : ("," + configuration.BaseDn));
			string humanResourcesDN = configuration.ServerRoot + "ou=Human Resources,ou=people" + ((configuration.BaseDn.Length == 0) ? String.Empty : ("," + configuration.BaseDn));

			using (DirectoryEntry humanResourcesDE = new DirectoryEntry(	humanResourcesDN,
																	configuration.Username,
																	configuration.Password,
																	configuration.AuthenticationType)){

			using (DirectoryEntry newEmployeeDE = humanResourcesDE.Children.Add("cn=New Employee","Class")){
			Assert.AreEqual(newEmployeeDE.Properties["cn"].Value,null);

			((PropertyValueCollection)newEmployeeDE.Properties["objectClass"]).Add("person");
			((PropertyValueCollection)newEmployeeDE.Properties["objectClass"]).Add("organizationalPerson");
			newEmployeeDE.Properties["cn"].Value = "New Employee";
			newEmployeeDE.Properties["sn"].Value = "Employee";
			newEmployeeDE.Properties["ou"].Value = "Human Resources";

			Assert.AreEqual(newEmployeeDE.Properties["cn"].Value,"New Employee");

			try {
				newEmployeeDE.RefreshCache();
				Assert.Fail("Call to RefreshCache did not fail");
			}
			catch(AssertionException ae) {
				throw ae;
			}
			catch (Exception e) {
				// supress exception
			}

			Assert.AreEqual(newEmployeeDE.Properties["cn"].Value,"New Employee");

			newEmployeeDE.CommitChanges();

			// now it should work without any problem
			newEmployeeDE.RefreshCache();

			Assert.AreEqual(newEmployeeDE.Properties["cn"].Value,"New Employee");
			}
			}
		}
		public void DirectoryEntry_Properties2()
		{
			// delete entry, create a new one (the same) and access properties of the old object
			string barakTsabariDN = configuration.ServerRoot + "cn=Barak Tsabari,ou=Human Resources,ou=people" + ((configuration.BaseDn.Length == 0) ? String.Empty : ("," + configuration.BaseDn));
			de = new DirectoryEntry(barakTsabariDN,
									configuration.Username,
									configuration.Password,
									configuration.AuthenticationType);

			// cause to properties loading
			Assert.AreEqual(de.Properties.Count,6);
			Assert.AreEqual(((PropertyValueCollection)de.Properties["sn"]).Value,"Tsabari");

			// delete entry
			de.DeleteTree();

			// the local property chache is still accessible
			Assert.AreEqual(de.Properties.Count,6);
			Assert.AreEqual(((PropertyValueCollection)de.Properties["sn"]).Value,"Tsabari");

			de.CommitChanges();

			// the local property chache is still accessible
			((PropertyValueCollection)de.Properties["sn"]).Value = "Barbari";

			// create the entry back again
			using (DirectoryEntry ouHumanResources = new DirectoryEntry(	configuration.ServerRoot + "ou=Human Resources,ou=people" + ((configuration.BaseDn.Length == 0) ? String.Empty : ("," + configuration.BaseDn)),
																	configuration.Username,
																	configuration.Password,
																	configuration.AuthenticationType)){
			using (DirectoryEntry cnBarakTsabari = ouHumanResources.Children.Add("cn=Barak Tsabari","Class")){
			((PropertyValueCollection)cnBarakTsabari.Properties["objectClass"]).Add("person");
			((PropertyValueCollection)cnBarakTsabari.Properties["objectClass"]).Add("organizationalPerson");
			cnBarakTsabari.Properties["cn"].Value = "Barak Tsabari";
			cnBarakTsabari.Properties["facsimileTelephoneNumber"].Value = "+1 906 777 8853";
			((PropertyValueCollection)cnBarakTsabari.Properties["ou"]).Add("Human Resources");
			((PropertyValueCollection)cnBarakTsabari.Properties["ou"]).Add("People");
			cnBarakTsabari.Properties["sn"].Value = "Tsabari";
			cnBarakTsabari.Properties["telephoneNumber"].Value = "+1 906 777 8854";
			cnBarakTsabari.CommitChanges();
			}
			}
			
			// the local property chache is still accessible
			Assert.AreEqual(((PropertyValueCollection)de.Properties["sn"]).Value,"Barbari");

			// Refresh from server
			de.RefreshCache();
			// ensure the properties of an entry are still accessible through the old object
			Assert.AreEqual(((PropertyValueCollection)de.Properties["sn"]).Value,"Tsabari");

		}
示例#28
0
        public static void CheckProperties(DirectoryEntry dirEnt)
        {
            dirEnt.Properties["DefaultDoc"].Value = SiteInfo.Current.DefaultDoc;//默认文档
            dirEnt.Properties["AccessFlags"][0] = 513;
            dirEnt.Properties["AuthFlags"][0] = 1;
            string ScriptMaps = ".aspx," + System.Environment.GetFolderPath(System.Environment.SpecialFolder.System).ToUpper().Replace("SYSTEM32", "") + @"Microsoft.net\Framework\v2.0.50727\aspnet_isapi.dll,1,GET,HEAD,POST,DEBUG";
            if (!dirEnt.Properties["ScriptMaps"].Contains(ScriptMaps))
                dirEnt.Properties["ScriptMaps"][0] = ScriptMaps;
            dirEnt.CommitChanges();
            dirEnt.RefreshCache();

        }
示例#29
0
 static void PopulateExtensionAttributes(Ol.Recipient recipient, Contact contact, string LDAPpath)
 {
     try
     {
         string legacyExchangeDN = recipient.Address;
         if (!string.IsNullOrEmpty(LDAPpath))
             using (var dir = new DirectoryEntry(LDAPpath))
             {
                 dir.RefreshCache();
                 var adSearch = new DirectorySearcher(dir)
                 {
                     Filter = string.Format("(&(objectClass=user)(legacyExchangeDN={0}))", legacyExchangeDN)
                 };
                 SearchResult result = adSearch.FindOne();
                 contact.ExtensionAttribute3 = GetActiveDirectoryProperty(result, "extensionAttribute3").Trim((char)10, (char)13);
                 contact.ExtensionAttribute4 = GetActiveDirectoryProperty(result, "extensionAttribute4").Trim((char)10, (char)13);
             }
     }
     catch (Exception ex)
     {
         Message.LogError(ex);
     }
 }
示例#30
0
文件: Context.cs 项目: chcosta/corefx
        private void DoMachineInit()
        {
            GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalContext", "Entering DoMachineInit");

            Debug.Assert(_contextType == ContextType.Machine);
            Debug.Assert(_container == null);

            DirectoryEntry de = null;

            try
            {
                string hostname = _name;

                if (hostname == null)
                    hostname = Utils.GetComputerFlatName();

                GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalContext", "DoMachineInit: hostname is " + hostname);

                // use the options they specified
                AuthenticationTypes authTypes = SDSUtils.MapOptionsToAuthTypes(_options);

                GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalContext", "DoMachineInit: authTypes is " + authTypes.ToString());

                de = new DirectoryEntry("WinNT://" + hostname + ",computer", _username, _password, authTypes);

                // Force ADSI to connect so we detect if the server is down or if the servername is invalid
                de.RefreshCache();

                StoreCtx storeCtx = CreateContextFromDirectoryEntry(de);

                _queryCtx = storeCtx;
                _userCtx = storeCtx;
                _groupCtx = storeCtx;
                _computerCtx = storeCtx;

                _connectedServer = hostname;
                de = null;
            }
            catch (Exception e)
            {
                GlobalDebug.WriteLineIf(GlobalDebug.Error,
                                                  "PrincipalContext",
                                                  "DoMachineInit: caught exception of type "
                                                   + e.GetType().ToString() +
                                                   " and message " + e.Message);

                // Cleanup the DE on failure
                if (de != null)
                    de.Dispose();

                throw;
            }
        }