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.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();
        }
Esempio n. 2
0
        public void AutoFlushTargetWrapperSyncTest1()
        {
            var myTarget = new MyTarget();
            var wrapper = new AutoFlushTargetWrapper
            {
                WrappedTarget = myTarget,
            };

            myTarget.Initialize(null);
            wrapper.Initialize(null);
            var logEvent = new LogEventInfo();
            Exception lastException = null;
            bool continuationHit = false;
            AsyncContinuation continuation =
                ex =>
                    {
                        lastException = ex;
                        continuationHit = true;
                    };

            wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));

            Assert.IsTrue(continuationHit);
            Assert.IsNull(lastException);
            Assert.AreEqual(1, myTarget.FlushCount);
            Assert.AreEqual(1, myTarget.WriteCount);

            continuationHit = false;
            wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
            Assert.IsTrue(continuationHit);
            Assert.IsNull(lastException);
            Assert.AreEqual(2, myTarget.WriteCount);
            Assert.AreEqual(2, myTarget.FlushCount);
        }
Esempio n. 3
0
        public void CloseWithoutInitializeTest()
        {
            var target = new MyTarget();
            ((ISupportsInitialize)target).Close();

            // nothing was called
            Assert.AreEqual(0, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3);
        }
Esempio n. 4
0
        public void InitializeTest()
        {
            var target = new MyTarget();
            target.Initialize(null);

            // initialize was called once
            Assert.AreEqual(1, target.InitializeCount);
            Assert.AreEqual(1, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3);
        }
 public void AsyncTargetWrapperInitTest()
 {
     var myTarget = new MyTarget();
     var targetWrapper = new AsyncTargetWrapper(myTarget, 300, AsyncTargetWrapperOverflowAction.Grow);
     Assert.Equal(AsyncTargetWrapperOverflowAction.Grow, targetWrapper.OverflowAction);
     Assert.Equal(300, targetWrapper.QueueLimit);
     Assert.Equal(50, targetWrapper.TimeToSleepBetweenBatches);
     Assert.Equal(100, targetWrapper.BatchSize);
 }
Esempio n. 6
0
        public void AsyncTargetWrapperInitTest_WhenTimeToSleepBetweenBatchesIsEqualToZero_ShouldThrowNLogConfigurationException() {
            LogManager.ThrowConfigExceptions = true;

            var myTarget = new MyTarget();
            var targetWrapper = new AsyncTargetWrapper() {
                WrappedTarget = myTarget,
                TimeToSleepBetweenBatches = 0,
            };
            Assert.Throws<NLogConfigurationException>(() => targetWrapper.Initialize(null));
        }
Esempio n. 7
0
        public void DoubleCloseTest()
        {
            var target = new MyTarget();
            target.Initialize(null);
            target.Close();
            target.Close();

            // initialize and close were called once each
            Assert.Equal(1, target.InitializeCount);
            Assert.Equal(1, target.CloseCount);
            Assert.Equal(2, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3);
        }
Esempio n. 8
0
        public void DoubleCloseTest()
        {
            var target = new MyTarget();
            using (target.Initialize(CommonCfg))
            {
            }

            // initialize and close were called once each
            Assert.AreEqual(1, target.InitializeCount);
            Assert.AreEqual(1, target.CloseCount);
            Assert.AreEqual(2, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3);
        }
Esempio n. 9
0
        public void FlushTest()
        {
            var target = new MyTarget();
            List<Exception> exceptions = new List<Exception>();
            target.Initialize(CommonCfg);
            target.Flush(exceptions.Add);

            // flush was called
            Assert.AreEqual(1, target.FlushCount);
            Assert.AreEqual(2, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3);
            Assert.AreEqual(1, exceptions.Count);
            exceptions.ForEach(Assert.IsNull);
        }
Esempio n. 10
0
        public void AsyncTargetWrapperInitTest2()
        {
            var myTarget = new MyTarget();
            var targetWrapper = new AsyncTargetWrapper()
            {
                WrappedTarget = myTarget,
            };

            Assert.Equal(AsyncTargetWrapperOverflowAction.Discard, targetWrapper.OverflowAction);
            Assert.Equal(10000, targetWrapper.QueueLimit);
            Assert.Equal(50, targetWrapper.TimeToSleepBetweenBatches);
            Assert.Equal(100, targetWrapper.BatchSize);
        }
Esempio n. 11
0
        public void RoundRobinGroupTargetSyncTest1()
        {
            var myTarget1 = new MyTarget();
            var myTarget2 = new MyTarget();
            var myTarget3 = new MyTarget();

            var wrapper = new RoundRobinGroupTarget()
            {
                Targets = { myTarget1, myTarget2, myTarget3 },
            };

            ((ISupportsInitialize)myTarget1).Initialize();
            ((ISupportsInitialize)myTarget2).Initialize();
            ((ISupportsInitialize)myTarget3).Initialize();
            ((ISupportsInitialize)wrapper).Initialize();

            List<Exception> exceptions = new List<Exception>();

            // no exceptions
            for (int i = 0; i < 10; ++i)
            {
                wrapper.WriteLogEvent(LogEventInfo.CreateNullEvent(), exceptions.Add);
            }

            Assert.AreEqual(10, exceptions.Count);
            foreach (var e in exceptions)
            {
                Assert.IsNull(e);
            }

            Assert.AreEqual(4, myTarget1.WriteCount);
            Assert.AreEqual(3, myTarget2.WriteCount);
            Assert.AreEqual(3, myTarget3.WriteCount);

            Exception flushException = null;
            var flushHit = new ManualResetEvent(false);
            wrapper.Flush(ex => { flushException = ex; flushHit.Set(); });

            flushHit.WaitOne();
            if (flushException != null)
            {
                Assert.Fail(flushException.ToString());
            }

            Assert.AreEqual(1, myTarget1.FlushCount);
            Assert.AreEqual(1, myTarget2.FlushCount);
            Assert.AreEqual(1, myTarget3.FlushCount);
        }
        public void PostFilteringTargetWrapperUsingDefaultFilterTest()
        {
            var target = new MyTarget();
            var wrapper = new PostFilteringTargetWrapper()
            {
                WrappedTarget = target,
                Rules =
                {
                    // if we had any warnings, log debug too
                    new FilteringRule("level >= LogLevel.Warn", "level >= LogLevel.Debug"),

                    // when there is an error, emit everything
                    new FilteringRule
                    {
                        Exists = "level >= LogLevel.Error", 
                        Filter = "true",
                    },
                },

                // by default log info and above
                DefaultFilter = "level >= LogLevel.Info",
            };

            wrapper.Initialize(null);
            target.Initialize(null);

            var exceptions = new List<Exception>();
            
            var events = new []
            {
                new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Info, "Logger2", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Trace, "Logger1", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Info, "Logger3", "Hello").WithContinuation(exceptions.Add),
            };

            wrapper.WriteAsyncLogEvents(events);

            // make sure all Info events went through
            Assert.Equal(3, target.Events.Count);
            Assert.Same(events[1].LogEvent, target.Events[0]);
            Assert.Same(events[2].LogEvent, target.Events[1]);
            Assert.Same(events[5].LogEvent, target.Events[2]);

            Assert.Equal(events.Length, exceptions.Count);
        }
