Exemple #1
0
        public static void ClassInitialize(TestContext context)
        {
            Appender.AddFilter(new LevelMatchFilter {
                LevelToMatch = new Level(35000, "DETAIL")
            });
            Appender.AddFilter(new DenyAllFilter());

            BasicConfigurator.Configure(Appender);
        }
        private void SendErrorToProvider(DocSourceHandlerForTesting handler, MiniMailException exception, Mime sourceLetter)
        {
            try {
                var memoryAppender = new MemoryAppender();
                memoryAppender.AddFilter(new LoggerMatchFilter {
                    AcceptOnMatch = true, LoggerToMatch = "PriceProcessor", Next = new DenyAllFilter()
                });
                BasicConfigurator.Configure(memoryAppender);

                handler.SendErrorLetterToSupplier(exception, sourceLetter);

                var events = memoryAppender.GetEvents();
                Assert.That(
                    events.Length,
                    Is.EqualTo(0),
                    "Ошибки при обработки задач сертификатов:\r\n{0}",
                    events.Select(item => {
                    if (string.IsNullOrEmpty(item.GetExceptionString()))
                    {
                        return(item.RenderedMessage);
                    }
                    else
                    {
                        return(item.RenderedMessage + Environment.NewLine + item.GetExceptionString());
                    }
                }).Implode("\r\n"));
            }
            finally {
                LogManager.ResetConfiguration();
            }
        }
 public Log4NetLogProviderLoggingDisabledTests()
 {
     _memoryAppender = new MemoryAppender();
     _memoryAppender.AddFilter(new DenyAllFilter());
     BasicConfigurator.Configure(_memoryAppender);
     _sut = new Log4NetLogProvider().GetLogger("Test");
 }
 public Log4NetLogManagerLoggingDisabledTests()
 {
     Log4NetLogManager.ProviderIsAvailabileOverride = true;
     memoryAppender = new MemoryAppender();
     memoryAppender.AddFilter(new DenyAllFilter());
     BasicConfigurator.Configure(memoryAppender);
     sut = new Log4NetLogManager().GetLogger("Test");
 }
Exemple #5
0
        /// <summary>
        /// Handles when the value changes for a <see cref="CheckBox"/> for a <see cref="Level"/>.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        void LevelCheckBox_ValueChanged(Control sender, EventArgs e)
        {
            // Rebuild the list of disabled log levels
            _disabledLogLevels.Clear();
            _disabledLogLevels.AddRange(_logLevelCheckBoxes.Where(x => !x.Value).Select(x => (Level)x.Tag));

            // Also add filters to the logger to reject the disabled log levels
            _logger.ClearFilters();
            foreach (var disabledLevel in _disabledLogLevels)
            {
                _logger.AddFilter(new LevelMatchFilter {
                    AcceptOnMatch = false, LevelToMatch = disabledLevel
                });
            }
        }
Exemple #6
0
        public override void SetUp()
        {
            base.SetUp();

            _mocks              = new MockRepository();
            _mockAclFinder      = _mocks.StrictMock <IAccessControlListFinder>();
            _mockTokenBuilder   = _mocks.StrictMock <ISecurityTokenBuilder>();
            _mockAccessResolver = _mocks.StrictMock <IAccessResolver>();

            _service = new SecurityService(_mockAclFinder, _mockTokenBuilder, _mockAccessResolver);
            _context = SecurityContext.Create(typeof(Order), "Owner", "UID: OwnerGroup", "OwnerTenant", new Dictionary <string, Enum>(), new Enum[0]);

            _clientTransaction = ClientTransaction.CreateRootTransaction();
            using (_clientTransaction.EnterNonDiscardingScope())
            {
                OrganizationalStructureFactory organizationalStructureFactory = new OrganizationalStructureFactory();
                _tenant = organizationalStructureFactory.CreateTenant();
            }

            _principalStub = _mocks.Stub <ISecurityPrincipal>();
            SetupResult.For(_principalStub.User).Return("group0/user1");

            _memoryAppender = new MemoryAppender();

            LoggerMatchFilter acceptFilter = new LoggerMatchFilter();

            acceptFilter.LoggerToMatch = "Remotion.SecurityManager";
            acceptFilter.AcceptOnMatch = true;
            _memoryAppender.AddFilter(acceptFilter);

            DenyAllFilter denyFilter = new DenyAllFilter();

            _memoryAppender.AddFilter(denyFilter);

            BasicConfigurator.Configure(_memoryAppender);
        }
