public void ImpersonatingWrapperTest() { var wrapped = new MyTarget() { ExpectedUser = Environment.MachineName + "\\" + NLogTestUser, }; var wrapper = new ImpersonatingTargetWrapper() { UserName = NLogTestUser, Password = NLogTestUserPassword, Domain = Environment.MachineName, WrappedTarget = wrapped, }; // wrapped.Initialize(null); wrapper.Initialize(null); var exceptions = new List<Exception>(); wrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); Assert.Equal(1, exceptions.Count); wrapper.WriteAsyncLogEvents( LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add), LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add), LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); Assert.Equal(4, exceptions.Count); wrapper.Flush(exceptions.Add); Assert.Equal(5, exceptions.Count); foreach (var ex in exceptions) { Assert.Null(ex); } wrapper.Close(); }
public void RevertToSelfTest() { var wrapped = new MyTarget() { ExpectedUser = Environment.UserDomainName + "\\" + Environment.UserName, }; WindowsIdentity originalIdentity = WindowsIdentity.GetCurrent(); try { var id = this.CreateWindowsIdentity(NLogTestUser, Environment.MachineName, NLogTestUserPassword, SecurityLogOnType.Interactive, LogOnProviderType.Default, SecurityImpersonationLevel.Identification); id.Impersonate(); WindowsIdentity changedIdentity = WindowsIdentity.GetCurrent(); Assert.AreEqual((Environment.MachineName + "\\" + NLogTestUser).ToLowerInvariant(), changedIdentity.Name.ToLowerInvariant()); var wrapper = new ImpersonatingTargetWrapper() { WrappedTarget = wrapped, RevertToSelf = true, }; // wrapped.Initialize(null); wrapper.Initialize(null); var exceptions = new List<Exception>(); wrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); Assert.AreEqual(1, exceptions.Count); wrapper.WriteAsyncLogEvents( LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add), LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add), LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); Assert.AreEqual(4, exceptions.Count); wrapper.Flush(exceptions.Add); Assert.AreEqual(5, exceptions.Count); foreach (var ex in exceptions) { Assert.IsNull(ex, Convert.ToString(ex)); } wrapper.Close(); } finally { // revert to self NativeMethods.RevertToSelf(); WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent(); Assert.AreEqual(originalIdentity.Name.ToLowerInvariant(), currentIdentity.Name.ToLowerInvariant()); } }