Esempio n. 13
0
        public void RoundRobinGroupTargetSyncTest1()
        {
            var myTarget1 = new MyTarget();
            var myTarget2 = new MyTarget();
            var myTarget3 = new MyTarget();

            var wrapper = new RoundRobinGroupTarget()
            {
                Targets = { myTarget1, myTarget2, myTarget3 },
            };

            myTarget1.Initialize(null);
            myTarget2.Initialize(null);
            myTarget3.Initialize(null);
            wrapper.Initialize(null);

            List<Exception> exceptions = new List<Exception>();

            // no exceptions
            for (int i = 0; i < 10; ++i)
            {
                wrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
            }

            Assert.Equal(10, exceptions.Count);
            foreach (var e in exceptions)
            {
                Assert.Null(e);
            }

            Assert.Equal(4, myTarget1.WriteCount);
            Assert.Equal(3, myTarget2.WriteCount);
            Assert.Equal(3, myTarget3.WriteCount);

            Exception flushException = null;
            var flushHit = new ManualResetEvent(false);
            wrapper.Flush(ex => { flushException = ex; flushHit.Set(); });

            flushHit.WaitOne();
            if (flushException != null)
            {
                Assert.True(false, flushException.ToString());
            }

            Assert.Equal(1, myTarget1.FlushCount);
            Assert.Equal(1, myTarget2.FlushCount);
            Assert.Equal(1, myTarget3.FlushCount);
        }
Esempio n. 14
0
        public void FirstTargetWorks_Write_AllEventsAreWrittenToFirstTarget()
        {
            var myTarget1 = new MyTarget();
            var myTarget2 = new MyTarget();
            var myTarget3 = new MyTarget();

            var wrapper = CreateAndInitializeFallbackGroupTarget(false, myTarget1, myTarget2, myTarget3);

            WriteAndAssertNoExceptions(wrapper);

            Assert.Equal(10, myTarget1.WriteCount);
            Assert.Equal(0, myTarget2.WriteCount);
            Assert.Equal(0, myTarget3.WriteCount);

            AssertNoFlushException(wrapper);
        }
Esempio n. 15
0
        public void FirstTwoTargetsFails_Write_ThirdTargetWritesAllEvents()
        {
            var myTarget1 = new MyTarget { FailCounter = 1 };
            var myTarget2 = new MyTarget { FailCounter = 1 };
            var myTarget3 = new MyTarget();

            var wrapper = CreateAndInitializeFallbackGroupTarget(false, myTarget1, myTarget2, myTarget3);

            WriteAndAssertNoExceptions(wrapper);

            Assert.Equal(1, myTarget1.WriteCount);
            Assert.Equal(1, myTarget2.WriteCount);
            Assert.Equal(10, myTarget3.WriteCount);

            AssertNoFlushException(wrapper);
        }
        public void PostFilteringTargetWrapperNoFiltersDefined()
        {
            var target = new MyTarget();
            var wrapper = new PostFilteringTargetWrapper()
            {
                WrappedTarget = target,
            };

            ((ISupportsInitialize)wrapper).Initialize();
            ((ISupportsInitialize)target).Initialize();

            var events = new LogEventInfo[]
            {
                new LogEventInfo(LogLevel.Debug, "Logger1", "Hello"),
                new LogEventInfo(LogLevel.Info, "Logger1", "Hello"),
                new LogEventInfo(LogLevel.Info, "Logger2", "Hello"),
                new LogEventInfo(LogLevel.Debug, "Logger1", "Hello"),
                new LogEventInfo(LogLevel.Trace, "Logger1", "Hello"),
                new LogEventInfo(LogLevel.Info, "Logger3", "Hello"),
                new LogEventInfo(LogLevel.Error, "Logger1", "Hello"),
            };

            var exceptions = new List<Exception>();

            var continuations = new AsyncContinuation[events.Length];
            for (int i = 0; i < continuations.Length; ++i)
            {
                continuations[i] = exceptions.Add;
            }

            wrapper.WriteLogEvents(events, continuations);

            // make sure all events went through
            Assert.AreEqual(7, target.Events.Count);
            Assert.AreSame(events[0], target.Events[0]);
            Assert.AreSame(events[1], target.Events[1]);
            Assert.AreSame(events[2], target.Events[2]);
            Assert.AreSame(events[3], target.Events[3]);
            Assert.AreSame(events[4], target.Events[4]);
            Assert.AreSame(events[5], target.Events[5]);
            Assert.AreSame(events[6], target.Events[6]);

            Assert.AreEqual(continuations.Length, exceptions.Count, "Some continuations were not invoked.");
        }
Esempio n. 17
0
        public void RetryingTargetWrapperTest1()
        {
            var target = new MyTarget();
            var wrapper = new RetryingTargetWrapper()
            {
                WrappedTarget = target,
                RetryCount = 10,
                RetryDelayMilliseconds = 1,
            };

            ((ISupportsInitialize)wrapper).Initialize();
            ((ISupportsInitialize)target).Initialize();

            var events = new LogEventInfo[]
            {
                new LogEventInfo(LogLevel.Debug, "Logger1", "Hello"),
                new LogEventInfo(LogLevel.Info, "Logger1", "Hello"),
                new LogEventInfo(LogLevel.Info, "Logger2", "Hello"),
            };

            var exceptions = new List<Exception>();

            var continuations = new AsyncContinuation[events.Length];
            for (int i = 0; i < continuations.Length; ++i)
            {
                continuations[i] = exceptions.Add;
            }

            wrapper.WriteLogEvents(events, continuations);

            // make sure all events went through
            Assert.AreEqual(3, target.Events.Count);
            Assert.AreSame(events[0], target.Events[0]);
            Assert.AreSame(events[1], target.Events[1]);
            Assert.AreSame(events[2], target.Events[2]);

            Assert.AreEqual(continuations.Length, exceptions.Count, "Some continuations were not invoked.");

            // make sure there were no exception
            foreach (var ex in exceptions)
            {
                Assert.IsNull(ex);
            }
        }
Esempio n. 18
0
        public void InitializeFailedTest()
        {
            var target = new MyTarget();
            target.ThrowOnInitialize = true;

            LogManager.ThrowExceptions = true;


            Assert.Throws<InvalidOperationException>(() => target.Initialize(null));

            // after exception in Initialize(), the target becomes non-functional and all Write() operations
            var exceptions = new List<Exception>();
            target.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
            Assert.Equal(0, target.WriteCount);
            Assert.Equal(1, exceptions.Count);
            Assert.NotNull(exceptions[0]);
            Assert.Equal("Target " + target + " failed to initialize.", exceptions[0].Message);
            Assert.Equal("Init error.", exceptions[0].InnerException.Message);
        }
Esempio n. 19
0
        public void FallbackGroupTargetSyncTest2()
        {
            // fail once
            var myTarget1 = new MyTarget() { FailCounter = 1 };
            var myTarget2 = new MyTarget();
            var myTarget3 = new MyTarget();

            var wrapper = new FallbackGroupTarget()
            {
                Targets = { myTarget1, myTarget2, myTarget3 },
            };

            wrapper.Initialize(CommonCfg);

            List<Exception> exceptions = new List<Exception>();

            // no exceptions
            for (int i = 0; i < 10; ++i)
            {
                wrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
            }

            Assert.AreEqual(10, exceptions.Count);
            foreach (var e in exceptions)
            {
                Assert.IsNull(e);
            }

            Assert.AreEqual(1, myTarget1.WriteCount);
            Assert.AreEqual(10, myTarget2.WriteCount);
            Assert.AreEqual(0, myTarget3.WriteCount);

            Exception flushException = null;
            var flushHit = new ManualResetEvent(false);
            wrapper.Flush(ex => { flushException = ex; flushHit.Set(); });

            flushHit.WaitOne();
            if (flushException != null)
            {
                Assert.Fail(flushException.ToString());
            }
        }