Exemple #7
0
        /// <summary>
        /// This function will be called before the start of the monitor.
        /// </summary>
        public void Initialise()
        {
            _listener = new HttpListener();

            foreach (string uriPrefix in _uriPrefixes)
            {
                _listener.Prefixes.Add(uriPrefix);
            }

            _memoryAppender = new MemoryAppender();
            _memoryAppender.AddFilter(new LevelRangeFilter {
                LevelMin = Level.Info, LevelMax = Level.Fatal
            });

            ((Hierarchy)LogManager.GetRepository()).Root.AddAppender(_memoryAppender);
        }
        private void ProcessCertificatesWithLog(Action action)
        {
            if (session.Transaction.IsActive)
            {
                session.Transaction.Commit();
            }

            try {
                var memoryAppender = new MemoryAppender();
                memoryAppender.AddFilter(new LoggerMatchFilter {
                    AcceptOnMatch = true, LoggerToMatch = "PriceProcessor", Next = new DenyAllFilter()
                });
                BasicConfigurator.Configure(memoryAppender);

                try {
                    action();
                }
                catch {
                    var logEvents = memoryAppender.GetEvents();
                    Console.WriteLine(
                        "Ошибки при обработки задач сертификатов:\r\n{0}",
                        logEvents.Select(item => {
                        if (string.IsNullOrEmpty(item.GetExceptionString()))
                        {
                            return(item.RenderedMessage);
                        }
                        else
                        {
                            return(item.RenderedMessage + Environment.NewLine + item.GetExceptionString());
                        }
                    }).Implode("\r\n"));
                    throw;
                }

                var events = memoryAppender.GetEvents();
                var errors = events.Where(item => item.Level >= Level.Warn);
                Assert.That(errors.Count(), Is.EqualTo(0), "При обработки задач сертификатов возникли ошибки:\r\n{0}", errors.Select(item => item.RenderedMessage).Implode("\r\n"));
            }
            finally {
                LogManager.ResetConfiguration();
            }
        }
        public void SendErrorsOnProcessTask()
        {
            Clean();

            var certificateSource = CreateSourceForSupplier(supplier, typeof(TestErrorSource).Name);

            var serialNumber = Path.GetRandomFileName();
            var catalog      = TestCatalogProduct.Queryable.First();
            var product      = TestProduct.Queryable.First(p => p.CatalogProduct == catalog);

            var documentLine = CreateBodyLine(serialNumber, product);

            var realDocumentLine = Document.Find(documentLine.Waybill.Id).Lines[0];

            var task = new CertificateTask(certificateSource, realDocumentLine);

            task.Save();

            Assert.That(task.Id, Is.GreaterThan(0));

            try {
                session.Transaction.Commit();

                ((Logger)LogManager.GetLogger(typeof(TestCertificateSourceHandler)).Logger).Level = Level.Warn;
                var memoryAppender = new MemoryAppender();
                memoryAppender.ActivateOptions();
                memoryAppender.AddFilter(new LoggerMatchFilter {
                    AcceptOnMatch = true, LoggerToMatch = "PriceProcessor", Next = new DenyAllFilter()
                });
                BasicConfigurator.Configure(memoryAppender);

                var handler = new TestCertificateSourceHandler();

                handler.OnSource = (c) => {
                    c.CertificateSource.CertificateSourceParser = new TestErrorSource();
                    return(c.CertificateSource);
                };

                //Обрабатываем задачу первый раз
                handler.ProcessData();
                CheckErrors(task, memoryAppender, handler, 1);

                //Создаем новую задачу с теми же параметрами и обрабатываем задачу второй раз
                task = new CertificateTask(certificateSource, realDocumentLine);
                SaveAndProcess(task, handler);
                CheckErrors(task, memoryAppender, handler, 2);

                //Создаем новую задачу с теми же параметрами и обрабатываем задачу третий раз
                task = new CertificateTask(certificateSource, realDocumentLine);

                SaveAndProcess(task, handler);
                CheckErrors(task, memoryAppender, handler, 3);

                var lastEvents = memoryAppender.GetEvents();
                var errors     = lastEvents.Where(item => item.Level >= Level.Warn).ToList();
                Assert.That(errors.Count, Is.EqualTo(3));
                //Последнее сообщение должно быть Error
                Assert.That(errors[2].Level, Is.EqualTo(Level.Error));

                //Успешно обработываем сертификат и список ошибок должен очистится
                handler.OnSource = (c) => {
                    c.CertificateSource.CertificateSourceParser = new TestSuccessSource();
                    return(c.CertificateSource);
                };
                certificateSource.SourceClassName = typeof(TestSuccessSource).Name;
                certificateSource.Save();
                //Создаем новую задачу с теми же параметрами и обрабатываем задачу третий раз
                task = new CertificateTask(certificateSource, realDocumentLine);
                SaveAndProcess(task, handler);

                Assert.That(errors.Count, Is.EqualTo(3));
                Assert.That(handler.Errors.Count, Is.EqualTo(0), handler.Errors.Implode());

                //Задача должна быть удалена из базы данных
                var deletedSuccessTask = CertificateTask.Queryable.FirstOrDefault(t => t.Id == task.Id);
                Assert.That(deletedSuccessTask, Is.Null);
            }
            finally {
                LogManager.ResetConfiguration();
            }
        }