Пример #1
0
        public static List <String> getRemoteAdmins(String target)
        {
            //Get accounts with admin privilege from remote machine
            List <String> adminAccounts = new List <string>();

            try
            {
                using (System.DirectoryServices.DirectoryEntry machine = new System.DirectoryServices.DirectoryEntry("WinNT://" + target))
                {
                    using (new UserImpersonator(AppSession.UserName, AppSession.Domain, AppSession.Password))                    //Impersonate as Ad user
                    {
                        using (System.DirectoryServices.DirectoryEntry group = machine.Children.Find("Administrators", "Group")) //Get Administrators Group
                        {
                            object members = group.Invoke("Members", null);                                                      //Get Members of Administratos group
                            foreach (object member in (System.Collections.IEnumerable)members)
                            {
                                string accountName = new System.DirectoryServices.DirectoryEntry(member).Name;
                                if (accountName != "Domain Admins")
                                {
                                    adminAccounts.Add(accountName);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                // TODO Log the Exception
            }
            return(adminAccounts);
        }
Пример #2
0
        public JsonResult SearchUserLDAP()
        {
            Boolean userExists = false;

            System.DirectoryServices.SearchResultCollection sResults = null;
            string path      = "LDAP://201.217.205.157:389/DC =ita, DC=com";
            string criterios = "(&(objectClass=user))";

            try
            {
                System.DirectoryServices.DirectoryEntry    dEntry    = new System.DirectoryServices.DirectoryEntry(path);
                System.DirectoryServices.DirectorySearcher dSearcher = new System.DirectoryServices.DirectorySearcher(dEntry);
                dSearcher.Filter = criterios;
                sResults         = dSearcher.FindAll();

                int result = sResults.Count;
                if (result >= 1)
                {
                    userExists = true;
                }
                else
                {
                    userExists = false;
                }
            }
            catch (Exception ex)
            {
                return(Json(userExists, JsonRequestBehavior.AllowGet));
            }
            return(Json(userExists, JsonRequestBehavior.AllowGet));
        }
Пример #3
0
        public static string GetUserEmail(WindowsIdentity UserIdentity)
        {
            string tempCurrentUserEmail = null;
            var    UserName             = UserIdentity.Name;

            UserName = UserName.Substring(UserName.IndexOf("\\") + 1);
            var Entry = new System.DirectoryServices.DirectoryEntry("LDAP://RootDSE");
            var sFQDN = System.Convert.ToString(Entry.Properties["defaultNamingContext"].Value);
            var myDE  = new System.DirectoryServices.DirectoryEntry("LDAP://" + sFQDN);

            var mySearcher = new System.DirectoryServices.DirectorySearcher(myDE);

            mySearcher.Filter = "sAMAccountName=" + UserName;
            mySearcher.PropertiesToLoad.Add("Mail");
            try
            {
                var myresult = mySearcher.FindOne();
                tempCurrentUserEmail = System.Convert.ToString(myresult.Properties["Mail"][0]);
            }
            catch (Exception ex)
            {
                throw new ApplicationException("Could not establish an email address for user '" + UserName + "' : " + ex.Message);
            }

            return(tempCurrentUserEmail);
        }
Пример #4
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="pDirectoryEntry"></param>
        public ObjectDomainGroup(System.DirectoryServices.DirectoryEntry pDirectoryEntry)
        {
            if (pDirectoryEntry.Properties.Contains("sAMAccountName"))
            {
                base.Name = pDirectoryEntry.Properties["sAMAccountName"][0].ToString(); //Nombre usuario como aaguirre
                _CN       = base.Name;
            }
            if (pDirectoryEntry.Properties.Contains("userPrincipalName"))
            {
                _UserPrincipalName = pDirectoryEntry.Properties["userPrincipalName"][0].ToString();//Nombre usuario como [email protected]
            }
            if (pDirectoryEntry.Properties.Contains("name"))
            {
                base.FullName = pDirectoryEntry.Properties["name"][0].ToString(); //Nombre completo
            }
            if (pDirectoryEntry.Properties.Contains("sAMAccountType"))
            {
                _FirstName = pDirectoryEntry.Properties["sAMAccountType"][0].ToString();
            }
            if (pDirectoryEntry.Properties.Contains("objectCategory"))
            {
                base.Category = pDirectoryEntry.Properties["objectCategory"][0].ToString();
            }

            //ej:CN=GS_Comite_comunicacion_RW,OU=Seguridad,DC=Datacom,DC=org
            if (pDirectoryEntry.Properties.Contains("distinguishedName"))
            {
                _DistinguishedName = pDirectoryEntry.Properties["distinguishedName"][0].ToString();
                SetNameInfo(_DistinguishedName);
            }
            if (pDirectoryEntry.Properties.Contains("description"))
            {
                _Description = pDirectoryEntry.Properties["description"][0].ToString();
            }
        }
 /// <summary>
 /// 删除用户组
 /// </summary>
 /// <param name="groupCommonName">组名</param>
 public void DeleteGroup(string groupCommonName)
 {
     System.DirectoryServices.DirectoryEntry Group = null;
     try
     {
         Group = this.AD.Children.Find(groupCommonName, "group");
     }
     catch (System.Runtime.InteropServices.COMException e)
     {                                                                                        //如果组不存在则正常返回,否则抛出异常。
         if (System.Convert.ToInt64(string.Format("0x{0:X}", e.ErrorCode), 16) == 0x800708AC) //找不到组名。 (异常来自 HRESULT:0x800708AC)
         {
             return;
         }
         throw;
     }
     try
     {
         if (Group.Name != null)
         {
             this.AD.Children.Remove(Group);
         }
     }
     finally
     {
         Group.Close();
     }
 }
Пример #6
0
        private void LDAPQuery(string LDAPUrl, string domain, string userID, string password)
        {
            System.Net.Mail.MailAddress                mailAddres;
            System.DirectoryServices.DirectoryEntry    directoryEntry;
            System.DirectoryServices.DirectorySearcher directorySearcher;
            System.DirectoryServices.SearchResult      searchResult;

            if (this.IsMailAddress(userID, out mailAddres) && mailAddres != null)
            {
                userID = mailAddres.User;
                domain = mailAddres.Host;
            }

            if (userID.Contains("\\"))
            {
                domain = userID.Substring(0, userID.IndexOf('\\'));
                userID = userID.Substring(userID.IndexOf('\\') + 1);
            }

            directoryEntry    = new System.DirectoryServices.DirectoryEntry(LDAPUrl, string.Format("{0}\\{1}", domain, userID), password);
            directorySearcher = new System.DirectoryServices.DirectorySearcher(directoryEntry);
            directorySearcher.ClientTimeout = new TimeSpan(3000);

            directorySearcher.Filter = string.Format("(SAMAccountName={0})", userID);
            searchResult             = directorySearcher.FindOne();

            if (searchResult == null)
            {
                throw new Exception("Not found Valid User");
            }
            else
            {
                Config.Client.SetAttribute("System.DirectoryServices.SearchResult", searchResult);
            }
        }
Пример #7
0
        /// <summary>
        /// 验证域用户
        /// </summary>
        /// <param name="account">域账号</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
        public object checkUser()
        {
            string account  = HttpContext.Current.Request["account"];
            string password = HttpContext.Current.Request["password"];
            string domainIP = Config.GetValue("DomainName");      //域名

            try
            {
                using (System.DirectoryServices.DirectoryEntry deUser = new System.DirectoryServices.DirectoryEntry(@"LDAP://" + domainIP, account, password))
                {
                    if (deUser == null)
                    {
                        return(new { code = 1, message = "验证失败" });
                    }
                    else
                    {
                        if (deUser.Properties.Count == 0)
                        {
                            return(new { code = 1, message = "验证失败" });
                        }
                        else
                        {
                            return(new { code = 0, message = "验证成功" });
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                return(new { code = 1, message = ex.Message });
            }
        }
Пример #8
0
        private void Load()
        {
            // find the userid in the AD
            string ldap = LDAP_Server;

            System.DirectoryServices.DirectoryEntry    colleagues = new System.DirectoryServices.DirectoryEntry(ldap, LDAP_UserName, LDAP_Password);
            System.DirectoryServices.DirectorySearcher searcher   = new System.DirectoryServices.DirectorySearcher(colleagues);
            searcher.Filter       = "(&(objectClass=user)(samAccountName=" + _samAccount + "))";
            searcher.SearchScope  = System.DirectoryServices.SearchScope.Subtree;
            searcher.PageSize     = 9999999;
            searcher.CacheResults = true;

            System.DirectoryServices.SearchResultCollection results = null;

            results = searcher.FindAll();

            if (results.Count > 0)
            {
                System.DirectoryServices.DirectoryEntry entry = results[0].GetDirectoryEntry();
                _name             = GetProperty(entry, "displayName");
                _office           = GetProperty(entry, "physicalDeliveryOfficeName");
                _title            = GetProperty(entry, "title");
                _email            = GetProperty(entry, "mail");
                _phone            = GetProperty(entry, "telephoneNumber");
                _hasDirectReports = GetProperty(entry, "extensionAttribute5");
            }
        }
Пример #9
0
        public DomainPolicy(System.DirectoryServices.DirectoryEntry domainRoot)
        {
            string[] policyAttributes = new string[] {
                "maxPwdAge", "minPwdAge", "minPwdLength",
                "lockoutDuration", "lockOutObservationWindow",
                "lockoutThreshold", "pwdProperties",
                "pwdHistoryLength", "objectClass",
                "distinguishedName"
            };

            //we take advantage of the marshaling with
            //DirectorySearcher for LargeInteger values...
            System.DirectoryServices.DirectorySearcher ds = new System.DirectoryServices.DirectorySearcher(domainRoot, "(objectClass=domainDNS)"
                                                                                                           , policyAttributes, System.DirectoryServices.SearchScope.Base
                                                                                                           );
            System.DirectoryServices.SearchResult result = ds.FindOne();

            //do some quick validation...
            if (result == null)
            {
                throw new System.ArgumentException("domainRoot is not a domainDNS object.");
            }

            this.attribs = result.Properties;
        }
Пример #10
0
 public void RequestRootNode()
 {
     System.DirectoryServices.DirectoryEntry ds = null;
     //
     if (_credential != null)
     {
         ds = new System.DirectoryServices.DirectoryEntry(_rootPath, Credential.UserName, Credential.Password, AuthenticationType);
     }
     else
     {
         ds = new System.DirectoryServices.DirectoryEntry(_rootPath);
     }
     try
     {
         foreach (System.DirectoryServices.DirectoryEntry entry in ds.Children)
         {
             TreeNodePath node = _helper.CreateTreeNode(null, entry.Name.Substring(3), entry.Path, true, false, false);
             node.Tag = entry;
             SetIcon(entry, node);
         }
     }
     finally
     {
         if (ds != null)
         {
             ds.Close();
         }
     }
 }
Пример #11
0
        } // End Function Groups

        // http://stackoverflow.com/questions/45437/determining-members-of-local-groups-via-c-sharp
        public static System.Collections.Generic.List <string> AttributeValuesMultiString(string attributeName, string objectDn
                                                                                          , System.Collections.Generic.List <string> valuesCollection, bool recursive)
        {
            using (System.DirectoryServices.DirectoryEntry ent = new System.DirectoryServices.DirectoryEntry(objectDn))
            {
                System.DirectoryServices.PropertyValueCollection ValueCollection = ent.Properties[attributeName];
                System.Collections.IEnumerator en = ValueCollection.GetEnumerator();

                while (en.MoveNext())
                {
                    if (en.Current != null)
                    {
                        if (!valuesCollection.Contains(en.Current.ToString()))
                        {
                            valuesCollection.Add(en.Current.ToString());
                            if (recursive)
                            {
                                AttributeValuesMultiString(attributeName, "LDAP://" + en.Current.ToString(), valuesCollection, true);
                            } // End if (recursive)
                        }     // End if (!valuesCollection.Contains(en.Current.ToString()))
                    }         // End if (en.Current != null)
                }             // Whend

                ent.Close();
                // ent.Dispose();
            } // End Using DirectoryEntry ent

            return(valuesCollection);
        } // End Function AttributeValuesMultiString
Пример #12
0
        public JsonResult ValidateLdapUser(string user)
        {
            Boolean userExists = false;

            System.DirectoryServices.SearchResultCollection sResults = null;
            string path      = "LDAP://Falabella.com";
            string criterios = "(&(objectClass=user)(samAccountName=" + user + "))";

            try
            {
                System.DirectoryServices.DirectoryEntry    dEntry    = new System.DirectoryServices.DirectoryEntry(path);
                System.DirectoryServices.DirectorySearcher dSearcher = new System.DirectoryServices.DirectorySearcher(dEntry);
                dSearcher.Filter = criterios;
                sResults         = dSearcher.FindAll();

                int result = sResults.Count;
                if (result >= 1)
                {
                    userExists = true;
                }
                else
                {
                    userExists = false;
                }
            }
            catch (Exception ex)
            {
                return(Json(userExists, JsonRequestBehavior.AllowGet));
            }

            return(Json(userExists, JsonRequestBehavior.AllowGet));
        }
        /// <summary>
        /// 将用户从指定组中移除。默认为 Users 下的组和用户。
        /// </summary>
        /// <param name="userCommonName">用户名</param>
        /// <param name="groupCommonName">组名</param>
        public void RemoveUserFromGroup(string userCommonName, string groupCommonName)
        {
            System.DirectoryServices.DirectoryEntry oGroup = this.AD.Children.Find(groupCommonName, "group");

            try
            {
                object members = oGroup.Invoke("Members", null);
                foreach (object member in (System.Collections.IEnumerable)members)
                {
                    //获取该组的每个成员
                    System.DirectoryServices.DirectoryEntry x = new System.DirectoryServices.DirectoryEntry(member);

                    if (userCommonName == x.Name)                                                                     //要移除的用户存在的话,则从该组中移除。
                    {
                        System.DirectoryServices.DirectoryEntry User = this.AD.Children.Find(userCommonName, "user"); //找到该用户
                        oGroup.Invoke("Remove", new object[] { User.Path });
                        User.Close();
                    }
                }
            }
            finally
            {
                oGroup.Close();
            }
        }
Пример #14
0
        private string ObtenerPrimaryDomain(string Dominio, string Usuario, string Clave)
        {
            ///''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
            ///''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
            //               DESCRIPCION DE VARIABLES LOCALES
            //strDominio     : Nombre del dominio a verificar
            //objDirectorio  : Entrada del directorio
            //strPath        : Ubicación del recurso a buscar en el Active Directory
            //strItem        : Valor de array
            //strRet         : Valor de reotorno
            //objVerif       : Objeto DirectorySearcher que se utiliza para verificar si el dominio
            //                 existe
            //objResultado   : Resultado de la búsqueda
            ///''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
            string strDominio = Dominio;

            System.DirectoryServices.DirectoryEntry objDirectorio = null;
            string strPath = null;
            string strItem = null;
            string strRet  = string.Empty;

            System.DirectoryServices.DirectorySearcher objVerif     = default(System.DirectoryServices.DirectorySearcher);
            System.DirectoryServices.SearchResult      objResultado = default(System.DirectoryServices.SearchResult);

            //Si se envia un nombre de dominio en formato NETBIOS se incorpora la palabra local
            if (strDominio.IndexOf('.') == -1)
            {
                strDominio += ".local";
            }
            strPath = "LDAP://";
            foreach (string strItem_loopVariable in strDominio.Split('.'))
            {
                strItem  = strItem_loopVariable;
                strPath += "DC=";
                strPath += strItem;
                strPath += ",";
            }
            strPath = strPath.Substring(0, strPath.Length - 1);

            try
            {
                objDirectorio = new System.DirectoryServices.DirectoryEntry(strPath, Usuario, Clave);
                objVerif      = new System.DirectoryServices.DirectorySearcher(objDirectorio, "(objectClass=domain)");
                objResultado  = objVerif.FindOne();

                if ((objResultado != null))
                {
                    strRet = strDominio;
                }
            }
            catch (Exception)
            {
                return("");
            }
            finally
            {
                objDirectorio.Close();
            }
            return(strRet);
        }
Пример #15
0
        public static List<String> getRemoteAdmins(String target)
        {
            //Get accounts with admin privilege from remote machine
            List<String> adminAccounts = new List<string>();

            try
            {
                using (System.DirectoryServices.DirectoryEntry machine = new System.DirectoryServices.DirectoryEntry("WinNT://" + target))
                {
                    using (new UserImpersonator(AppSession.UserName, AppSession.Domain, AppSession.Password)) //Impersonate as Ad user
                    {
                        using (System.DirectoryServices.DirectoryEntry group = machine.Children.Find("Administrators", "Group")) //Get Administrators Group
                        {
                            object members = group.Invoke("Members", null); //Get Members of Administratos group
                            foreach (object member in (System.Collections.IEnumerable)members)
                            {
                                string accountName = new System.DirectoryServices.DirectoryEntry(member).Name;
                                if (accountName != "Domain Admins")
                                {
                                    adminAccounts.Add(accountName);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                // TODO Log the Exception
            }
            return adminAccounts;
        }
Пример #16
0
        public static bool UpdateUserInfo()
        {
            try
            {
                string domain = GetFqd((!string.IsNullOrEmpty(_UserName) && _UserName.Contains("\\") ? _UserName.Split('\\')[0] : string.Empty));
                using (System.DirectoryServices.AccountManagement.PrincipalContext ctx = new System.DirectoryServices.AccountManagement.PrincipalContext(System.DirectoryServices.AccountManagement.ContextType.Domain, domain))
                {
                    // ReSharper disable once UnusedVariable
                    bool val = ctx.ValidateCredentials(null, null, System.DirectoryServices.AccountManagement.ContextOptions.Negotiate);
                    using (System.DirectoryServices.AccountManagement.UserPrincipal up = System.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity(ctx, _UserName))
                    {
                        // ReSharper disable once UnusedVariable
                        if (up != null)
                        {
                            using (System.DirectoryServices.DirectoryEntry de =
                                       (System.DirectoryServices.DirectoryEntry)up.GetUnderlyingObject())
                            {
                                //string adProperty = "";
                                //if (!de.Properties.Contains(adProperty))
                                //{
                                //    throw new Exception(String.Format("Property {0} does not exist for user {1}", adProperty, userID.Name));
                                //}
                                //switch(adProperty.ToLower()) {
                                //    case "accountexpires":
                                //    case "badpasswordtime":
                                //    case "lastlogon":
                                //    case "pwlastset":
                                //    case "whencreated":  //examples of AD date fields
                                //        DateTime adVal = SDHelpers.ADHelper.FromADDate(de.Properties[adProperty].Value);
                                //        //example of setting an AD Date value
                                //        //de.Properties[adProperty].Value = SDHelpers.ADHelper.ToADDate(DateTime.FromFileTimeUtc(0)); //0 for never(1 / 1 / 1601)-- i.e. for account expiration
                                //        //de.Properties[adProperty].Value = SDHelpers.ADHelper.ToADDate(DateTime.Now.AddMonths(3));   //actual date value
                                //        break;
                                //    case "objectguid":  //example of binary array (GUID) values
                                //        string adVal = SDHelpers.ADHelper.FromBinaryArray((byte[])de.Properties[adProperty].Value);   //equivilent to SDHelpers.ADHelper.FromBinaryArray(de.Properties(adProperty).Value, True)
                                //        //for no hypens
                                //        //string adVal = SDHelpers.ADHelper.FromBinaryArray((byte[])de.Properties[adProperty].Value, false);
                                //        break;
                                //    default:
                                //        string adVal = (string)de.Properties[adProperty].Value;
                                //        //example of setting an AD value
                                //        //de.Properties[adProperty].Value = "somevalue";
                                //        break;
                                //}
                                //  de.CommitChanges();   //save the changes
                                return(true);
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
                return(false);   //error creating the windowidentity object -- not a valid user
            }

            return(false);
        }
Пример #17
0
        private static bool IsValidUserName(string un)
        {
            try
            {
                try
                { //attempt to get information from AD
                    string domain = GetFqd((!string.IsNullOrEmpty(un) && un.Contains("\\") ? un.Split('\\')[0] : string.Empty));
                    using (System.DirectoryServices.AccountManagement.PrincipalContext ctx = new System.DirectoryServices.AccountManagement.PrincipalContext(System.DirectoryServices.AccountManagement.ContextType.Domain, domain))
                    {
                        using (System.DirectoryServices.AccountManagement.UserPrincipal up = System.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity(ctx, un ?? throw new ArgumentNullException(nameof(un))))
                        {
                            if (up != null)
                            {
                                using (System.DirectoryServices.DirectoryEntry de =
                                           (System.DirectoryServices.DirectoryEntry)up.GetUnderlyingObject())
                                {
                                    System.DirectoryServices.PropertyCollection
                                        pc = de.Properties; //all properties AD maintains for a user
                                    //List<string> availableProperties = new List<string>();
                                    //foreach (string pn in pc.PropertyNames)
                                    //{
                                    //    availableProperties.Add(String.Format("{0} -> {1}", pn, pc[pn].Value));
                                    //}
                                    _UserInfo = new AdUser()
                                    {
                                        ObjectGuid =
                                            BitConverter.ToString((byte[])pc["objectguid"].Value)
                                            .Replace("-", string.Empty),
                                        UserName          = un,
                                        EmployeeNumber    = (string)pc["employeenumber"].Value,
                                        FirstName         = up.GivenName,
                                        MiddleName        = up.MiddleName,
                                        LastName          = up.Surname,
                                        DisplayName       = up.DisplayName,
                                        EmailAddress      = up.EmailAddress,
                                        OfficePhoneNumber = up.VoiceTelephoneNumber,
                                        MobilePhoneNumber = (string)pc["mobile"].Value,
                                        Title             = (string)pc["title"].Value
                                    };
                                }
                            }
                        }
                    }
                }
                catch
                {
                    _UserInfo = null;
                }
                return(true);    //valid/active user
            }
            catch (Exception ex)
            {
                Log(ex, MethodBase.GetCurrentMethod());
            }

            return(false);
        }
Пример #18
0
        protected void EnumerateDirectoryEntryProperties(System.DirectoryServices.DirectoryEntry directoryEntry)
        {
            foreach (String currentPropertyName in directoryEntry.Properties.PropertyNames)
            {
                System.Diagnostics.Debug.Write(currentPropertyName + ": ");

                System.Diagnostics.Debug.WriteLine(directoryEntry.Properties[currentPropertyName].Value.ToString());
            }
        }
Пример #19
0
        protected void EnumerateDirectoryEntryProperties(System.DirectoryServices.DirectoryEntry directoryEntry)
        {
            foreach (String currentPropertyName in directoryEntry.Properties.PropertyNames)
            {
                System.Diagnostics.Trace.WriteIf(traceSwitchSecurity.TraceVerbose, currentPropertyName + ": ");

                System.Diagnostics.Trace.WriteLineIf(traceSwitchSecurity.TraceVerbose, directoryEntry.Properties[currentPropertyName].Value.ToString());
            }
        }
Пример #20
0
    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        System.Security.Principal.WindowsIdentity wi = System.Security.Principal.WindowsIdentity.GetCurrent();
        string[] a = User.Identity.Name.Split('\\');
        System.DirectoryServices.DirectoryEntry ADEntry = new   System.DirectoryServices.DirectoryEntry("WinNT://" + a[0] + "/" + a[1]);
        ViewBag.Username = ADEntry.Properties["FullName"].Value.ToString();

        base.OnActionExecuting(filterContext);
    }
Пример #21
0
        public List <DirectoryEntry> BrowseDirectory(String directoryPath)
        {
            List <DirectoryEntry> directoryEntries = new List <DirectoryEntry> ();


            System.DirectoryServices.DirectoryEntry directory = new System.DirectoryServices.DirectoryEntry();

            Boolean foundDirectoryEntry = false;


            try { // TO CONNECT TO DIRECTORY SERVICE BY DOMAIN NAME ONLY
                directory = new System.DirectoryServices.DirectoryEntry("WinNT://" + credentials.Domain);

                foundDirectoryEntry = true;
            }

            catch (Exception directoryExceptionDomainOnly) {
                System.Diagnostics.Trace.WriteLineIf(traceSwitchSecurity.TraceError, directoryExceptionDomainOnly);

                try { // TO CONNECT TO DIRECTORY SERVICE BY DOMAIN NAME AND SERVER NAME
                    directory = new System.DirectoryServices.DirectoryEntry("WinNT://" + credentials.Domain + "/" + credentials.ServerName);

                    foundDirectoryEntry = true;
                }

                catch (Exception directoryException) {
                    System.Diagnostics.Trace.WriteLineIf(traceSwitchSecurity.TraceError, directoryException);

                    // groupDictionary.Add ("0", "Unable to retreive group list for this Domain (" + credentials.Domain + ").");
                }
            } // END TRY: CONNECT TO DIRECTORY SERVICES


            if (foundDirectoryEntry)
            {
                directory.Children.SchemaFilter.Add("User");

                directory.Children.SchemaFilter.Add("Group");

                foreach (System.DirectoryServices.DirectoryEntry currentEntry in directory.Children)
                {
                    if ((currentEntry.SchemaClassName.Equals("Group")) || (currentEntry.SchemaClassName.Equals("User")))
                    {
                        DirectoryEntry directoryEntry = new DirectoryEntry(currentEntry);

                        if ((directoryEntry.ObjectType == "Group") || (directoryEntry.ObjectType == "User"))
                        {
                            directoryEntries.Add(directoryEntry);
                        }
                    }
                }
            } // if (foundDirectoryEntry)


            return(directoryEntries);
        }
Пример #22
0
 public void RequestChildNodes(TreeNodePath parent, System.Windows.Forms.TreeViewCancelEventArgs e)
 {
     System.DirectoryServices.DirectoryEntry parentEntry = parent.Tag as System.DirectoryServices.DirectoryEntry;
     foreach (System.DirectoryServices.DirectoryEntry entry in parentEntry.Children)
     {
         TreeNodePath node = _helper.CreateTreeNode(parent, entry.Name.Substring(3), entry.Path, true, false, false);
         node.Tag = entry;
         SetIcon(entry, node);
     }
 }
Пример #23
0
        public static int GetIndexForADObject(System.DirectoryServices.DirectoryEntry de)
        {
            try
            {
                object[] asProp = de.Properties["objectClass"].Value as object[];
                // poke these in a list for easier reference
                List <string> liClasses = new List <string>();
                foreach (string s in asProp)
                {
                    liClasses.Add(s);
                }
                if (liClasses.Contains("user") || liClasses.Contains("computer"))
                {
                    string usercontrol    = de.Properties["userAccountControl"].Value.ToString();
                    int    userControl    = Convert.ToInt32(usercontrol);
                    string userCtrlBinStr = UserGroupUtils.DecimalToBase(userControl, 2);
                    if (userCtrlBinStr.Length >= 2)
                    {
                        if (liClasses.Contains("computer"))
                        {
                            if (userCtrlBinStr[userCtrlBinStr.Length - 2] == '1')
                            {
                                return((int)ADUCDirectoryNode.GetNodeType("Computer"));
                            }
                            else
                            {
                                return((int)ADUCDirectoryNode.GetNodeType("computer"));
                            }
                        }
                        if (liClasses.Contains("user"))
                        {
                            if (userCtrlBinStr[userCtrlBinStr.Length - 2] == '1')
                            {
                                return((int)ADUCDirectoryNode.GetNodeType("disabledUser"));
                            }
                            else
                            {
                                return((int)ADUCDirectoryNode.GetNodeType("user"));
                            }
                        }
                    }
                }
                else if (liClasses.Contains("group") || liClasses.Contains("foreignSecurityPrincipal"))
                {
                    return((int)ADUCDirectoryNode.GetNodeType("group"));
                }
            }

            catch
            {
                return((int)ADUCDirectoryNode.GetNodeType("group"));
            }

            return((int)ADUCDirectoryNode.GetNodeType("group"));
        }
Пример #24
0
        protected String GetUserDisplayName(String userAccountName)
        {
            System.DirectoryServices.DirectoryEntry directory = new System.DirectoryServices.DirectoryEntry();

            Boolean foundDirectoryEntry = false;

            String userDisplayName = String.Empty;


            try { // TO CONNECT TO DIRECTORY SERVICE BY DOMAIN NAME ONLY
                directory = new System.DirectoryServices.DirectoryEntry("WinNT://" + credentials.Domain);

                foundDirectoryEntry = true;
            }

            catch (Exception directoryExceptionDomainOnly) {
                System.Diagnostics.Trace.WriteLineIf(traceSwitchSecurity.TraceError, directoryExceptionDomainOnly);

                try { // TO CONNECT TO DIRECTORY SERVICE BY DOMAIN NAME AND SERVER NAME
                    directory = new System.DirectoryServices.DirectoryEntry("WinNT://" + credentials.Domain + "/" + credentials.ServerName);

                    foundDirectoryEntry = true;
                }

                catch (Exception directoryException) {
                    System.Diagnostics.Trace.WriteLineIf(traceSwitchSecurity.TraceError, directoryException);

                    // groupDictionary.Add ("0", "Unable to retreive group list for this Domain (" + credentials.Domain + ").");
                }
            } // END TRY: CONNECT TO DIRECTORY SERVICES


            if (foundDirectoryEntry)
            {
                try {
                    directory = new System.DirectoryServices.DirectoryEntry(directory.Path + "/" + userAccountName);

                    if (directory != null)
                    {
                        DirectoryEntry directoryAccount = new DirectoryEntry(directory);

                        userDisplayName = directoryAccount.DisplayName;
                    }
                }

                catch (Exception directoryException) {
                    /* Unsupported function or user name not found. */

                    System.Diagnostics.Trace.WriteLineIf(traceSwitchSecurity.TraceError, "[" + this.GetType().ToString() + "] " + directoryException.Message);
                }
            }

            return(userDisplayName);
        }
Пример #25
0
        }         // End Sub Connect

        //[System.Runtime.InteropServices.ComImport]
        //[System.Runtime.InteropServices.Guid("9068270b-0939-11d1-8be1-00c04fd8d503")]
        //[System.Runtime.InteropServices.InterfaceType(System.Runtime.InteropServices.ComInterfaceType.InterfaceIsDual)]
        //public interface IADsLargeInteger
        //{
        //    [System.Runtime.InteropServices.DispId(0x00000002)]
        //    uint HighPart { get; set; }

        //    [System.Runtime.InteropServices.DispId(0x00000003)]
        //    uint LowPart { get; set; }
        //}


        private void ctr_tree_AfterSelect(object sender, TreeViewEventArgs e)
        {
            //Fill the TreeView dynamic after Click
            if (e.Node.Nodes.Count == 0)
            {
                System.DirectoryServices.DirectoryEntry parent = (System.DirectoryServices.DirectoryEntry)e.Node.Tag;

                if (parent != null)
                {
                    if (parent.Children != null)
                    {
                        foreach (System.DirectoryServices.DirectoryEntry Iter in parent.Children)
                        {
                            TreeNode childNode = e.Node.Nodes.Add(Iter.Name);
                            childNode.Tag = Iter;
                        } // Next Iter
                    }     // End if (parent.Children != null)
                }         // End if (parent != null)
            }             // End if (e.Node.Nodes.Count == 0)


            //Fill the ListView Element
            try
            {
                System.DirectoryServices.DirectoryEntry list = (System.DirectoryServices.DirectoryEntry)e.Node.Tag;
                if (list != null)
                {
                    ctr_list.Clear();

                    //Add some information to ListView ELement
                    ctr_list.Columns.Add("Attribute", 90, HorizontalAlignment.Left);
                    ctr_list.Columns.Add("Value", 350, HorizontalAlignment.Left);

                    foreach (object listIter in list.Properties.PropertyNames)
                    {
                        foreach (object Iter in list.Properties[listIter.ToString()])
                        {
                            string propertyName = listIter.ToString();
                            System.Windows.Forms.ListViewItem item = new System.Windows.Forms.ListViewItem(propertyName, 0);
                            AddLdapObjectAsString(propertyName, Iter, item);
                            ctr_list.Items.AddRange(new ListViewItem[] { item });
                        } // Next Iter
                    }     // Next listIter

                    ctr_list.ListViewItemSorter = this.m_ColumnSorter;
                    ctr_list.Sorting            = SortOrder.Ascending;
                    ctr_list.Sort();
                } // End if (list != null)
            }     // End Try
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
            } // End Catch
        }     // End Sub ctr_tree_AfterSelect
Пример #26
0
        public static System.DirectoryServices.DirectoryEntry[] GetAllChildren(System.DirectoryServices.DirectoryEntry entry)
        {
            System.Collections.Generic.List <System.DirectoryServices.DirectoryEntry> children =
                new System.Collections.Generic.List <System.DirectoryServices.DirectoryEntry>();
            foreach (System.DirectoryServices.DirectoryEntry child in entry.Children)
            {
                children.Add(child);
                children.AddRange(GetAllChildren(child));
            }

            return(children.ToArray());
        }
Пример #27
0
        public static IEnumerable <SyncRecord> DcSyncAll(DcSyncAllSettings settings)
        {
            if (User.IsSystem())
            {
                throw new InvalidOperationException("Current session is running as SYSTEM, dcsync won't work.");
            }

            System.Diagnostics.Debug.Write("[PSH BINDING - DCSYNCALL] User is not running as SYSTEM.");

            if (string.IsNullOrEmpty(settings.Domain))
            {
                settings.Domain = System.DirectoryServices.ActiveDirectory.Domain.GetComputerDomain().Name;
            }

            if (string.IsNullOrEmpty(settings.Domain))
            {
                throw new ArgumentException("Domain parameter must be specified.");
            }

            System.Diagnostics.Debug.WriteLine("[PSH BINDING - DCSYNCALL] Running against domain " + settings.Domain);

            using (var adRoot = new System.DirectoryServices.DirectoryEntry(string.Format("LDAP://{0}", settings.Domain)))
                using (var searcher = new System.DirectoryServices.DirectorySearcher(adRoot))
                {
                    searcher.SearchScope     = System.DirectoryServices.SearchScope.Subtree;
                    searcher.ReferralChasing = System.DirectoryServices.ReferralChasingOption.All;
                    searcher.Filter          = "(objectClass=user)";
                    searcher.PropertiesToLoad.Add("samAccountName");

                    using (var searchResults = searcher.FindAll())
                    {
                        System.Diagnostics.Debug.WriteLine("[PSH BINDING - DCSYNCALL] Search resulted in results: " + searchResults.Count.ToString());
                        foreach (System.DirectoryServices.SearchResult searchResult in searchResults)
                        {
                            if (searchResult != null)
                            {
                                var username = searchResult.Properties["samAccountName"][0].ToString();
                                System.Diagnostics.Debug.WriteLine("[PSH BINDING - DCSYNCALL] Found account: " + username);

                                if (settings.IncludeMachineAccounts || !username.EndsWith("$"))
                                {
                                    var record = DcSync(string.Format("{0}\\{1}", settings.Domain, username), settings.DomainController, settings.DomainFqdn);

                                    if (record != null && (settings.IncludeEmpty || !string.IsNullOrEmpty(record.NtlmHash)))
                                    {
                                        yield return(record);
                                    }
                                }
                            }
                        }
                    }
                }
        }
 /// <summary>
 /// 修改用户密码
 /// </summary>
 /// <param name="commonName">用户名</param>
 /// <param name="oldPassword">旧密码</param>
 /// <param name="newPassword">新密码</param>
 public void ChangeUserPassword(string commonName, string oldPassword, string newPassword)
 {
     System.DirectoryServices.DirectoryEntry obUser = this.AD.Children.Find(commonName, "User");
     try
     {
         obUser.Invoke("ChangePassword", new object[] { oldPassword, newPassword });
         obUser.CommitChanges();
     }
     finally
     {
         obUser.Close();
     }
 }
 /// <summary>
 /// 取消设置用户下次登录时需更改密码。
 /// </summary>
 /// <param name="commonName">用户名</param>
 public void DisablePasswordExpired(string commonName)
 {
     System.DirectoryServices.DirectoryEntry obUser = this.AD.Children.Find(commonName, "User");
     try
     {
         obUser.Invoke("Put", "PasswordExpired", 0);
         obUser.CommitChanges();
     }
     finally
     {
         obUser.Close();
     }
 }
 /// <summary>
 /// 获取用户组信息。
 /// </summary>
 /// <param name="groupCommonName">用户组名称</param>
 /// <returns>用户组信息。</returns>
 public GroupInfo GetGroup(string groupCommonName)
 {
     System.DirectoryServices.DirectoryEntry o = this.AD.Children.Find(groupCommonName, "Group");
     try
     {
         string Description = (string)o.Invoke("Get", "Description");
         return(new GroupInfo(groupCommonName, Description));
     }
     finally
     {
         o.Close();
     }
 }
Пример #31
0
 protected void Button1_Click(object sender, EventArgs e)
 {
     try
     {
         System.DirectoryServices.DirectoryEntry Entry = new System.DirectoryServices.DirectoryEntry("LDAP://" + "bsd.uchicago.edu", TextBox1.Text, TextBox2.Text);
         object nativeobject = Entry.NativeObject;
         lblMessage.Text = "Success";
     }
     catch (Exception ex)
     {
         lblMessage.Text = ex.Message;
     }
 }
 /// <summary>
 /// 添加用户组
 /// </summary>
 /// <param name="groupCommonName">组名</param>
 /// <param name="Description">描述</param>
 public void CreateGroup(string groupCommonName, string Description)
 {
     System.DirectoryServices.DirectoryEntry Group = this.AD.Children.Add(groupCommonName, "group");
     try
     {
         Group.Invoke("Put", "description", Description);
         Group.CommitChanges();
     }
     finally
     {
         Group.Close();
     }
 }
Пример #33
0
        public string ADAuthentication(string User)
        {
            string sMessage="";
            JavaScriptSerializer JSS = new JavaScriptSerializer();

            var DS_ADUser = JSS.Deserialize<Class.ADUser>(User);
            System.DirectoryServices.DirectoryEntry Entity =
                new System.DirectoryServices.DirectoryEntry("LDAP://" + DS_ADUser.DomainName, DS_ADUser.UserID, DS_ADUser.Password);
            try
            {
                object nativeObject = Entity.NativeObject;
                sMessage = "Success";
            }

            catch (Exception ex) { return ex.Message; }

            return sMessage;
        }
Пример #34
0
 /// <summary>
 /// Required method for Designer support - do not modify
 /// the contents of this method with the code editor.
 /// </summary>
 private void InitializeComponent()
 {
     this.label1 = new System.Windows.Forms.Label();
     this.userProfilesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
     this.doctorsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
     this.nursesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
     this.receptionistsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
     this.otherStaffToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
     this.createAUserToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
     this.menuStrip1 = new System.Windows.Forms.MenuStrip();
     this.staffProfileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
     this.configureToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
     this.complaintsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
     this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
     this.directoryEntry1 = new System.DirectoryServices.DirectoryEntry();
     this.textBox1 = new System.Windows.Forms.TextBox();
     this.label2 = new System.Windows.Forms.Label();
     this.panel1 = new System.Windows.Forms.Panel();
     this.textBox5 = new System.Windows.Forms.TextBox();
     this.textBox4 = new System.Windows.Forms.TextBox();
     this.textBox3 = new System.Windows.Forms.TextBox();
     this.textBox2 = new System.Windows.Forms.TextBox();
     this.label7 = new System.Windows.Forms.Label();
     this.label6 = new System.Windows.Forms.Label();
     this.label5 = new System.Windows.Forms.Label();
     this.label4 = new System.Windows.Forms.Label();
     this.label3 = new System.Windows.Forms.Label();
     this.label8 = new System.Windows.Forms.Label();
     this.panel2 = new System.Windows.Forms.Panel();
     this.textBox7 = new System.Windows.Forms.TextBox();
     this.label10 = new System.Windows.Forms.Label();
     this.textBox6 = new System.Windows.Forms.TextBox();
     this.label9 = new System.Windows.Forms.Label();
     this.label11 = new System.Windows.Forms.Label();
     this.panel3 = new System.Windows.Forms.Panel();
     this.textBox10 = new System.Windows.Forms.TextBox();
     this.textBox9 = new System.Windows.Forms.TextBox();
     this.textBox8 = new System.Windows.Forms.TextBox();
     this.label15 = new System.Windows.Forms.Label();
     this.label14 = new System.Windows.Forms.Label();
     this.label13 = new System.Windows.Forms.Label();
     this.label12 = new System.Windows.Forms.Label();
     this.button1 = new System.Windows.Forms.Button();
     this.Registerhak = new System.Windows.Forms.Button();
     this.menuStrip1.SuspendLayout();
     this.panel1.SuspendLayout();
     this.panel2.SuspendLayout();
     this.panel3.SuspendLayout();
     this.SuspendLayout();
     //
     // label1
     //
     this.label1.AutoSize = true;
     this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
     this.label1.Location = new System.Drawing.Point(12, 39);
     this.label1.Name = "label1";
     this.label1.Size = new System.Drawing.Size(122, 24);
     this.label1.TabIndex = 1;
     this.label1.Text = "Create a user";
     //
     // userProfilesToolStripMenuItem
     //
     this.userProfilesToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
     this.doctorsToolStripMenuItem,
     this.nursesToolStripMenuItem,
     this.receptionistsToolStripMenuItem,
     this.otherStaffToolStripMenuItem,
     this.createAUserToolStripMenuItem});
     this.userProfilesToolStripMenuItem.Name = "userProfilesToolStripMenuItem";
     this.userProfilesToolStripMenuItem.Size = new System.Drawing.Size(47, 20);
     this.userProfilesToolStripMenuItem.Text = "Users";
     this.userProfilesToolStripMenuItem.Click += new System.EventHandler(this.userProfilesToolStripMenuItem_Click);
     //
     // doctorsToolStripMenuItem
     //
     this.doctorsToolStripMenuItem.Name = "doctorsToolStripMenuItem";
     this.doctorsToolStripMenuItem.Size = new System.Drawing.Size(144, 22);
     this.doctorsToolStripMenuItem.Text = "Doctors";
     //
     // nursesToolStripMenuItem
     //
     this.nursesToolStripMenuItem.Name = "nursesToolStripMenuItem";
     this.nursesToolStripMenuItem.Size = new System.Drawing.Size(144, 22);
     this.nursesToolStripMenuItem.Text = "Nurses";
     //
     // receptionistsToolStripMenuItem
     //
     this.receptionistsToolStripMenuItem.Name = "receptionistsToolStripMenuItem";
     this.receptionistsToolStripMenuItem.Size = new System.Drawing.Size(144, 22);
     this.receptionistsToolStripMenuItem.Text = "Receptionists";
     //
     // otherStaffToolStripMenuItem
     //
     this.otherStaffToolStripMenuItem.Name = "otherStaffToolStripMenuItem";
     this.otherStaffToolStripMenuItem.Size = new System.Drawing.Size(144, 22);
     this.otherStaffToolStripMenuItem.Text = "Other staff";
     //
     // createAUserToolStripMenuItem
     //
     this.createAUserToolStripMenuItem.Name = "createAUserToolStripMenuItem";
     this.createAUserToolStripMenuItem.Size = new System.Drawing.Size(144, 22);
     this.createAUserToolStripMenuItem.Text = "Create a User";
     //
     // menuStrip1
     //
     this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
     this.staffProfileToolStripMenuItem,
     this.userProfilesToolStripMenuItem,
     this.configureToolStripMenuItem,
     this.complaintsToolStripMenuItem,
     this.exitToolStripMenuItem});
     this.menuStrip1.Location = new System.Drawing.Point(0, 0);
     this.menuStrip1.Name = "menuStrip1";
     this.menuStrip1.Size = new System.Drawing.Size(674, 24);
     this.menuStrip1.TabIndex = 0;
     this.menuStrip1.Text = "menuStrip1";
     //
     // staffProfileToolStripMenuItem
     //
     this.staffProfileToolStripMenuItem.Name = "staffProfileToolStripMenuItem";
     this.staffProfileToolStripMenuItem.Size = new System.Drawing.Size(80, 20);
     this.staffProfileToolStripMenuItem.Text = "Staff Profile";
     this.staffProfileToolStripMenuItem.Click += new System.EventHandler(this.staffProfileToolStripMenuItem_Click);
     //
     // configureToolStripMenuItem
     //
     this.configureToolStripMenuItem.Name = "configureToolStripMenuItem";
     this.configureToolStripMenuItem.Size = new System.Drawing.Size(72, 20);
     this.configureToolStripMenuItem.Text = "Configure";
     this.configureToolStripMenuItem.Click += new System.EventHandler(this.configureToolStripMenuItem_Click);
     //
     // complaintsToolStripMenuItem
     //
     this.complaintsToolStripMenuItem.Name = "complaintsToolStripMenuItem";
     this.complaintsToolStripMenuItem.Size = new System.Drawing.Size(80, 20);
     this.complaintsToolStripMenuItem.Text = "Complaints";
     this.complaintsToolStripMenuItem.Click += new System.EventHandler(this.complaintsToolStripMenuItem_Click);
     //
     // exitToolStripMenuItem
     //
     this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
     this.exitToolStripMenuItem.Size = new System.Drawing.Size(37, 20);
     this.exitToolStripMenuItem.Text = "Exit";
     this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click);
     //
     // textBox1
     //
     this.textBox1.Location = new System.Drawing.Point(115, 81);
     this.textBox1.Name = "textBox1";
     this.textBox1.Size = new System.Drawing.Size(100, 20);
     this.textBox1.TabIndex = 2;
     //
     // label2
     //
     this.label2.AutoSize = true;
     this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
     this.label2.Location = new System.Drawing.Point(13, 82);
     this.label2.Name = "label2";
     this.label2.Size = new System.Drawing.Size(96, 16);
     this.label2.TabIndex = 3;
     this.label2.Text = "Registration ID";
     //
     // panel1
     //
     this.panel1.Controls.Add(this.textBox5);
     this.panel1.Controls.Add(this.textBox4);
     this.panel1.Controls.Add(this.textBox3);
     this.panel1.Controls.Add(this.textBox2);
     this.panel1.Controls.Add(this.label7);
     this.panel1.Controls.Add(this.label6);
     this.panel1.Controls.Add(this.label5);
     this.panel1.Controls.Add(this.label4);
     this.panel1.Location = new System.Drawing.Point(16, 128);
     this.panel1.Name = "panel1";
     this.panel1.Size = new System.Drawing.Size(287, 100);
     this.panel1.TabIndex = 4;
     //
     // textBox5
     //
     this.textBox5.Location = new System.Drawing.Point(66, 77);
     this.textBox5.Name = "textBox5";
     this.textBox5.Size = new System.Drawing.Size(209, 20);
     this.textBox5.TabIndex = 7;
     //
     // textBox4
     //
     this.textBox4.Location = new System.Drawing.Point(67, 54);
     this.textBox4.Name = "textBox4";
     this.textBox4.Size = new System.Drawing.Size(206, 20);
     this.textBox4.TabIndex = 6;
     //
     // textBox3
     //
     this.textBox3.Location = new System.Drawing.Point(67, 32);
     this.textBox3.Name = "textBox3";
     this.textBox3.Size = new System.Drawing.Size(206, 20);
     this.textBox3.TabIndex = 5;
     //
     // textBox2
     //
     this.textBox2.Location = new System.Drawing.Point(66, 9);
     this.textBox2.Name = "textBox2";
     this.textBox2.Size = new System.Drawing.Size(207, 20);
     this.textBox2.TabIndex = 4;
     //
     // label7
     //
     this.label7.AutoSize = true;
     this.label7.Location = new System.Drawing.Point(3, 79);
     this.label7.Name = "label7";
     this.label7.Size = new System.Drawing.Size(30, 13);
     this.label7.TabIndex = 3;
     this.label7.Text = "DOB";
     //
     // label6
     //
     this.label6.AutoSize = true;
     this.label6.Location = new System.Drawing.Point(3, 57);
     this.label6.Name = "label6";
     this.label6.Size = new System.Drawing.Size(45, 13);
     this.label6.TabIndex = 2;
     this.label6.Text = "Address";
     //
     // label5
     //
     this.label5.AutoSize = true;
     this.label5.Location = new System.Drawing.Point(3, 35);
     this.label5.Name = "label5";
     this.label5.Size = new System.Drawing.Size(58, 13);
     this.label5.TabIndex = 1;
     this.label5.Text = "Last Name";
     //
     // label4
     //
     this.label4.AutoSize = true;
     this.label4.Location = new System.Drawing.Point(3, 12);
     this.label4.Name = "label4";
     this.label4.Size = new System.Drawing.Size(57, 13);
     this.label4.TabIndex = 0;
     this.label4.Text = "First Name";
     //
     // label3
     //
     this.label3.AutoSize = true;
     this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
     this.label3.Location = new System.Drawing.Point(13, 107);
     this.label3.Name = "label3";
     this.label3.Size = new System.Drawing.Size(113, 18);
     this.label3.TabIndex = 5;
     this.label3.Text = "Personal details";
     //
     // label8
     //
     this.label8.AutoSize = true;
     this.label8.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
     this.label8.Location = new System.Drawing.Point(12, 241);
     this.label8.Name = "label8";
     this.label8.Size = new System.Drawing.Size(115, 20);
     this.label8.TabIndex = 6;
     this.label8.Text = "Contact details";
     //
     // panel2
     //
     this.panel2.Controls.Add(this.textBox7);
     this.panel2.Controls.Add(this.label10);
     this.panel2.Controls.Add(this.textBox6);
     this.panel2.Controls.Add(this.label9);
     this.panel2.Location = new System.Drawing.Point(16, 264);
     this.panel2.Name = "panel2";
     this.panel2.Size = new System.Drawing.Size(287, 64);
     this.panel2.TabIndex = 7;
     //
     // textBox7
     //
     this.textBox7.Location = new System.Drawing.Point(85, 33);
     this.textBox7.Name = "textBox7";
     this.textBox7.Size = new System.Drawing.Size(188, 20);
     this.textBox7.TabIndex = 3;
     //
     // label10
     //
     this.label10.AutoSize = true;
     this.label10.Location = new System.Drawing.Point(3, 36);
     this.label10.Name = "label10";
     this.label10.Size = new System.Drawing.Size(32, 13);
     this.label10.TabIndex = 2;
     this.label10.Text = "Email";
     //
     // textBox6
     //
     this.textBox6.Location = new System.Drawing.Point(85, 10);
     this.textBox6.Name = "textBox6";
     this.textBox6.Size = new System.Drawing.Size(188, 20);
     this.textBox6.TabIndex = 1;
     //
     // label9
     //
     this.label9.AutoSize = true;
     this.label9.Location = new System.Drawing.Point(3, 13);
     this.label9.Name = "label9";
     this.label9.Size = new System.Drawing.Size(76, 13);
     this.label9.TabIndex = 0;
     this.label9.Text = "Mobile number";
     //
     // label11
     //
     this.label11.AutoSize = true;
     this.label11.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
     this.label11.Location = new System.Drawing.Point(352, 105);
     this.label11.Name = "label11";
     this.label11.Size = new System.Drawing.Size(147, 20);
     this.label11.TabIndex = 8;
     this.label11.Text = "Department Details";
     //
     // panel3
     //
     this.panel3.Controls.Add(this.textBox10);
     this.panel3.Controls.Add(this.textBox9);
     this.panel3.Controls.Add(this.textBox8);
     this.panel3.Controls.Add(this.label15);
     this.panel3.Controls.Add(this.label14);
     this.panel3.Controls.Add(this.label13);
     this.panel3.Controls.Add(this.label12);
     this.panel3.Location = new System.Drawing.Point(356, 128);
     this.panel3.Name = "panel3";
     this.panel3.Size = new System.Drawing.Size(247, 92);
     this.panel3.TabIndex = 9;
     //
     // textBox10
     //
     this.textBox10.Location = new System.Drawing.Point(84, 57);
     this.textBox10.Name = "textBox10";
     this.textBox10.Size = new System.Drawing.Size(154, 20);
     this.textBox10.TabIndex = 6;
     //
     // textBox9
     //
     this.textBox9.Location = new System.Drawing.Point(84, 32);
     this.textBox9.Name = "textBox9";
     this.textBox9.Size = new System.Drawing.Size(154, 20);
     this.textBox9.TabIndex = 5;
     //
     // textBox8
     //
     this.textBox8.Location = new System.Drawing.Point(84, 9);
     this.textBox8.Name = "textBox8";
     this.textBox8.Size = new System.Drawing.Size(154, 20);
     this.textBox8.TabIndex = 4;
     //
     // label15
     //
     this.label15.AutoSize = true;
     this.label15.Location = new System.Drawing.Point(3, 77);
     this.label15.Name = "label15";
     this.label15.Size = new System.Drawing.Size(0, 13);
     this.label15.TabIndex = 3;
     //
     // label14
     //
     this.label14.AutoSize = true;
     this.label14.Location = new System.Drawing.Point(3, 64);
     this.label14.Name = "label14";
     this.label14.Size = new System.Drawing.Size(75, 13);
     this.label14.TabIndex = 2;
     this.label14.Text = "Date of joining";
     //
     // label13
     //
     this.label13.AutoSize = true;
     this.label13.Location = new System.Drawing.Point(3, 39);
     this.label13.Name = "label13";
     this.label13.Size = new System.Drawing.Size(63, 13);
     this.label13.TabIndex = 1;
     this.label13.Text = "Designation";
     //
     // label12
     //
     this.label12.AutoSize = true;
     this.label12.Location = new System.Drawing.Point(3, 16);
     this.label12.Name = "label12";
     this.label12.Size = new System.Drawing.Size(62, 13);
     this.label12.TabIndex = 0;
     this.label12.Text = "Department";
     //
     // button1
     //
     this.button1.Location = new System.Drawing.Point(543, 305);
     this.button1.Name = "button1";
     this.button1.Size = new System.Drawing.Size(60, 23);
     this.button1.TabIndex = 10;
     this.button1.Text = "Done";
     this.button1.UseVisualStyleBackColor = true;
     this.button1.Click += new System.EventHandler(this.button1_Click);
     //
     // Registerhak
     //
     this.Registerhak.Location = new System.Drawing.Point(347, 305);
     this.Registerhak.Name = "Registerhak";
     this.Registerhak.Size = new System.Drawing.Size(75, 23);
     this.Registerhak.TabIndex = 11;
     this.Registerhak.Text = "Register";
     this.Registerhak.UseVisualStyleBackColor = true;
     this.Registerhak.Click += new System.EventHandler(this.button2_Click);
     //
     // Systems_Admin
     //
     this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
     this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
     this.BackColor = System.Drawing.SystemColors.InactiveCaption;
     this.ClientSize = new System.Drawing.Size(674, 381);
     this.Controls.Add(this.Registerhak);
     this.Controls.Add(this.button1);
     this.Controls.Add(this.panel3);
     this.Controls.Add(this.label11);
     this.Controls.Add(this.panel2);
     this.Controls.Add(this.label8);
     this.Controls.Add(this.label3);
     this.Controls.Add(this.panel1);
     this.Controls.Add(this.label2);
     this.Controls.Add(this.textBox1);
     this.Controls.Add(this.label1);
     this.Controls.Add(this.menuStrip1);
     this.MainMenuStrip = this.menuStrip1;
     this.Name = "Systems_Admin";
     this.Text = "Systems_Admin";
     this.Load += new System.EventHandler(this.Systems_Admin_Load);
     this.menuStrip1.ResumeLayout(false);
     this.menuStrip1.PerformLayout();
     this.panel1.ResumeLayout(false);
     this.panel1.PerformLayout();
     this.panel2.ResumeLayout(false);
     this.panel2.PerformLayout();
     this.panel3.ResumeLayout(false);
     this.panel3.PerformLayout();
     this.ResumeLayout(false);
     this.PerformLayout();
 }
Пример #35
0
        public bool GetADInformation()
        {
            string strUserId = "", strFilter = "";

            if(!SAMAccountName.Equals( "" ))
            {
                strUserId = SAMAccountName;

                if(strUserId.Contains( @"\" ))
                    strUserId = strUserId.Substring( 5 );

                // only EmCare/EMSC users
                strFilter = string.Format( "(|(&(objectClass=User)(sAMAccountName={0})(|(company=EmCare*)(company=EMSC*))))", strUserId );
            }

            if(!LastName.Equals( "" ))
                // only EmCare/EMSC users
                strFilter = string.Format( "(|(&(objectClass=User)(givenname={0})(sn={1})(|(company=EmCare*)(company=EMSC*))))", FirstName, LastName );

            string strServer = System.Configuration.ConfigurationManager.AppSettings["EMSC"].ToString();
            string strADUser = System.Configuration.ConfigurationManager.AppSettings["LDAPUID"].ToString();
            string strADPwd = System.Configuration.ConfigurationManager.AppSettings["LDAPPwd"].ToString();

            string sLDAPPath = string.Format("LDAP://{0}/DC=EMSC,DC=root01,DC=org", strServer);
            System.DirectoryServices.DirectoryEntry objDE = null;
            System.DirectoryServices.DirectorySearcher objDS = null;
            try
            {
                objDE = new System.DirectoryServices.DirectoryEntry( sLDAPPath, strADUser, strADPwd, System.DirectoryServices.AuthenticationTypes.Secure );

                objDS = new System.DirectoryServices.DirectorySearcher( objDE );

                // get the LDAP filter string based on selections
                objDS.Filter = strFilter;
                objDS.ReferralChasing = System.DirectoryServices.ReferralChasingOption.None;

                //String strResult = String.Format(
                //"(&(objectClass={0})(givenname={1})(sn={2}))",
                //sLDAPUserObjectClass, sFirstNameSearchFilter, sLastNameSearchFilter);
                //string sFilter =
                //String.Format("(&(objectclass=user)(MemberOf=CN={0},OU=Groups,DC={1},DC=root01,DC=org))",
                //    strGroupName, strDomain);

                objDS.PropertiesToLoad.Add( "userAccountControl" );
                objDS.PropertiesToLoad.Add( "SAMAccountName" );
                objDS.PropertiesToLoad.Add( "givenName" );
                objDS.PropertiesToLoad.Add( "sn" );
                objDS.PropertiesToLoad.Add( "TelephoneNumber" );
                objDS.PropertiesToLoad.Add( "mail" );
                objDS.PropertiesToLoad.Add( "title" );
                objDS.PropertiesToLoad.Add( "department" );
                objDS.PropertiesToLoad.Add( "company" );
                objDS.PropertiesToLoad.Add( "physicalDeliveryOfficeName" );
                objDS.PropertiesToLoad.Add( "displayName" );

                //start searching
                System.DirectoryServices.SearchResultCollection objSRC = objDS.FindAll();

                try
                {
                    if( objSRC.Count != 0 )
                    {
                        //if(objSRC.Count > 1)
                        //    Found = Found;

                        // grab the first search result
                        System.DirectoryServices.SearchResult objSR = objSRC[ 0 ];

                        Found = true;

                        displayName = objSR.Properties[ "displayName" ][ 0 ].ToString();
                        givenName = objSR.Properties[ "givenName" ][ 0 ].ToString();
                        sn = objSR.Properties[ "sn" ][ 0 ].ToString();
                        SAMAccountName = objSR.Properties[ "SAMAccountName" ][ 0 ].ToString();

                        userAccountControl = objSR.Properties[ "userAccountControl" ][ 0 ].ToString();
                        int iInactiveFlag = Convert.ToInt32( userAccountControl );
                        iInactiveFlag = iInactiveFlag & 0x0002;
                        Active = iInactiveFlag <= 0;

                        if( objSR.Properties[ "TelephoneNumber" ].Count > 0 )
                            TelephoneNumber = objSR.Properties[ "TelephoneNumber" ][ 0 ].ToString();
                        if( objSR.Properties[ "mail" ].Count > 0 )
                            mail = objSR.Properties[ "mail" ][ 0 ].ToString();
                        if( objSR.Properties[ "title" ].Count > 0 )
                            title = objSR.Properties[ "title" ][ 0 ].ToString();
                        if( objSR.Properties[ "department" ].Count > 0 )
                            department = objSR.Properties[ "department" ][ 0 ].ToString();
                        if( objSR.Properties[ "company" ].Count > 0 )
                            company = objSR.Properties[ "company" ][ 0 ].ToString();
                        if( objSR.Properties[ "physicalDeliveryOfficeName" ].Count > 0 )
                            physicalDeliveryOfficeName = objSR.Properties[ "physicalDeliveryOfficeName" ][ 0 ].ToString();
                    }
                    else
                    {
                        Found = false;
                        return Found;
                    }
                }
                catch( Exception )
                {
                    // ignore errors
                    Found = false;
                    return false;
                }
                finally
                {
                    objDE.Dispose();
                    objSRC.Dispose();
                    //objDS.Dispose();
                }
            }
            catch( Exception )
            {
                // ignore errors
                Found = false;
                return false;
            }
            finally
            {
                objDS.Dispose();
            }

            return Found;
        }
 public static DateTime PasswordExpireTime(string domainOrMachineName, string userName)
 {
     using (var directoryEntry = new System.DirectoryServices.DirectoryEntry("WinNT://" + domainOrMachineName + '/' + userName + ",user"))
     {
         try
         {
             return (DateTime)directoryEntry.InvokeGet("PasswordExpirationDate");
         }
         catch (TargetInvocationException e)
         {
             throw e.InnerException;
         }
     }
 }
        public void RequestRootNode()
        {
            System.DirectoryServices.DirectoryEntry ds = null;
            //
            if (_credential != null)
            {
                ds = new System.DirectoryServices.DirectoryEntry(_rootPath, Credential.UserName, Credential.Password, AuthenticationType);
            }
            else
            {
                ds = new System.DirectoryServices.DirectoryEntry(_rootPath);
            }
            try
            {
                foreach (System.DirectoryServices.DirectoryEntry entry in ds.Children)
                {
                    TreeNodePath node = _helper.CreateTreeNode(null, entry.Name.Substring(3), entry.Path, true, false, false);
                    node.Tag = entry;
                    SetIcon(entry, node);
                }

            }
            finally
            {
                if (ds != null) ds.Close();
            }
        }
        private void queryDomainWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            string domainName = e.Argument as string;
            System.DirectoryServices.DirectoryEntry directoryEntry = new System.DirectoryServices.DirectoryEntry();
            directoryEntry.Path = "WinNT://" + domainName;

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

            foreach (System.DirectoryServices.DirectoryEntry child in directoryEntry.Children)
            {
                switch (child.SchemaClassName)
                {
                    case "Computer":
                        domainComputerNames.Add(child.Name);
                        break;
                }
            }

            e.Result = domainComputerNames;
        }
Пример #39
0
        private void btnLogin_Click(object sender, EventArgs e)
        {
            //UserPrincipal user = UserPrincipal.Current;
            //string displayName = user.DisplayName;

            if (rBtnWindows.Checked)
            {
                string domain = IPGlobalProperties.GetIPGlobalProperties().DomainName;
                using (var principalContext = new PrincipalContext(ContextType.Domain, domain))
                {
                    bool logged = principalContext.ValidateCredentials(txtUsername.Text, txtPassword.Text);
                    if (logged)
                    {
                        BEUser loggedUser = _gateway.GetUserByUsername("User/GetUserByUsername/" + txtUsername.Text) ??
                                            new BEUser();
                        WindowsIdentity identity = new WindowsIdentity(txtUsername.Text);
                        string[] identitySplitted = identity.Name.Split('\\');
                        System.DirectoryServices.DirectoryEntry ADEntry =
                            new System.DirectoryServices.DirectoryEntry("WinNT://" + identitySplitted[0] + "/" +
                                                                        identitySplitted[1]);

                        loggedUser.Company = identitySplitted[0];
                        loggedUser.Username = identitySplitted[1];
                        loggedUser.WindowsLogged = true;
                        loggedUser.FullName = ADEntry.Properties["FullName"].Value.ToString();

                        FormLoadingDevice startup = new FormLoadingDevice(loggedUser);
                        startup.Show();
                        Hide();
                    }
                    else
                    {
                        MessageBox.Show("Login failed. Incorrect credentials");
                    }
                }
            }
            else
            {
                var user = _gateway.GetUserByUsername("User/GetUserByPhoneNumber/" + txtUsername.Text);
                if (user == null)
                {
                    int response = CheckForLegalPhoneNumber(txtUsername.Text);
                    if (response == 10)
                    {
                        user = _gateway.CreateUser("User?phoneNumber=" + txtUsername.Text, txtUsername.Text);
                    }
                    else
                    {
                        if (response == 1)
                            MessageBox.Show("Phone number cannot be shorter than 8 digits", "Error");

                        else if (response == 2)
                            MessageBox.Show("Phone number may only contain numbers", "Error");

                        return;
                    }
                }
                user.WindowsLogged = false;
                FormLoadingDevice startup = new FormLoadingDevice(user);
                startup.Show();
                Hide();
            }
        }
Пример #40
0
        private void bwAD_DoWork(object sender, DoWorkEventArgs e) {
            // http://channel9.msdn.com/Forums/TechOff/Computer-names-on-network-c
            List<String> _ComputerNames = new List<String>();
            String _ComputerSchema = "Computer";
            System.DirectoryServices.DirectoryEntry _WinNTDirectoryEntries = new System.DirectoryServices.DirectoryEntry("WinNT:");
            foreach (System.DirectoryServices.DirectoryEntry _AvailDomains in _WinNTDirectoryEntries.Children) {
                foreach (System.DirectoryServices.DirectoryEntry _PCNameEntry in _AvailDomains.Children) {
                    if (_PCNameEntry.SchemaClassName.ToLower().Contains(_ComputerSchema.ToLower())) {
                        _ComputerNames.Add(_PCNameEntry.Name);
                    }
                }
            }

            e.Result = _ComputerNames;
        }
        private bool LDAPValidation(string ldapDomain, string userName, string password)
        {
            System.DirectoryServices.DirectoryEntry de = new System.DirectoryServices.DirectoryEntry(@"LDAP://" + ldapDomain, userName, password);

            try
            {
                object o = de.NativeObject;
                //This means LDAP has found the entry with username and Password
                return true;
            }
            catch (Exception ex)
            {
                //Either User does not exists or password is Wrong
                throw new Exception("LDAP validation failed:" + ex.Message);
            }
        }
Пример #42
0
 /// <summary>
 /// 设计器支持所需的方法 - 不要
 /// 使用代码编辑器修改此方法的内容。
 /// </summary>
 private void InitializeComponent()
 {
     this.directoryEntry1 = new System.DirectoryServices.DirectoryEntry();
     this.button1 = new System.Windows.Forms.Button();
     this.label1 = new System.Windows.Forms.Label();
     this.textBox1 = new System.Windows.Forms.TextBox();
     this.folderBrowserDialog1 = new System.Windows.Forms.FolderBrowserDialog();
     this.button2 = new System.Windows.Forms.Button();
     this.label2 = new System.Windows.Forms.Label();
     this.textBox2 = new System.Windows.Forms.TextBox();
     this.groupBox1 = new System.Windows.Forms.GroupBox();
     this.groupBox2 = new System.Windows.Forms.GroupBox();
     this.groupBox1.SuspendLayout();
     this.groupBox2.SuspendLayout();
     this.SuspendLayout();
     //
     // button1
     //
     this.button1.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
     this.button1.Location = new System.Drawing.Point(270, 28);
     this.button1.Name = "button1";
     this.button1.Size = new System.Drawing.Size(93, 23);
     this.button1.TabIndex = 0;
     this.button1.Text = "选择虚拟目录";
     this.button1.UseVisualStyleBackColor = true;
     this.button1.Click += new System.EventHandler(this.button1_Click);
     //
     // label1
     //
     this.label1.AutoSize = true;
     this.label1.Location = new System.Drawing.Point(12, 33);
     this.label1.Name = "label1";
     this.label1.Size = new System.Drawing.Size(113, 12);
     this.label1.TabIndex = 1;
     this.label1.Text = "虚拟目录物理路径:";
     //
     // textBox1
     //
     this.textBox1.Location = new System.Drawing.Point(131, 28);
     this.textBox1.Name = "textBox1";
     this.textBox1.Size = new System.Drawing.Size(122, 21);
     this.textBox1.TabIndex = 2;
     //
     // button2
     //
     this.button2.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
     this.button2.Location = new System.Drawing.Point(123, 16);
     this.button2.Name = "button2";
     this.button2.Size = new System.Drawing.Size(130, 23);
     this.button2.TabIndex = 3;
     this.button2.Text = "建立虚拟目录";
     this.button2.UseVisualStyleBackColor = true;
     this.button2.Click += new System.EventHandler(this.button2_Click);
     //
     // label2
     //
     this.label2.AutoSize = true;
     this.label2.Location = new System.Drawing.Point(14, 64);
     this.label2.Name = "label2";
     this.label2.Size = new System.Drawing.Size(89, 12);
     this.label2.TabIndex = 4;
     this.label2.Text = "虚拟目录名称:";
     //
     // textBox2
     //
     this.textBox2.Location = new System.Drawing.Point(130, 61);
     this.textBox2.Name = "textBox2";
     this.textBox2.Size = new System.Drawing.Size(233, 21);
     this.textBox2.TabIndex = 5;
     //
     // groupBox1
     //
     this.groupBox1.Controls.Add(this.label1);
     this.groupBox1.Controls.Add(this.textBox2);
     this.groupBox1.Controls.Add(this.button1);
     this.groupBox1.Controls.Add(this.label2);
     this.groupBox1.Controls.Add(this.textBox1);
     this.groupBox1.Location = new System.Drawing.Point(5, 1);
     this.groupBox1.Name = "groupBox1";
     this.groupBox1.Size = new System.Drawing.Size(379, 103);
     this.groupBox1.TabIndex = 6;
     this.groupBox1.TabStop = false;
     this.groupBox1.Text = "信息";
     //
     // groupBox2
     //
     this.groupBox2.Controls.Add(this.button2);
     this.groupBox2.Location = new System.Drawing.Point(5, 110);
     this.groupBox2.Name = "groupBox2";
     this.groupBox2.Size = new System.Drawing.Size(379, 50);
     this.groupBox2.TabIndex = 7;
     this.groupBox2.TabStop = false;
     this.groupBox2.Text = "操作";
     //
     // Frm_Main
     //
     this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
     this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
     this.ClientSize = new System.Drawing.Size(389, 163);
     this.Controls.Add(this.groupBox2);
     this.Controls.Add(this.groupBox1);
     this.Name = "Frm_Main";
     this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
     this.Text = "使用DirectoryEntry组件建立虚拟目录";
     this.groupBox1.ResumeLayout(false);
     this.groupBox1.PerformLayout();
     this.groupBox2.ResumeLayout(false);
     this.ResumeLayout(false);
 }
Пример #43
0
        /// <summary>
        /// Method to convert strlong to byte[].
        /// </summary>
        /// <param name="strLogin">The login string.</param>
        /// <returns>The bytes array that will be converted.</returns>
        private byte[] GetSid(string strLogin)
        {
            byte[] arr = null;

            // Parse the string to check if domain name is present.
            int idx = strLogin.IndexOf('\\');
            if (idx == -1)
            {
                idx = strLogin.IndexOf('@');
            }

            string strDomain;
            string strName;

            if (idx != -1)
            {
                strDomain = strLogin.Substring(0, idx);
                strName = strLogin.Substring(idx + 1);
            }
            else
            {
                strDomain = Environment.MachineName;
                strName = strLogin;
            }

            System.DirectoryServices.DirectoryEntry obDirEntry = null;
            try
            {
                obDirEntry = new System.DirectoryServices.DirectoryEntry("WinNT://" + strDomain + "/" + strName);
                System.DirectoryServices.PropertyCollection coll = obDirEntry.Properties;
                object obVal = coll["objectSid"].Value;

                if (null != obVal)
                {
                    arr = (byte[])obVal;
                }
            }
            catch (Exception)
            {
                throw;
            }

            return arr;
        }
Пример #44
0
 private static System.Data.DataTable GetDataSourceLDAP(System.String book, System.String connectstring, System.String connectusername, System.String connectpassword, System.String searchfilter, System.String namecolumn, System.String mailcolumn, System.String ownercolumn)
 {
     System.Data.DataTable datasource = GetDataSourceDataTable(namecolumn, mailcolumn, ownercolumn, book);
     System.DirectoryServices.DirectoryEntry direntry = new System.DirectoryServices.DirectoryEntry(connectstring);
     direntry.Username = connectusername;
     direntry.Password = connectpassword;
     System.DirectoryServices.DirectorySearcher dirsearcher = new System.DirectoryServices.DirectorySearcher(direntry);
     dirsearcher.Filter = searchfilter;
     dirsearcher.SearchScope = System.DirectoryServices.SearchScope.OneLevel;
     dirsearcher.PropertiesToLoad.Add(namecolumn);
     dirsearcher.PropertiesToLoad.Add(mailcolumn);
     System.DirectoryServices.SearchResultCollection results = null;
     try {
         results = dirsearcher.FindAll();
     } catch ( System.Exception e) {
         if (log.IsErrorEnabled)
             log.Error("Error while doing LDAP query", e);
         return null;
     }
     System.String name, value;
     foreach ( System.DirectoryServices.SearchResult result in results ) {
         name = null;
         value = null;
         if ( result.Properties.Contains(namecolumn) && result.Properties.Contains(mailcolumn) && result.Properties[namecolumn].Count>0 && result.Properties[mailcolumn].Count>0 ) {
             name = result.Properties[namecolumn][0].ToString();
             value = result.Properties[mailcolumn][0].ToString();
         }
         if ( name!=null && value!=null ) {
             try {
                 datasource.Rows.Add(new object[]{name, value});
             } catch ( System.Exception ){}
         }
     }
     return datasource;
 }
        /// <summary>
        /// Apply the conversion from username to email address.
        /// </summary>
        /// <param name="username">The username.</param>
        /// <returns>The email address.</returns>
        public string Convert(string username)
        {           
            string ldapPath = @"LDAP://" + domainName;
            string ldapFilter = @"(&(objectClass=user)(SAMAccountName=" + username + "))";
            string[] ldapProperties = { ldap_Mail, ldap_QueryField };

            System.DirectoryServices.DirectoryEntry domain;
            if (ldap_LogOnUser.Length > 0 )
            {
                domain = new System.DirectoryServices.DirectoryEntry(ldapPath,ldap_LogOnUser,ldap_LogOnPassword.PrivateValue);
            }
            else
            {
                domain = new System.DirectoryServices.DirectoryEntry(ldapPath);
            }
            

            System.DirectoryServices.DirectorySearcher searcher = new System.DirectoryServices.DirectorySearcher(domain);
            System.DirectoryServices.SearchResult result;

            searcher.Filter = ldapFilter;
            searcher.PropertiesToLoad.AddRange(ldapProperties);
            
            result = searcher.FindOne();

            searcher.Dispose();

            // Check the result
            if (result != null)
            {
                return result.Properties[ldap_Mail][0].ToString();
            }
            else
            {
                Core.Util.Log.Debug(string.Format(System.Globalization.CultureInfo.CurrentCulture,"No email adress found for user {0} in domain {1}",username,domainName));
                return null;
            }
        }
        /// <summary>
        /// Queries and fills the ldap message for the Domain
        /// Gets the attribute list from AD for Domain schema attribute.
        /// search for the attributes description
        /// </summary>
        /// <param name="ce"></param>
        /// <param name="servername"></param>
        /// <param name="name"></param>
        /// <param name="dirnode"></param>
        public void SetData(CredentialEntry ce, string servername, string name, ADUCDirectoryNode dirnode)
        {
            try
            {
                this.dirnode = dirnode;
                int ret = -1;
                List<LdapEntry> ldapEntries = null;

                ret = dirnode.LdapContext.ListChildEntriesSynchronous
                (dirnode.DistinguishedName,
                LdapAPI.LDAPSCOPE.BASE,
                "(objectClass=*)",
                null,
                false,
                out ldapEntries);

                if (ldapEntries == null || ldapEntries.Count == 0)
                {
                    return;
                }
                LdapEntry ldapNextEntry = ldapEntries[0];

                string[] attrsList = ldapNextEntry.GetAttributeNames();

                if (attrsList != null)
                {
                    foreach (string attr in attrsList)
                    {
                        string sValue = "";

                        LdapValue[] attrValues = ldapNextEntry.GetAttributeValues(attr, dirnode.LdapContext);

                        if (attrValues != null && attrValues.Length > 0)
                        {
                            foreach (LdapValue value in attrValues)
                            {
                                sValue = sValue + "," + value.stringData;
                            }
                        }

                        if (sValue.StartsWith(","))
                        {
                            sValue = sValue.Substring(1);
                        }

                        if (string.Compare(sValue, "") == 0)
                        {
                            sValue = "<Not Set>";
                        }

                        if (string.Compare(attr, "description") == 0)
                        {
                            this.txtDescription.Text = sValue;
                            Description = sValue;
                        }
                        if (string.Compare(attr, "objectSid") == 0)
                        {
                            System.DirectoryServices.DirectoryEntry de = new System.DirectoryServices.DirectoryEntry(dirnode.DistinguishedName);
                            byte[] objectSid = de.Properties["objectSid"].Value as byte[];
                            string Sid = UserGroupUtils.SIDtoString(objectSid);
                            string cn = UserGroupUtils.GetGroupFromForeignSecurity(Sid, dirnode.LdapContext);
                            if (cn != null)
                            {
                                lblName.Text = string.Concat("NT AUTHORITY\\",cn );
                            }
                        }

                    }

                    this.ParentContainer.DataChanged = false;
                    this.ParentContainer.btnApply.Enabled = false;
                }
            }
            catch (Exception e)
            {
                container.ShowError(e.Message);
            }
            // throw new NotImplementedException();
        }