Esempio n. 20
0
        public void RepeatingTargetWrapperTest1()
        {
            var target = new MyTarget();
            var wrapper = new RepeatingTargetWrapper()
            {
                WrappedTarget = target,
                RepeatCount = 3,
            };
            ((ISupportsInitialize)wrapper).Initialize();
            ((ISupportsInitialize)target).Initialize();

            var events = new LogEventInfo[]
            {
                new LogEventInfo(LogLevel.Debug, "Logger1", "Hello"),
                new LogEventInfo(LogLevel.Info, "Logger1", "Hello"),
                new LogEventInfo(LogLevel.Info, "Logger2", "Hello"),
            };

            var exceptions = new List<Exception>();

            var continuations = new AsyncContinuation[events.Length];
            for (int i = 0; i < continuations.Length; ++i)
            {
                continuations[i] = exceptions.Add;
            }

            wrapper.WriteLogEvents(events, continuations);

            // make sure all events went through and were replicated 3 times
            Assert.AreEqual(9, target.Events.Count);
            Assert.AreSame(events[0], target.Events[0]);
            Assert.AreSame(events[0], target.Events[1]);
            Assert.AreSame(events[0], target.Events[2]);
            Assert.AreSame(events[1], target.Events[3]);
            Assert.AreSame(events[1], target.Events[4]);
            Assert.AreSame(events[1], target.Events[5]);
            Assert.AreSame(events[2], target.Events[6]);
            Assert.AreSame(events[2], target.Events[7]);
            Assert.AreSame(events[2], target.Events[8]);

            Assert.AreEqual(continuations.Length, exceptions.Count, "Some continuations were not invoked.");
        }
Esempio n. 21
0
        public void RetryingTargetWrapperTest1()
        {
            var target = new MyTarget();
            var wrapper = new RetryingTargetWrapper()
            {
                WrappedTarget = target,
                RetryCount = 10,
                RetryDelayMilliseconds = 1,
            };

            wrapper.Initialize(null);
            target.Initialize(null);

            var exceptions = new List<Exception>();

            var events = new []
            {
                new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Info, "Logger2", "Hello").WithContinuation(exceptions.Add),
            };

            wrapper.WriteAsyncLogEvents(events);

            // make sure all events went through
            Assert.AreEqual(3, target.Events.Count);
            Assert.AreSame(events[0].LogEvent, target.Events[0]);
            Assert.AreSame(events[1].LogEvent, target.Events[1]);
            Assert.AreSame(events[2].LogEvent, target.Events[2]);

            Assert.AreEqual(events.Length, exceptions.Count, "Some continuations were not invoked.");

            // make sure there were no exception
            foreach (var ex in exceptions)
            {
                Assert.IsNull(ex);
            }
        }
Esempio n. 22
0
        void CheckVisibility(IntVector3 location, TileData oldData, TileData newData)
        {
            var env = m_environment;

            var initLocs = new IntVector3[] { location };
            var target = new MyTarget(env, this);

            var bfs = new BFS(initLocs, target);

            var revealed = bfs.Find().ToList();

            //Debug.Print("Revealed {0} tiles: {1}", revealed.Count, string.Join(", ", revealed.Select(p => p.ToString())));

            if (revealed.Count == 0)
                return;

            foreach (var p in revealed)
                SetVisible(p);

            // Send new tiles

            var msg = new Messages.MapDataTerrainsListMessage()
            {
                Environment = env.ObjectID,
                TileDataList = revealed.Select(l => new KeyValuePair<IntVector3, TileData>(l, env.GetTileData(l))).ToArray(),
            };

            m_player.Send(msg);

            // Send new objects

            foreach (var ob in revealed.SelectMany(env.GetContents))
            {
                var vis = m_player.GetObjectVisibility(ob);
                Debug.Assert(vis != ObjectVisibility.None);
                ob.SendTo(m_player, vis);
            }
        }
        public void FilteringTargetWrapperSyncTest1()
        {
            var myMockCondition = new MyMockCondition(true);
            var myTarget = new MyTarget();
            var wrapper = new FilteringTargetWrapper
            {
                WrappedTarget = myTarget,
                Condition = myMockCondition,
            };

            myTarget.Initialize(null);
            wrapper.Initialize(null);
            var logEvent = new LogEventInfo();
            Exception lastException = null;
            bool continuationHit = false;
            AsyncContinuation continuation =
                ex =>
                    {
                        lastException = ex;
                        continuationHit = true;
                    };

            wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));

            Assert.Equal(1, myMockCondition.CallCount);

            Assert.True(continuationHit);
            Assert.Null(lastException);
            Assert.Equal(1, myTarget.WriteCount);

            continuationHit = false;
            wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
            Assert.True(continuationHit);
            Assert.Null(lastException);
            Assert.Equal(2, myTarget.WriteCount);
            Assert.Equal(2, myMockCondition.CallCount);
        }
Esempio n. 24
0
        public void PostFilteringTargetWrapperNoFiltersDefined()
        {
            var target = new MyTarget();
            var wrapper = new PostFilteringTargetWrapper()
            {
                WrappedTarget = target,
            };

            wrapper.Initialize(CommonCfg);

            var exceptions = new List<Exception>();

            var events = new[]
            {
                new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Info, "Logger2", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Trace, "Logger1", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Info, "Logger3", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Error, "Logger1", "Hello").WithContinuation(exceptions.Add),
            };

            wrapper.WriteAsyncLogEvents(events);

            // make sure all events went through
            Assert.AreEqual(7, target.Events.Count);
            Assert.AreSame(events[0].LogEvent, target.Events[0]);
            Assert.AreSame(events[1].LogEvent, target.Events[1]);
            Assert.AreSame(events[2].LogEvent, target.Events[2]);
            Assert.AreSame(events[3].LogEvent, target.Events[3]);
            Assert.AreSame(events[4].LogEvent, target.Events[4]);
            Assert.AreSame(events[5].LogEvent, target.Events[5]);
            Assert.AreSame(events[6].LogEvent, target.Events[6]);

            Assert.AreEqual(events.Length, exceptions.Count, "Some continuations were not invoked.");
        }
