0

I'm using EventLogSession, EventLogQuery and EventLogReader classes to query remote computer, when I use below code, it works fine:

var session = new EventLogSession(machineName, 
                                  null, null, null, 
                                  SessionAuthentication.Default);

But after I specify domain, username, password exactly as my local machine, then it does not work, throws

"Attempting to perform unauthorized operation" (UnauthorizedAccessException) exception.

The code I'm using is like this:

var password = new SecureString();
passwordString.ToCharArray().ForEach(ch => password.AppendChar(ch));
var session = new EventLogSession(machineName, 
                                  "domain", "username", password, 
                                   SessionAuthentication.Default);

MSDN says that when domain, username, password are all null, EventLogSession will user local machine's credential. But when I specify them in code, it's not working, how so?

BTW, I'm using Windows Server 2008 R2 to test the code. But I doubt that this is a OS-dependent thing.

Update: Turns out this is caused by my stupidity because I forget about the laziness of LINQ or rather yield return of C#. Cause for the convenience I implemented ForEach as following extension method

public static IEnumerable<T> ForEach<T>(this IEnumerable<T> sequence, Action<T> action)
{
    foreach (var item in sequence)
    {
        action(item);
        yield return item;
    }
}

This way, the ForEach will not actually execute the action delegate until it's been foreached. Hence I never call foreach on the char sequence, it will never execute therefore password is not initialized at all.

Apologize for bothering you guys, I marked tammy's answer as accepted.

imgen
  • 2,803
  • 7
  • 44
  • 64

1 Answers1

1

http://msdn.microsoft.com/en-us/library/bb671200(v=vs.90).aspx

public void QueryRemoteComputer()
    {
        string queryString = "*[System/Level=2]"; // XPATH Query
        SecureString pw = GetPassword();

        EventLogSession session = new EventLogSession(
            "RemoteComputerName",                               // Remote Computer
            "Domain",                                  // Domain
            "Username",                                // Username
            pw,
            SessionAuthentication.Default);

        pw.Dispose();

        // Query the Application log on the remote computer.
        EventLogQuery query = new EventLogQuery("Application", PathType.LogName, queryString);
        query.Session = session;

        try
        {
            EventLogReader logReader = new EventLogReader(query);

            // Display event info
            DisplayEventAndLogInformation(logReader);
        }
        catch (EventLogException e)
        {
            Console.WriteLine("Could not query the remote computer! " + e.Message);
            return;
        }
    }
tam tam
  • 1,870
  • 2
  • 21
  • 46