Hej Udviklere,
Sidder og leger med et lille tool der henter en bunke pc navne ud fra AD, for derefter at pinge dem alle.
Det virker fint nok med undtagelse af at e.Reply nogle gange (tilsyneladende sporadisk) er null.
Jeg har søgt lidt på nettet og er tilsyneladende ikke den eneste der har haft problemet, men jeg kan ikke finde nogen løsning på det. Har i nogle idé'er?
using System;
using System.Collections;
using System.Collections.Generic;
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading;
namespace ConsoleApplication1
{
class PlayingWithAD
{
static SearchResultCollection results;
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] argv)
{
Console.WriteLine("Working... Please wait.");
DirectoryEntry de = new DirectoryEntry();
de.Path = "LDAP://<REMOVED>";
DirectorySearcher search = new DirectorySearcher(de);
search.Filter = "<REMOVED>"; //Only allows Computers to be returned in results.
search.PageSize = 1000; //Maximum amount returned by the server at one time, to prevent slowing the server if more than 1000 entries.
results = search.FindAll();
Console.WriteLine(results.Count.ToString());
ArrayList pingReply = new ArrayList();
AutoResetEvent resetEvent = new AutoResetEvent(false);
Ping p = null;
foreach (SearchResult res in results)
{
string[] temp = res.Path.Split(','); //temp[0] would contain the computer name ex: cn=computerName.
p = new Ping();
p.SendAsync(temp[0].Substring(10), resetEvent);
//Event handler must be attached each active ping.
p.PingCompleted += new PingCompletedEventHandler(p_PingCompleted);
}
//Clean up resources
de.Dispose();
p.Dispose();
timeout();
Console.ReadKey();
}
static int i = 0;
static ArrayList reply = new ArrayList();
private static void p_PingCompleted(object Sender, PingCompletedEventArgs e)
{
if (e.Reply != null)
reply.Add("Ping reply #" + ++i + " from: " + e.Reply.Address + " = " + e.Reply.Status);
else
{
reply.Add("Something went wrong: #" + ++i + " " + e.UserState + " | " + e.ToString());
SearchResult res = results[i];
string[] temp = res.Path.Split(',');
Console.WriteLine(i.ToString());
Console.WriteLine(temp[0].Substring(10));
}
timeout();
}
/// <summary>
/// If no new replys for the last 10 sec. then we assume there will be no more replys as ping timeout is set to 5 sec.
/// </summary>
static Timer t = new Timer(pingEnd);
private static void timeout()
{
t.Change(10000, 10000);
}
private static void pingEnd(Object state)
{
for (int i = 0; i < reply.Count; i++)
{
Console.WriteLine(reply[i]);
}
Console.WriteLine(DateTime.Now);
t.Dispose();
}
}
}