Esempio n. 25
0
        public void AsyncTargetWrapperSyncTest1()
        {
            var myTarget = new MyTarget();
            var targetWrapper = new AsyncTargetWrapper
            {
                WrappedTarget = myTarget,
            };
            targetWrapper.Initialize(null);
            myTarget.Initialize(null);

            var logEvent = new LogEventInfo();
            Exception lastException = null;
            ManualResetEvent continuationHit = new ManualResetEvent(false);
            Thread continuationThread = null;
            AsyncContinuation continuation =
                ex =>
                    {
                        lastException = ex;
                        continuationThread = Thread.CurrentThread;
                        continuationHit.Set();
                    };

            targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));

            // continuation was not hit 
            Assert.True(continuationHit.WaitOne(2000));
            Assert.NotSame(continuationThread, Thread.CurrentThread);
            Assert.Null(lastException);
            Assert.Equal(1, myTarget.WriteCount);

            continuationHit.Reset();
            targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
            continuationHit.WaitOne();
            Assert.NotSame(continuationThread, Thread.CurrentThread);
            Assert.Null(lastException);
            Assert.Equal(2, myTarget.WriteCount);
        }
        public void RepeatingTargetWrapperTest2()
        {
            var target = new MyTarget();
            target.ThrowExceptions = true;
            var wrapper = new RepeatingTargetWrapper()
            {
                WrappedTarget = target,
                RepeatCount = 3,
            };
            wrapper.Initialize(null);
            target.Initialize(null);

            var exceptions = new List<Exception>();

            var events = new []
            {
                new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Info, "Logger2", "Hello").WithContinuation(exceptions.Add),
            };

            wrapper.WriteAsyncLogEvents(events);

            // make sure all events went through but were registered only once
            // since repeating target wrapper will not repeat in case of exception.
            Assert.Equal(3, target.Events.Count);
            Assert.Same(events[0].LogEvent, target.Events[0]);
            Assert.Same(events[1].LogEvent, target.Events[1]);
            Assert.Same(events[2].LogEvent, target.Events[2]);

            Assert.Equal(events.Length, exceptions.Count);
            foreach (var exception in exceptions)
            {
                Assert.NotNull(exception);
                Assert.Equal("Some exception has occurred.", exception.Message);
            }
        }
        public void RepeatingTargetWrapperTest1()
        {
            var target = new MyTarget();
            var wrapper = new RepeatingTargetWrapper()
            {
                WrappedTarget = target,
                RepeatCount = 3,
            };
            wrapper.Initialize(null);
            target.Initialize(null);

            var exceptions = new List<Exception>();

            var events = new[]
            {
                new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Info, "Logger2", "Hello").WithContinuation(exceptions.Add),
            };

            wrapper.WriteAsyncLogEvents(events);

            // make sure all events went through and were replicated 3 times
            Assert.Equal(9, target.Events.Count);
            Assert.Same(events[0].LogEvent, target.Events[0]);
            Assert.Same(events[0].LogEvent, target.Events[1]);
            Assert.Same(events[0].LogEvent, target.Events[2]);
            Assert.Same(events[1].LogEvent, target.Events[3]);
            Assert.Same(events[1].LogEvent, target.Events[4]);
            Assert.Same(events[1].LogEvent, target.Events[5]);
            Assert.Same(events[2].LogEvent, target.Events[6]);
            Assert.Same(events[2].LogEvent, target.Events[7]);
            Assert.Same(events[2].LogEvent, target.Events[8]);

            Assert.Equal(events.Length, exceptions.Count);
        }
Esempio n. 28
0
        public void When_Logging_LogEvent_Without_Level_Defined_No_Exception_Should_Be_Thrown()
        {
            var config = new LoggingConfiguration();
            var target = new MyTarget();
            config.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, target));
            LogManager.Configuration = config;
            var logger = LogManager.GetLogger("A");

            Assert.Throws<InvalidOperationException>(() => logger.Log(new LogEventInfo()));
        }
Esempio n. 29
0
    private static void CombatRotation()
    {
        if (Me.ManaPercentage < MageLevelSettings.CurrentSetting.Manastone)
        {
            _foodManager.UseManaStone();
        }

        if (MageLevelSettings.CurrentSetting.Sheep)
        {
            //Poly Management
            if (Extension.GetAttackingUnits(5).Count() > 1 && Polymorph.KnownSpell)
            {
                Extension.Frameunlock();
                Logging.Write("2 Attackers, one will get Feared");
                WoWUnit mainTarget = Extension.GetAttackingUnits(5).Where(u => u.HealthPercent == Extension.GetAttackingUnits(5).Min(x => x.HealthPercent)).FirstOrDefault();
                WoWUnit polyTarget = Extension.GetAttackingUnits(5).Where(u => u.HealthPercent == Extension.GetAttackingUnits(5).Max(x => x.HealthPercent)).FirstOrDefault();
                if (polyTarget != mainTarget && !polyTarget.HaveBuff("Polymorph"))
                {
                    ObjectManager.Me.FocusGuid = polyTarget.Guid;
                    Extension.FightSpell(Polymorph, true);
                    Logging.Write("Cast Poly on " + polyTarget);
                    Thread.Sleep(1000);
                }
            }
        }
        if (Extension.InterruptableUnit(20f) != null && CounterSpell.KnownSpell && CounterSpell.IsSpellUsable)
        {
            Logging.Write("Interrupt Target found");
            ObjectManager.Me.FocusGuid = Extension.InterruptableUnit(20f).Guid;
            Logging.Write("Interrupt Target Set" + Extension.InterruptableUnit(20f).Guid);
            Extension.FightSpell(CounterSpell, true);
        }
        if (Me.HaveBuff("Fireball!"))
        {
            Extension.FightSpell(FrostFirebolt);
        }
        if (!IceBarrier.IsSpellUsable && !IceBlock.IsSpellUsable)
        {
            Extension.BuffSpell(ColdSnap);
        }
        if (Me.HealthPercent < 15 && Extension.GetAttackingUnits(20).Count() >= 2)
        {
            Extension.BuffSpell(Evocation);
        }
        if (Me.HealthPercent < 14 && !IceBarrier.IsSpellUsable)
        {
            Extension.BuffSpell(IceBlock);
        }
        if (Me.HealthPercent < 95)
        {
            Extension.BuffSpell(IceBarrier);
        }
        if (Extension.GetAttackingUnits(25).Count() >= 3 || MyTarget.IsElite)
        {
            Extension.FightSpell(MirrorImage);
            Extension.FightSpell(SummonWaterElemental);
        }
        if (Extension.GetAttackingUnits(25).Count() >= 2 || MyTarget.IsElite)
        {
            Extension.BuffSpell(IcyVeins);
            Extension.FightSpell(SummonWaterElemental);
        }
        Extension.FightSpell(DeepFreeze);
        if (Me.HaveBuff("Fingers of Frost") || MyTarget.HaveBuff(FrostNova.Id))
        {
            Extension.FightSpell(IceLance);
        }
        if (!Frostbolt.KnownSpell)
        {
            Extension.FightSpell(Fireball, false, false, false, false);
        }
        Extension.FightSpell(Frostbolt, false, false, false, false);
        if (MyTarget.HealthPercent < 10)
        {
            Extension.FightSpell(FireBlast);
        }
        if (MyTarget.GetDistance < 7)
        {
            Extension.FightSpell(FrostNova);
        }
        Extension.Frameunlock();
    }
Esempio n. 30
0
        public void FallbackGroupTargetSyncTest6()
        {
            // fail once
            var myTarget1 = new MyTarget()
            {
                FailCounter = 10
            };
            var myTarget2 = new MyTarget()
            {
                FailCounter = 3
            };
            var myTarget3 = new MyTarget()
            {
                FailCounter = 3
            };

            var wrapper = new FallbackGroupTarget()
            {
                Targets = { myTarget1, myTarget2, myTarget3 },
                ReturnToFirstOnSuccess = true,
            };

            myTarget1.Initialize(null);
            myTarget2.Initialize(null);
            myTarget3.Initialize(null);
            wrapper.Initialize(null);

            List <Exception> exceptions = new List <Exception>();

            // no exceptions
            for (int i = 0; i < 10; ++i)
            {
                wrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
            }

            Assert.AreEqual(10, exceptions.Count);
            for (int i = 0; i < 10; ++i)
            {
                if (i < 3)
                {
                    // for the first 3 rounds, no target is available
                    Assert.IsNotNull(exceptions[i]);
                    Assert.IsInstanceOfType(typeof(InvalidOperationException), exceptions[i]);
                    Assert.AreEqual("Some failure.", exceptions[i].Message);
                }
                else
                {
                    Assert.IsNull(exceptions[i], Convert.ToString(exceptions[i]));
                }
            }

            Assert.AreEqual(10, myTarget1.WriteCount);
            Assert.AreEqual(10, myTarget2.WriteCount);
            Assert.AreEqual(3, myTarget3.WriteCount);

            Exception flushException = null;
            var       flushHit       = new ManualResetEvent(false);

            wrapper.Flush(ex => { flushException = ex; flushHit.Set(); });

            flushHit.WaitOne();
            if (flushException != null)
            {
                Assert.Fail(flushException.ToString());
            }

            Assert.AreEqual(1, myTarget1.FlushCount);
            Assert.AreEqual(1, myTarget2.FlushCount);
            Assert.AreEqual(1, myTarget3.FlushCount);
        }
