Hi all,\
I have small issue.
I wrote the code which check logon times of user on every domain controller, after that, it return the latest one.
The problem is that if any of domain controller is off/faulty - I get an error "server is not operational" and the function stops.
How to make it continue? for example: one of the DCs is not operational, so the function skips it and continue checking the logon times on other ones.

Please assist.

String Lastlogon(string username, string domainname)
        {
            try
            {
                {
                    DirectoryContext context = new DirectoryContext(DirectoryContextType.Domain,domainname);
                    DateTime latestLogon = DateTime.MinValue;
                    string servername = null;
                    DomainControllerCollection dcc = DomainController.FindAll(context);
                    foreach (DomainController dc in dcc)
                    {
                        DirectorySearcher ds;
                        using (dc)
                        using (ds = dc.GetDirectorySearcher())
                        {                      
                            ds.Filter = "(&(objectClass=user)(|(cn=" + username + ")(Mail=" + username + ")(userPrincipalName=" + username + ")(sAMAccountName=" + username + ")))";
                            ds.PropertiesToLoad.Add("lastLogon");
                            ds.SizeLimit = 1;
                            SearchResult sr = ds.FindOne();
                            if (sr != null)
                            {
                                DateTime lastLogon = DateTime.MinValue;
                                if (sr.Properties.Contains("lastLogon"))
                                {
                                    lastLogon = DateTime.FromFileTime((long)sr.Properties["lastLogon"][0]);
                                }
                                if (DateTime.Compare(lastLogon, latestLogon) > 0)
                                {
                                    latestLogon = lastLogon;
                                    servername = dc.Name;
                                }
                            }
                        }
                    }

                    return servername.ToString() + " - " + latestLogon.ToString();
                }
            }

Do you get an exception? If so use a try catch block to catch that specific exception and in the catch clause, use a continue; statement to process the next iteration of the loop.

and how to catch only "server not operational" exception?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.