Esempio n. 31
0
        public void RetryingTargetWrapperTest2()
        {
            var target = new MyTarget()
            {
                ThrowExceptions = 6,
            };

            var wrapper = new RetryingTargetWrapper()
            {
                WrappedTarget = target,
                RetryCount = 4,
                RetryDelayMilliseconds = 1,
            };

            wrapper.Initialize(null);
            target.Initialize(null);

            var exceptions = new List<Exception>();

            var events = new []
            {
                new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Info, "Logger2", "Hello").WithContinuation(exceptions.Add),
            };

            var internalLogOutput = RunAndCaptureInternalLog(() => wrapper.WriteAsyncLogEvents(events), LogLevel.Trace);
            string expectedLogOutput = @"Warn Error while writing to 'MyTarget': System.InvalidOperationException: Some exception has ocurred.. Try 1/4
Warn Error while writing to 'MyTarget': System.InvalidOperationException: Some exception has ocurred.. Try 2/4
Warn Error while writing to 'MyTarget': System.InvalidOperationException: Some exception has ocurred.. Try 3/4
Warn Error while writing to 'MyTarget': System.InvalidOperationException: Some exception has ocurred.. Try 4/4
Warn Too many retries. Aborting.
Warn Error while writing to 'MyTarget': System.InvalidOperationException: Some exception has ocurred.. Try 1/4
Warn Error while writing to 'MyTarget': System.InvalidOperationException: Some exception has ocurred.. Try 2/4
";
            Assert.AreEqual(expectedLogOutput, internalLogOutput);

            // first event does not get to wrapped target because of too many attempts.
            // second event gets there in 3rd retry
            // and third event gets there immediately
            Assert.AreEqual(2, target.Events.Count);
            Assert.AreSame(events[1].LogEvent, target.Events[0]);
            Assert.AreSame(events[2].LogEvent, target.Events[1]);

            Assert.AreEqual(events.Length, exceptions.Count, "Some continuations were not invoked.");

            Assert.IsNotNull(exceptions[0]);
            Assert.AreEqual("Some exception has ocurred.", exceptions[0].Message);
            Assert.IsNull(exceptions[1]);
            Assert.IsNull(exceptions[2]);
        }
Esempio n. 32
0
        /// <summary>
        /// Test Fix for https://github.com/NLog/NLog/issues/1069
        /// </summary>
        private void AsyncTargetWrapperSyncTest_WhenTimeToSleepBetweenBatchesIsEqualToZero(bool forceLockingQueue)
        {
            LogManager.ThrowConfigExceptions = true;

            var myTarget      = new MyTarget();
            var targetWrapper = new AsyncTargetWrapper()
            {
                WrappedTarget             = myTarget,
                TimeToSleepBetweenBatches = 0,
#if NET4_5
                ForceLockingQueue   = forceLockingQueue,
                OptimizeBufferReuse = !forceLockingQueue,
#endif
                BatchSize  = 3,
                QueueLimit = 5, // Will make it "sleep" between every second write
                FullBatchSizeWriteLimit = 1,
                OverflowAction          = AsyncTargetWrapperOverflowAction.Block
            };

            targetWrapper.Initialize(null);
            myTarget.Initialize(null);

            try
            {
                int flushCounter = 0;
                AsyncContinuation flushHandler = (ex) => { ++flushCounter; };

                var itemPrepareList = new List <AsyncLogEventInfo>(500);
                var itemWrittenList = new List <int>(itemPrepareList.Capacity);
                for (int i = 0; i < itemPrepareList.Capacity; ++i)
                {
                    var  logEvent      = new LogEventInfo();
                    int  sequenceID    = logEvent.SequenceID;
                    bool blockConsumer = (itemPrepareList.Capacity / 2) == i;  // Force producers to get into blocking-mode
                    itemPrepareList.Add(logEvent.WithContinuation((ex) => { if (blockConsumer)
                                                                            {
                                                                                Thread.Sleep(125);
                                                                            }
                                                                            itemWrittenList.Add(sequenceID); }));
                }

                var eventProducer0 = new ManualResetEvent(false);
                var eventProducer1 = new ManualResetEvent(false);
                ParameterizedThreadStart producerMethod = (s) =>
                {
                    var eventProducer = (ManualResetEvent)s;
                    if (eventProducer != null)
                    {
                        eventProducer.Set();    // Signal we are ready
                    }
                    int partitionNo = ReferenceEquals(eventProducer, eventProducer1) ? 1 : 0;
                    for (int i = 0; i < itemPrepareList.Count; ++i)
                    {
                        if (i % 2 == partitionNo)
                        {
                            targetWrapper.WriteAsyncLogEvent(itemPrepareList[i]);
                        }
                    }
                };

                Thread producer0 = new Thread(producerMethod);
                producer0.IsBackground = true;
                Thread producer1 = new Thread(producerMethod);
                producer1.IsBackground = true;
                producer1.Start(eventProducer0);
                producer0.Start(eventProducer1);
                Assert.True(eventProducer0.WaitOne(5000), "Producer0 Start Timeout");
                Assert.True(eventProducer1.WaitOne(5000), "Producer1 Start Timeout");

                long startTicks = Environment.TickCount;

                Assert.True(producer0.Join(5000), "Producer0 Complete Timeout");  // Wait for producer0 to complete
                Assert.True(producer1.Join(5000), "Producer1 Complete Timeout");  // Wait for producer1 to complete

                long elapsedMilliseconds = Environment.TickCount - startTicks;

                targetWrapper.Flush(flushHandler);

                for (int i = 0; i < itemPrepareList.Count * 2 && itemWrittenList.Count != itemPrepareList.Count; ++i)
                {
                    Thread.Sleep(1);
                }

                Assert.Equal(itemPrepareList.Count, itemWrittenList.Count);

                int producer0sequenceID = 0;
                int producer1sequenceID = 0;
                for (int i = 1; i < itemWrittenList.Count; ++i)
                {
                    if (itemWrittenList[i] % 2 == 0)
                    {
                        Assert.True(producer0sequenceID < itemWrittenList[i], "Producer0 invalid sequence");
                        producer0sequenceID = itemWrittenList[i];
                    }
                    else
                    {
                        Assert.True(producer1sequenceID < itemWrittenList[i], "Producer1 invalid sequence");
                        producer1sequenceID = itemWrittenList[i];
                    }
                }

#if NET4_5
                if (!IsAppVeyor())  // Skip timing test when running within OpenCover.Console.exe
#endif
                Assert.InRange(elapsedMilliseconds, 0, 975);

                targetWrapper.Flush(flushHandler);
                for (int i = 0; i < 2000 && flushCounter != 2; ++i)
                {
                    Thread.Sleep(1);
                }
                Assert.Equal(2, flushCounter);
            }
            finally
            {
                myTarget.Close();
                targetWrapper.Close();
            }
        }
Esempio n. 33
0
 private static void ShadowRotation()
 {
     Extension.BuffSpell(ShadowForm);
     if (Extension.GetAttackingUnits(6).Count() > 1)
     {
         Extension.FightSpell(PsychicScream);
     }
     if (Extension.GetAttackingUnits(6).Count() > 1)
     {
         Extension.BuffSpell(InnerFire);
     }
     if (_icanusewand && Me.ManaPercentage < 5)
     {
         Extension.FightSpell(UseWand);
     }
     if (_icanusewand &&
         PriestLevelSettings.CurrentSetting.UseWand &&
         MyTarget.HealthPercent < PriestLevelSettings.CurrentSetting.UseWandTresh)
     {
         Extension.FightSpell(UseWand);
         return;
     }
     if (Me.Level >= 10 && Me.Level < 20)
     {
         Extension.FightSpell(MindBlast);
         if (!MindBlast.IsSpellUsable)
         {
             Extension.FightSpell(ShadowWordPain);
         }
         if (!MindBlast.IsSpellUsable)
         {
             Extension.FightSpell(Smite);
         }
     }
     if (Me.Level > 19 && Me.Level < 30)
     {
         if (Extension.GetAttackingUnits(20).Count() > 1 && !Me.IsStunned)
         {
             WoWUnit MainTarget = Extension.GetAttackingUnits(20).Where(u => u.HealthPercent == Extension.GetAttackingUnits(20).Min(x => x.HealthPercent)).FirstOrDefault();
             WoWUnit DotTarget  = Extension.GetAttackingUnits(20).Where(u => u.HealthPercent == Extension.GetAttackingUnits(20).Max(x => x.HealthPercent)).FirstOrDefault();
             if (DotTarget != MainTarget)
             {
                 ObjectManager.Me.FocusGuid = DotTarget.Guid;
                 Extension.FightSpell(ShadowWordPain, true, true);
                 Logging.Write("Cast Dot on " + DotTarget);
                 Thread.Sleep(50);
             }
         }
         Extension.FightSpell(HolyFire);
         Extension.FightSpell(DevouringPlague);
         Extension.FightSpell(ShadowWordPain);
         if (MyTarget.HaveBuff(DevouringPlague.Id) && MyTarget.HaveBuff(ShadowWordPain.Id) && PriestLevelSettings.CurrentSetting.ShadowUseMindflay)
         {
             Extension.FightSpell(MindFlay);
         }
         Extension.FightSpell(MindBlast);
     }
     if (Me.Level > 29 && Me.Level < 40)
     {
         //Vampiric Touch > Vampiric Embrace > Mind Blast > Mind Flay
         if (Extension.GetAttackingUnits(20).Count() > 1 && !Me.IsStunned)
         {
             WoWUnit MainTarget = Extension.GetAttackingUnits(20).Where(u => u.HealthPercent == Extension.GetAttackingUnits(20).Min(x => x.HealthPercent)).FirstOrDefault();
             WoWUnit DotTarget  = Extension.GetAttackingUnits(20).Where(u => u.HealthPercent == Extension.GetAttackingUnits(20).Max(x => x.HealthPercent)).FirstOrDefault();
             if (DotTarget != MainTarget)
             {
                 ObjectManager.Me.FocusGuid = DotTarget.Guid;
                 Extension.FightSpell(ShadowWordPain, true, true);
                 Logging.Write("Cast Dot on " + DotTarget);
                 Thread.Sleep(50);
             }
         }
         Extension.FightSpell(HolyFire);
         Extension.FightSpell(DevouringPlague);
         if (MyTarget.HaveBuff(DevouringPlague.Id))
         {
             Extension.BuffSpell(VampiricEmbrace);
         }
         Extension.FightSpell(ShadowWordPain);
         if (MyTarget.HaveBuff(DevouringPlague.Id) && MyTarget.HaveBuff(ShadowWordPain.Id) && PriestLevelSettings.CurrentSetting.ShadowUseMindflay)
         {
             Extension.FightSpell(MindFlay);
         }
         Extension.FightSpell(MindBlast);
     }
     if (Me.Level > 39 && Me.Level < 50)
     {
         //Vampiric Touch > Vampiric Embrace > Mind Blast > Mind Flay
         if (Extension.GetAttackingUnits(20).Count() > 1 && !Me.IsStunned)
         {
             WoWUnit MainTarget = Extension.GetAttackingUnits(20).Where(u => u.HealthPercent == Extension.GetAttackingUnits(20).Min(x => x.HealthPercent)).FirstOrDefault();
             WoWUnit DotTarget  = Extension.GetAttackingUnits(20).Where(u => u.HealthPercent == Extension.GetAttackingUnits(20).Max(x => x.HealthPercent)).FirstOrDefault();
             if (DotTarget != MainTarget)
             {
                 ObjectManager.Me.FocusGuid = DotTarget.Guid;
                 Extension.FightSpell(ShadowWordPain, true, true);
                 Logging.Write("Cast Dot on " + DotTarget);
                 Thread.Sleep(50);
             }
         }
         if (PriestLevelSettings.CurrentSetting.ShadowDPUse)
         {
             Extension.FightSpell(DevouringPlague);
         }
         Extension.FightSpell(ShadowWordPain);
         if (MyTarget.HaveBuff(ShadowWordPain.Id))
         {
             Extension.BuffSpell(VampiricEmbrace);
         }
         Extension.FightSpell(MindBlast);
         if (MyTarget.HaveBuff(ShadowWordPain.Id) && PriestLevelSettings.CurrentSetting.ShadowUseMindflay)
         {
             Extension.FightSpell(MindFlay);
         }
     }
     if (Me.Level > 49 && Me.Level < 60)
     {
         //Vampiric Touch > Vampiric Embrace > Mind Blast > Mind Flay
         if (Extension.GetAttackingUnits(20).Count() > 1 && !Me.IsStunned)
         {
             WoWUnit MainTarget = Extension.GetAttackingUnits(20).Where(u => u.HealthPercent == Extension.GetAttackingUnits(20).Min(x => x.HealthPercent)).FirstOrDefault();
             WoWUnit DotTarget  = Extension.GetAttackingUnits(20).Where(u => u.HealthPercent == Extension.GetAttackingUnits(20).Max(x => x.HealthPercent)).FirstOrDefault();
             if (DotTarget != MainTarget)
             {
                 ObjectManager.Me.FocusGuid = DotTarget.Guid;
                 Extension.FightSpell(ShadowWordPain, true, true);
                 Logging.Write("Cast Dot on " + DotTarget);
                 Thread.Sleep(50);
             }
         }
         if (PriestLevelSettings.CurrentSetting.ShadowDPUse)
         {
             Extension.FightSpell(DevouringPlague);
         }
         Extension.FightSpell(VampiricTouch);
         if (MyTarget.HaveBuff(VampiricTouch.Id))
         {
             Extension.FightSpell(ShadowWordPain);
         }
         Extension.BuffSpell(VampiricEmbrace);
         Extension.FightSpell(MindBlast);
         if (MyTarget.HaveBuff(VampiricTouch.Id) &&
             MyTarget.HaveBuff(ShadowWordPain.Id) && PriestLevelSettings.CurrentSetting.ShadowUseMindflay)
         {
             Extension.FightSpell(MindFlay);
         }
     }
     if (Me.Level > 59)
     {
         //Vampiric Touch > Vampiric Embrace > Mind Blast > Mind Flay
         if (Extension.GetAttackingUnits(20).Count() > 1 && !Me.IsStunned)
         {
             WoWUnit MainTarget = Extension.GetAttackingUnits(20).Where(u => u.HealthPercent == Extension.GetAttackingUnits(20).Min(x => x.HealthPercent)).FirstOrDefault();
             WoWUnit DotTarget  = Extension.GetAttackingUnits(20).Where(u => u.HealthPercent == Extension.GetAttackingUnits(20).Max(x => x.HealthPercent)).FirstOrDefault();
             if (DotTarget != MainTarget)
             {
                 ObjectManager.Me.FocusGuid = DotTarget.Guid;
                 Extension.FightSpell(ShadowWordPain, true, true);
                 Logging.Write("Cast Dot on " + DotTarget);
                 Thread.Sleep(50);
             }
         }
         if (PriestLevelSettings.CurrentSetting.ShadowDPUse)
         {
             Extension.FightSpell(DevouringPlague);
         }
         Extension.FightSpell(VampiricTouch);
         if (MyTarget.HaveBuff(VampiricTouch.Id))
         {
             Extension.FightSpell(ShadowWordPain);
         }
         Extension.BuffSpell(VampiricEmbrace);
         if (Me.ManaPercentage < 20)
         {
             Extension.FightSpell(ShadowFiend);
         }
         Extension.FightSpell(MindBlast);
         if (MyTarget.HaveBuff(VampiricTouch.Id) &&
             MyTarget.HaveBuff(ShadowWordPain.Id) && PriestLevelSettings.CurrentSetting.ShadowUseMindflay)
         {
             Extension.FightSpell(MindFlay);
         }
     }
 }
        public void BufferingTargetWrapperSyncTest1()
        {
            var myTarget      = new MyTarget();
            var targetWrapper = new BufferingTargetWrapper
            {
                WrappedTarget = myTarget,
                BufferSize    = 10,
            };

            InitializeTargets(myTarget, targetWrapper);

            const int totalEvents = 100;

            var continuationHit    = new bool[totalEvents];
            var lastException      = new Exception[totalEvents];
            var continuationThread = new Thread[totalEvents];
            var hitCount           = 0;

            CreateContinuationFunc createAsyncContinuation =
                eventNumber =>
                ex =>
            {
                lastException[eventNumber]      = ex;
                continuationThread[eventNumber] = Thread.CurrentThread;
                continuationHit[eventNumber]    = true;
                Interlocked.Increment(ref hitCount);
            };

            // write 9 events - they will all be buffered and no final continuation will be reached
            var eventCounter = 0;

            for (var i = 0; i < 9; ++i)
            {
                targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
            }

            Assert.Equal(0, hitCount);
            Assert.Equal(0, myTarget.WriteCount);

            // write one more event - everything will be flushed
            targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
            Assert.Equal(10, hitCount);
            Assert.Equal(1, myTarget.BufferedWriteCount);
            Assert.Equal(10, myTarget.BufferedTotalEvents);
            Assert.Equal(10, myTarget.WriteCount);
            for (var i = 0; i < hitCount; ++i)
            {
                Assert.Same(Thread.CurrentThread, continuationThread[i]);
                Assert.Null(lastException[i]);
            }

            // write 9 more events - they will all be buffered and no final continuation will be reached
            for (var i = 0; i < 9; ++i)
            {
                targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
            }

            // no change
            Assert.Equal(10, hitCount);
            Assert.Equal(1, myTarget.BufferedWriteCount);
            Assert.Equal(10, myTarget.BufferedTotalEvents);
            Assert.Equal(10, myTarget.WriteCount);

            Exception flushException = null;
            var       flushHit       = new ManualResetEvent(false);

            targetWrapper.Flush(
                ex =>
            {
                flushException = ex;
                flushHit.Set();
            });

            flushHit.WaitOne();
            Assert.Null(flushException);

            // make sure remaining events were written
            Assert.Equal(19, hitCount);
            Assert.Equal(2, myTarget.BufferedWriteCount);
            Assert.Equal(19, myTarget.BufferedTotalEvents);
            Assert.Equal(19, myTarget.WriteCount);
            Assert.Equal(1, myTarget.FlushCount);

            // flushes happen on the same thread
            for (var i = 10; i < hitCount; ++i)
            {
                Assert.NotNull(continuationThread[i]);
                Assert.Same(Thread.CurrentThread, continuationThread[i]);
                Assert.Null(lastException[i]);
            }

            // flush again - should just invoke Flush() on the wrapped target
            flushHit.Reset();
            targetWrapper.Flush(
                ex =>
            {
                flushException = ex;
                flushHit.Set();
            });

            flushHit.WaitOne();
            Assert.Equal(19, hitCount);
            Assert.Equal(2, myTarget.BufferedWriteCount);
            Assert.Equal(19, myTarget.BufferedTotalEvents);
            Assert.Equal(19, myTarget.WriteCount);
            Assert.Equal(2, myTarget.FlushCount);

            targetWrapper.Close();
            myTarget.Close();
        }
Esempio n. 35
0
        public void Log_LoggerWrappedAndStackTraceEnabled_UserStackFrameIsCurrentMethod()
        {
            LoggingConfiguration config = new LoggingConfiguration();
            MyTarget target = new MyTarget();
            config.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, target));
            LogManager.Configuration = config;

            MyWrapper wrapper = new MyWrapper();
            wrapper.Log("test");


            Assert.Equal(MethodBase.GetCurrentMethod(), target.LastEvent.UserStackFrame.GetMethod());
        }
Esempio n. 36
0
        public void AsyncTargetWrapperSyncTest_WhenTimeToSleepBetweenBatchesIsEqualToZero()
        {
            LogManager.ThrowConfigExceptions = true;

            var myTarget      = new MyTarget();
            var targetWrapper = new AsyncTargetWrapper()
            {
                WrappedTarget             = myTarget,
                TimeToSleepBetweenBatches = 0,
                BatchSize      = 4,
                QueueLimit     = 2, // Will make it "sleep" between every second write
                OverflowAction = AsyncTargetWrapperOverflowAction.Block
            };

            targetWrapper.Initialize(null);
            myTarget.Initialize(null);

            try
            {
                int flushCounter = 0;
                AsyncContinuation flushHandler = (ex) => { ++flushCounter; };

                List <KeyValuePair <LogEventInfo, AsyncContinuation> > itemPrepareList = new List <KeyValuePair <LogEventInfo, AsyncContinuation> >(500);
                List <int> itemWrittenList = new List <int>(itemPrepareList.Capacity);
                for (int i = 0; i < itemPrepareList.Capacity; ++i)
                {
                    var logEvent   = new LogEventInfo();
                    int sequenceID = logEvent.SequenceID;
                    itemPrepareList.Add(new KeyValuePair <LogEventInfo, AsyncContinuation>(logEvent, (ex) => itemWrittenList.Add(sequenceID)));
                }

                long startTicks = Environment.TickCount;
                for (int i = 0; i < itemPrepareList.Count; ++i)
                {
                    var logEvent = itemPrepareList[i].Key;
                    targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(itemPrepareList[i].Value));
                }

                targetWrapper.Flush(flushHandler);

                for (int i = 0; i < itemPrepareList.Count * 2 && itemWrittenList.Count != itemPrepareList.Count; ++i)
                {
                    Thread.Sleep(1);
                }

                long elapsedMilliseconds = Environment.TickCount - startTicks;

                Assert.Equal(itemPrepareList.Count, itemWrittenList.Count);
                int prevSequenceID = 0;
                for (int i = 0; i < itemWrittenList.Count; ++i)
                {
                    Assert.True(prevSequenceID < itemWrittenList[i]);
                    prevSequenceID = itemWrittenList[i];
                }

#if NET4_5
                if (!IsAppVeyor())  // Skip timing test when running within OpenCover.Console.exe
#endif
                Assert.True(elapsedMilliseconds < 950);

                targetWrapper.Flush(flushHandler);
                for (int i = 0; i < 2000 && flushCounter != 2; ++i)
                {
                    Thread.Sleep(1);
                }
                Assert.Equal(2, flushCounter);
            }
            finally
            {
                myTarget.Close();
                targetWrapper.Close();
            }
        }
Esempio n. 37
0
        public void SplitGroupSyncTest1()
        {
            var myTarget1 = new MyTarget();
            var myTarget2 = new MyTarget();
            var myTarget3 = new MyTarget();

            var wrapper = new SplitGroupTarget()
            {
                Targets = { myTarget1, myTarget2, myTarget3 },
            };

            myTarget1.Initialize(null);
            myTarget2.Initialize(null);
            myTarget3.Initialize(null);
            wrapper.Initialize(null);

            List <Exception> exceptions = new List <Exception>();

            var inputEvents = new List <LogEventInfo>();

            for (int i = 0; i < 10; ++i)
            {
                inputEvents.Add(LogEventInfo.CreateNullEvent());
            }

            int remaining = inputEvents.Count;
            var allDone   = new ManualResetEvent(false);

            // no exceptions
            for (int i = 0; i < inputEvents.Count; ++i)
            {
                wrapper.WriteAsyncLogEvent(inputEvents[i].WithContinuation(ex =>
                {
                    lock (exceptions)
                    {
                        exceptions.Add(ex);
                        if (Interlocked.Decrement(ref remaining) == 0)
                        {
                            allDone.Set();
                        }
                    };
                }));
            }

            allDone.WaitOne();

            Assert.Equal(inputEvents.Count, exceptions.Count);
            foreach (var e in exceptions)
            {
                Assert.Null(e);
            }

            Assert.Equal(inputEvents.Count, myTarget1.WriteCount);
            Assert.Equal(inputEvents.Count, myTarget2.WriteCount);
            Assert.Equal(inputEvents.Count, myTarget3.WriteCount);

            for (int i = 0; i < inputEvents.Count; ++i)
            {
                Assert.Same(inputEvents[i], myTarget1.WrittenEvents[i]);
                Assert.Same(inputEvents[i], myTarget2.WrittenEvents[i]);
                Assert.Same(inputEvents[i], myTarget3.WrittenEvents[i]);
            }

            Exception flushException = null;
            var       flushHit       = new ManualResetEvent(false);

            wrapper.Flush(ex => { flushException = ex; flushHit.Set(); });

            flushHit.WaitOne();
            if (flushException != null)
            {
                Assert.True(false, flushException.ToString());
            }

            Assert.Equal(1, myTarget1.FlushCount);
            Assert.Equal(1, myTarget2.FlushCount);
            Assert.Equal(1, myTarget3.FlushCount);
        }
Esempio n. 38
0
        public void BufferingTargetWrapperSyncWithOverflowDiscardTest()
        {
            const int totalEvents = 15;
            const int bufferSize  = 10;

            var myTarget      = new MyTarget();
            var targetWrapper = new BufferingTargetWrapper
            {
                WrappedTarget  = myTarget,
                BufferSize     = bufferSize,
                OverflowAction = BufferingTargetWrapperOverflowAction.Discard
            };

            InitializeTargets(myTarget, targetWrapper);

            var continuationHit = new bool[totalEvents];
            var hitCount        = 0;
            CreateContinuationFunc createAsyncContinuation =
                eventNumber =>
                ex =>
            {
                continuationHit[eventNumber] = true;
                Interlocked.Increment(ref hitCount);
            };

            Assert.Equal(0, myTarget.WriteCount);

            for (int i = 0; i < totalEvents; i++)
            {
                targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(i)));
            }

            // No events should be written to the wrapped target unless flushing manually.
            Assert.Equal(0, myTarget.WriteCount);
            Assert.Equal(0, myTarget.BufferedWriteCount);
            Assert.Equal(0, myTarget.BufferedTotalEvents);

            targetWrapper.Flush(e => { });
            Assert.Equal(bufferSize, hitCount);
            Assert.Equal(bufferSize, myTarget.WriteCount);
            Assert.Equal(1, myTarget.BufferedWriteCount);
            Assert.Equal(bufferSize, myTarget.BufferedTotalEvents);

            // Validate that we dropped the oldest events.
            Assert.False(continuationHit[totalEvents - bufferSize - 1]);
            Assert.True(continuationHit[totalEvents - bufferSize]);

            // Make sure the events do not stay in the buffer.
            targetWrapper.Flush(e => { });
            Assert.Equal(bufferSize, hitCount);
            Assert.Equal(bufferSize, myTarget.WriteCount);
            Assert.Equal(1, myTarget.BufferedWriteCount);
            Assert.Equal(bufferSize, myTarget.BufferedTotalEvents);

            // Make sure that events are discarded when closing target (config-reload + shutdown)
            targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(totalEvents)));
            targetWrapper.Close();
            Assert.Equal(bufferSize, hitCount);
            Assert.Equal(bufferSize, myTarget.WriteCount);
            Assert.Equal(1, myTarget.BufferedWriteCount);
            Assert.Equal(bufferSize, myTarget.BufferedTotalEvents);
        }
        public void BufferingTargetWrapperSyncWithTimedFlushTest()
        {
            var myTarget      = new MyTarget();
            var targetWrapper = new BufferingTargetWrapper
            {
                WrappedTarget = myTarget,
                BufferSize    = 10,
                FlushTimeout  = 500,
            };

            InitializeTargets(myTarget, targetWrapper);

            const int totalEvents = 100;

            var continuationHit    = new bool[totalEvents];
            var lastException      = new Exception[totalEvents];
            var continuationThread = new Thread[totalEvents];
            var hitCount           = 0;

            CreateContinuationFunc createAsyncContinuation =
                eventNumber =>
                ex =>
            {
                lastException[eventNumber]      = ex;
                continuationThread[eventNumber] = Thread.CurrentThread;
                continuationHit[eventNumber]    = true;
                Interlocked.Increment(ref hitCount);
            };

            // write 9 events - they will all be buffered and no final continuation will be reached
            var eventCounter = 0;

            for (var i = 0; i < 9; ++i)
            {
                targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
            }

            Assert.Equal(0, hitCount);
            Assert.Equal(0, myTarget.WriteCount);

            // sleep 1 second, this will trigger the timer and flush all events
            Thread.Sleep(1000);
            Assert.Equal(9, hitCount);
            Assert.Equal(1, myTarget.BufferedWriteCount);
            Assert.Equal(9, myTarget.BufferedTotalEvents);
            Assert.Equal(9, myTarget.WriteCount);
            for (var i = 0; i < hitCount; ++i)
            {
                Assert.NotSame(Thread.CurrentThread, continuationThread[i]);
                Assert.Null(lastException[i]);
            }

            // write 11 more events, 10 will be hit immediately because the buffer will fill up
            // 1 will be pending
            for (var i = 0; i < 11; ++i)
            {
                targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
            }

            Assert.Equal(19, hitCount);
            Assert.Equal(2, myTarget.BufferedWriteCount);
            Assert.Equal(19, myTarget.BufferedTotalEvents);
            Assert.Equal(19, myTarget.WriteCount);

            // sleep 2 seconds and the last remaining one will be flushed
            Thread.Sleep(1000);
            Assert.Equal(20, hitCount);
            Assert.Equal(3, myTarget.BufferedWriteCount);
            Assert.Equal(20, myTarget.BufferedTotalEvents);
            Assert.Equal(20, myTarget.WriteCount);
        }