public void Setup()
        {
            this.callHandlerData =
                new LogCallHandlerData("logging")
                {
                    Order = 400,

                    LogBehavior = HandlerLogBehavior.BeforeAndAfter,
                    BeforeMessage = "before",
                    AfterMessage = "after",
                    EventId = 1000,
                    IncludeCallStack = true,
                    IncludeCallTime = false,
                    IncludeParameterValues = true,
                    Priority = 500,
                    Severity = TraceEventType.Warning,
                    Categories = 
                    { 
                        new LogCallHandlerCategoryEntry("cat1"), 
                        new LogCallHandlerCategoryEntry("cat2"), 
                        new LogCallHandlerCategoryEntry("cat3")
                    }
                };

            this.logWriter = new LogWriter(new LoggingConfiguration());
            Logger.SetLogWriter(this.logWriter, false);
        }
Example #2
0
        public void CanFindMatchingCategories()
        {
            Dictionary<string, LogSource> traceSources = new Dictionary<string, LogSource>();
            traceSources.Add("newcat1", new LogSource("newcat1"));
            traceSources.Add("newcat2", new LogSource("newcat2"));
            traceSources.Add("newcat3", new LogSource("newcat3"));
            traceSources.Add("newcat4", new LogSource("newcat4"));
            LogWriter logWriter = new LogWriter(emptyFilters, traceSources, new LogSource("errors"), "default");

            string[] categories = new string[] { "newcat1", "newcat2", "newcat5", "newcat6" };
            LogEntry logEntry = new LogEntry();
            logEntry.Categories = categories;
            IEnumerable<LogSource> matchingTraceSources = logWriter.GetMatchingTraceSources(logEntry);

            logWriter.Dispose();

            Dictionary<string, LogSource> matchingTraceSourcesDictionary = new Dictionary<string, LogSource>();
            foreach (LogSource traceSource in matchingTraceSources)
            {
                matchingTraceSourcesDictionary.Add(traceSource.Name, traceSource);
            }

            Assert.AreEqual(2, matchingTraceSourcesDictionary.Count);
            Assert.IsTrue(matchingTraceSourcesDictionary.ContainsKey(categories[0]));
            Assert.IsTrue(matchingTraceSourcesDictionary.ContainsKey(categories[1]));
            Assert.IsFalse(matchingTraceSourcesDictionary.ContainsKey(categories[2]));
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!Utils.CheckLoggedUser(Session["userEmployee"], UserTypeEmployee))
                    Response.Redirect(Page.ResolveUrl("~") + ConfigurationManager.AppSettings["UrlLogin"]);

                if (!Utils.CheckAccountStatus(Session["userEmployee"], UserTypeEmployee))
                    Response.Redirect(Page.ResolveUrl("~") + ConfigurationManager.AppSettings["UrlEmployeePasswordChange"]);

                if (!IsPostBack)
                {
                    LoadTexts();
                    Session.Remove("user");
                }
            }
            catch (ThreadAbortException)
            {

            }
            catch (Exception ex)
            {
                LogWriter log = new LogWriter();
                log.WriteLog(ex.Message, "Page_Load", Path.GetFileName(Request.PhysicalPath));
                throw ex;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!Utils.CheckLoggedUser(Session["userEmployee"], UserTypeEmployee))
                    Response.Redirect(Page.ResolveUrl("~") + ConfigurationManager.AppSettings["UrlLogin"]);

                if (!Utils.CheckAccountStatus(Session["userEmployee"], UserTypeEmployee))
                    Response.Redirect(Page.ResolveUrl("~") + ConfigurationManager.AppSettings["UrlEmployeePasswordChange"]);

                if (coleccionDniResend.IndexOf(((Usuario)Session["userEmployee"]).DNI.ToString()) == -1)
                    Response.Redirect(Page.ResolveUrl("~") + ConfigurationManager.AppSettings["UrlEmployee"]);

                menuControl = (wucMenuNavegacionSimulador)Master.FindControl("menuSimulador");
                //Session.Remove("user");
                //menuControl.BtnBackClick += new EventHandler(btnBack_Click);
            }
            catch (ThreadAbortException)
            {

            }
            catch (Exception ex)
            {
                LogWriter log = new LogWriter();
                log.WriteLog(ex.Message, "Page_Load", Path.GetFileName(Request.PhysicalPath));
                throw ex;
            }
        }
Example #5
0
        public bool Start(HostControl hostControl)
        {
            _log = HostLogger.Get<SampleService>();

            _log.Info("SampleService Starting...");

            hostControl.RequestAdditionalTime(TimeSpan.FromSeconds(10));

            Thread.Sleep(1000);

            ThreadPool.QueueUserWorkItem(x =>
                {
    //                Thread.Sleep(3000);

  //                  _log.Info("Requesting a restart!!!");

//                    hostControl.Restart();

//                _log.Info("Dying an ungraceful death");
//
//                throw new InvalidOperationException("Oh, what a world.");
                });
            _log.Info("SampleService Started");

            return true;
        }
 /// <summary>
 /// Event to save the password change
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 protected void btnEnviar_Click(object sender, EventArgs e)
 {
     try
     {
         if (!loggedUser.CambioPrimerLogin)
         {
             if (ValidatePassword())
             {
                 loggedUser.CambioPrimerLogin = true;
                 SaveNewPassword();
                 Session.Add("userEmployee", loggedUser);
                 SetSuccessView();
                 Response.AddHeader("REFRESH", "5;URL=" + Page.ResolveUrl("~") + ConfigurationManager.AppSettings["UrlEmployeeGenerarClaves"]);
             }
             else
             {
                 FailureText.Text = ConfigurationManager.AppSettings["ErrorMessagePasswordNoCambiada"];
                 divMessage.Visible = true;
             }
         }
     }
     catch (Exception ex)
     {
         LogWriter log = new LogWriter();
         log.WriteLog(ex.Message, "btnEnviar_Click", Path.GetFileName(Request.PhysicalPath));
         throw ex;
     }
 }
        public void CanGetLogFiltersByType()
        {
            ICollection<ILogFilter> filters = new List<ILogFilter>();

            ICollection<string> categories = new List<string>();
            categories.Add("cat1");
            categories.Add("cat2");
            categories.Add("cat3");
            categories.Add("cat4");
            filters.Add(new CategoryFilter("category", categories, CategoryFilterMode.AllowAllExceptDenied));
            filters.Add(new PriorityFilter("priority", 100));
            filters.Add(new LogEnabledFilter("enable", true));

            LogWriter writer = new LogWriter(filters, new Dictionary<string, LogSource>(), new LogSource("errors"), "default");
            CategoryFilter categoryFilter = writer.GetFilter<CategoryFilter>();
            PriorityFilter priorityFilter = writer.GetFilter<PriorityFilter>();
            LogEnabledFilter enabledFilter = writer.GetFilter<LogEnabledFilter>();

            Assert.IsNotNull(categoryFilter);
            Assert.AreEqual(4, categoryFilter.CategoryFilters.Count);
            Assert.IsNotNull(priorityFilter);
            Assert.AreEqual(100, priorityFilter.MinimumPriority);
            Assert.IsNotNull(enabledFilter);
            Assert.IsTrue(enabledFilter.Enabled);
        }
        public void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                {
                    if (!Utils.CheckLoggedUser(Session["userEmployee"], UserTypeEmployee))
                        Response.Redirect(Page.ResolveUrl("~") + ConfigurationManager.AppSettings["UrlLogin"]);
                    Session.Remove("user");
                }

                if (InscripcionDTO.CheckEmployeeTest())
                    btnClean.Enabled = true;

                FailureText.Visible = false;
                divNoDisponible.Visible = false;
            }
            catch (ThreadAbortException)
            {

            }
            catch (Exception ex)
            {
                LogWriter log = new LogWriter();
                log.WriteLog(ex.Message, "Page_Load", Path.GetFileName(Request.PhysicalPath));
                throw ex;
            }
        }
 /// <summary>
 /// Writes the given log entry to the log.
 /// </summary>
 /// <param name="entry">The log entry to write.</param>
 public void Write(LogEntry entry)
 {
     if (IsTracingEnabled())
     {
         LogWriter writer = new LogWriter(loggingConfigurationView.ConfigurationContext);
         writer.Write(entry);
     }
 }
        public void TestInitialize()
        {
            AppDomain.CurrentDomain.SetData("APPBASE", Environment.CurrentDirectory);

            this.logWriter = new LogWriterImpl(new ILogFilter[0], new LogSource[0], new LogSource("name"), "default");
            this.container = new UnityContainer();
            this.container.RegisterInstance(this.logWriter);
        }
Example #11
0
 public LogMessageLogger(string source, UntypedChannel output)
 {
     _debug = new LogMessageFormatter<DebugLogMessage>(output, (s, e) => new DebugLogMessageImpl(source, s, e));
     _info = new LogMessageFormatter<InfoLogMessage>(output, (s, e) => new InfoLogMessageImpl(source, s, e));
     _warn = new LogMessageFormatter<WarnLogMessage>(output, (s, e) => new WarnLogMessageImpl(source, s, e));
     _error = new LogMessageFormatter<ErrorLogMessage>(output, (s, e) => new ErrorLogMessageImpl(source, s, e));
     _fatal = new LogMessageFormatter<FatalLogMessage>(output, (s, e) => new FatalLogMessageImpl(source, s, e));
 }
Example #12
0
        public void RunIt() {
			
            // First we create some delegates using the many syntaxes supported by C# 

			// Old fashioned delegate creation
			// initialize delegate with a named method.
            LogWriter delA = new LogWriter(MethodDelegate);

            // We can just also just assign a method group to a delegate variable
            LogWriter delB = MethodDelegateTwo;
			
			// Since C# 2.0 a delegate can be initialized with
			// an "anonymous method." 
            LogWriter delC = delegate(string s) { Console.WriteLine("AnonymousMethodDelegate[" + _captured_string + "]:\t\t" + s); };
			
			// Since C# 3.0 a delegate can be initialized with
			// a lambda expression. 
            LogWriter delD = (string s) => { Console.WriteLine("LambdaExpressionDelegate[" + _captured_string + "]:\t\t" + s); };
			
			// Since C# 3.0 a delegate can be initialized with
			// a lambda expression, the type of the argument is inferred by the compiler.
            LogWriter delE = s => { Console.WriteLine("InferredLambdaExpressionDelegate[" + _captured_string + "]:\t" + s); };
			
			// Invoke the delegates.
			delA("Peter Piper");
			delB("picked a peck");
            delC("of pickled peppers.");
            delD("A peck of pickled peppers");
            delE("Peter Piper picked.");

            // Change the captured parameter and run them again 
            this._captured_string = "aaaa";

            delA("Peter Piper");
            delB("picked a peck");
            delC("of pickled peppers.");
            delD("A peck of pickled peppers");
            delE("Peter Piper picked.");

            // Now Combine the delegates
            var chainDelegates = delA + delB + delC + delD + delE;

            // and invoke it
            chainDelegates("Chained Delegates");

            // remove delB and rerun
            chainDelegates -= delB;

            chainDelegates("Chained without MethodDelegateTwo");
            
            // Calculate (4 * (x^x)) + 1
            Processor<int> calcIt = (ref int x) => { x = x*x; };
            calcIt += (ref int x) => { x = 4 * x; };
            calcIt += (ref int x) => { x += 1; };
            int val = 5;
            calcIt(ref val);
            Console.WriteLine("(4 * (5^5)) + 1 = " + val);
        }
		public void SetUp()
		{
			logWriter = EnterpriseLibraryFactory.BuildUp<LogWriter>();
			MockTraceListener.Reset();
			ErrorsMockTraceListener.Reset();
			
			emptyTraceSource = new LogSource("none");
			if (emptyTraceSource.Listeners.Count == 1)
				emptyTraceSource.Listeners.RemoveAt(0);
		}
Example #14
0
        public void Assembly_info_is_written_on_log_writer_construction()
        {
            var encoder = Substitute.For<ILogEncoder>();
              var byteWriter = Substitute.For<IByteWriter>();

              // ReSharper disable once UnusedVariable
              var logWriter = new LogWriter(encoder, byteWriter);

              encoder.Received(1).EncodeAssemblyInfo();
              byteWriter.Received(1).WriteBytes(Arg.Any<byte[]>());
        }
Example #15
0
	/// <summary>
	/// 
	/// </summary>
	/// <returns></returns>
	static LogWriter CreateSafeLogWriter()
	{
		bool bHasDDrive = Directory.Exists( "D:" );
		bool bHasFDrive = Directory.Exists( "F:" );
		
		string LogsPath = bHasFDrive ? "F:/" : (bHasDDrive ? "D:/" : "C:/");
		LogsPath += "CrashReportWebsiteLogs";

		LogWriter Log = new LogWriter( "CrashReportWebSite-" + GetCleanUserName(), LogsPath );
		return Log;
	}
        public void SetUp()
        {
            AppDomain.CurrentDomain.SetData("APPBASE", Environment.CurrentDirectory);

            logWriter = new LogWriterFactory().Create();
            MockTraceListener.Reset();
            ErrorsMockTraceListener.Reset();

            emptyTraceSource = new LogSource("none", Enumerable.Empty<TraceListener>(), SourceLevels.All);
            Assert.IsFalse(emptyTraceSource.Listeners.Any());
        }
        public void SetUp()
        {
            AppDomain.CurrentDomain.SetData("APPBASE", Environment.CurrentDirectory);

            logWriter = EnterpriseLibraryContainer.Current.GetInstance<LogWriter>();
            MockTraceListener.Reset();
            ErrorsMockTraceListener.Reset();

            emptyTraceSource = new LogSource("none");
            if (emptyTraceSource.Listeners.Count == 1)
                emptyTraceSource.Listeners.RemoveAt(0);
        }
        public WebAppConfigurator()
        {
            Scheme = "http";
            Domain = "*";
            Port = 8080;

            Log = HostLogger.Get(typeof(WebAppConfigurator));
            DependencyResolver = null;

            HttpConfigurator = httpConfiguration => httpConfiguration.MapHttpAttributeRoutes();
            StartOptions = options => options.Urls.Add(new UriBuilder(Scheme, Domain, Port).ToString());
        }
Example #19
0
        public void Assembly_info_is_not_written_if_encoder_returns_null()
        {
            var encoder = Substitute.For<ILogEncoder>();
              encoder.EncodeAssemblyInfo().Returns(x => null);

              var byteWriter = Substitute.For<IByteWriter>();

              // ReSharper disable once UnusedVariable
              var logWriter = new LogWriter(encoder, byteWriter);

              encoder.Received(1).EncodeAssemblyInfo();
              byteWriter.DidNotReceive().WriteBytes(Arg.Any<byte[]>());
        }
	/// <summary>
	/// 
	/// </summary>
	/// <returns></returns>
	static LogWriter CreateSafeLogWriter( bool bUseGlobal = false )
	{
		bool bHasDDrive = Directory.Exists( "D:" );
		bool bHasFDrive = Directory.Exists( "F:" );
		
		string LogsPath = bHasFDrive ? "F:/" : (bHasDDrive ? "D:/" : "C:/");
		LogsPath += "CrashReportWebsiteLogs";

		string LogFileName = bUseGlobal ? "Global-" + Guid.NewGuid().ToString( "N" ) : string.Format( "{1}-[{0}]", System.Threading.Thread.CurrentThread.ManagedThreadId, GetPathName() );

		LogWriter Log = new LogWriter( LogFileName,LogsPath );
		return Log;
	}
 protected void btnClean_Click(object sender, EventArgs e)
 {
     try
     {
         InscripcionDTO.DeleteEmployeeTestInscription();
         btnClean.Enabled = false;
     }
     catch (Exception ex)
     {
         LogWriter log = new LogWriter();
         log.WriteLog(ex.Message, "btnClean_Click", Path.GetFileName(Request.PhysicalPath));
         throw ex;
     }
 }
 public void Setup()
 {
     this.traceListener = new MockTraceListener("original");
     this.logWriter =
         new LogWriter(
             new LogWriterStructureHolder(
                 new ILogFilter[0],
                 new Dictionary<string, LogSource>(),
                 new LogSource("all", new[] { traceListener }, SourceLevels.All),
                 new LogSource("not processed"),
                 new LogSource("error"),
                 "default",
                 false,
                 false,
                 false));
 }
 /// <summary>
 /// Creates a new <see cref="LogCallHandler"/> that writes to the specified <see cref="LogWriter"/>
 /// using the given logging settings.
 /// </summary>
 /// <param name="logWriter"><see cref="LogWriter"/> to write log entries to.</param>
 /// <param name="eventId">EventId to include in log entries.</param>
 /// <param name="logBeforeCall">Should the handler log information before calling the target?</param>
 /// <param name="logAfterCall">Should the handler log information after calling the target?</param>
 /// <param name="beforeMessage">Message to include in a before-call log entry.</param>
 /// <param name="afterMessage">Message to include in an after-call log entry.</param>
 /// <param name="includeParameters">Should the parameter values be included in the log entry?</param>
 /// <param name="includeCallStack">Should the current call stack be included in the log entry?</param>
 /// <param name="includeCallTime">Should the time to execute the target be included in the log entry?</param>
 /// <param name="priority">Priority of the log entry.</param>
 public LogCallHandler(LogWriter logWriter, int eventId,
                       bool logBeforeCall,
                       bool logAfterCall, string beforeMessage, string afterMessage,
                       bool includeParameters, bool includeCallStack,
                       bool includeCallTime, int priority)
 {
     this.logWriter = logWriter;
     this.eventId = eventId;
     this.logBeforeCall = logBeforeCall;
     this.logAfterCall = logAfterCall;
     this.beforeMessage = beforeMessage;
     this.afterMessage = afterMessage;
     this.includeParameters = includeParameters;
     this.includeCallStack = includeCallStack;
     this.includeCallTime = includeCallTime;
     this.priority = priority;
 }
        protected override void Arrange()
        {
            var settings =
                new LoggingSettings
                {
                    TraceSources =
                    {
                        new TraceSourceData("category1", SourceLevels.All)
                        {
                            TraceListeners = 
                            {
                                new TraceListenerReferenceData("file")
                            }
                        },
                        new TraceSourceData("category2", SourceLevels.All)
                        {
                            TraceListeners = 
                            {
                                new TraceListenerReferenceData("file")
                            }
                        },
                        new TraceSourceData("category3", SourceLevels.All)
                        {
                            TraceListeners = 
                            {
                                new TraceListenerReferenceData("file2")
                            }
                        }
                    },
                    TraceListeners =
                    {
                        new FlatFileTraceListenerData("file", "trace.log", null),
                        new FlatFileTraceListenerData("file2", "trace.log", null)
                    }
                };

            var configurationSource = new DictionaryConfigurationSource();
            configurationSource.Add(LoggingSettings.SectionName, settings);

            this.container =
                EnterpriseLibraryContainer.CreateDefaultContainer(configurationSource).GetInstance<IUnityContainer>();
            this.instrumentationProvider = new TestLoggingInstrumentationProvider();
            this.container.RegisterInstance<ILoggingInstrumentationProvider>(this.instrumentationProvider);
            this.logWriter = this.container.Resolve<LogWriter>();
        }
        /// <summary>
        /// Event to abort the password change
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnCancelar_Click(object sender, EventArgs e)
        {
            try
            {
                Session.Remove("userEmployee");
                Response.Redirect(Page.ResolveUrl("~") + ConfigurationManager.AppSettings["UrlLogin"]);
            }
            catch (ThreadAbortException)
            {

            }
            catch (Exception ex)
            {
                LogWriter log = new LogWriter();
                log.WriteLog(ex.Message, "btnCancelar_Click", Path.GetFileName(Request.PhysicalPath));
                throw ex;
            }
        }
 public MainWindow()
 {
     InitializeComponent();
     passGen = new PasswordGenerater();
     logHandler = new LogWriter();
     textboxes = new TextBox[] {
         _textBox01,
         _textBox02,
         _textBox03,
         _textBox04,
         _textBox05,
         _textBox06,
         _textBox07,
         _textBox08,
         _textBox09,
         _textBox10,
     };
     LoadSettings();
 }
 protected void btnConsultar_Click(object sender, EventArgs e)
 {
     try
     {
         if (ddTurnos.SelectedIndex != 0)
         {
             var idTipoInscripcion = GetIdTipoInscripcion(ddTurnos.SelectedValue.Substring(ddTurnos.SelectedValue.IndexOf("-") + 2));
             DrawChartInscripciones(Convert.ToDateTime(Convert.ToDateTime(ddTurnos.SelectedValue.Substring(0, ddTurnos.SelectedValue.IndexOf("-")))), idTipoInscripcion);
             DrawInscripcionesCarrera(Convert.ToDateTime(Convert.ToDateTime(ddTurnos.SelectedValue.Substring(0, ddTurnos.SelectedValue.IndexOf("-")))), idTipoInscripcion);
             DrawInscripcionesComision(Convert.ToDateTime(Convert.ToDateTime(ddTurnos.SelectedValue.Substring(0, ddTurnos.SelectedValue.IndexOf("-")))), idTipoInscripcion);
         }
     }
     catch (Exception ex)
     {
         LogWriter log = new LogWriter();
         log.WriteLog(ex.Message, "btnConsultar_Click", Path.GetFileName(Request.PhysicalPath));
         throw ex;
     }
 }
        public void SetUp()
        {
            CommonUtil.DeletePrivateTestQ();
            CreateQueueForTesting();

            clientSource = new LogSource("unnamed", SourceLevels.All);
            clientSource.Listeners.Add(
                new MsmqTraceListener("unnamed", CommonUtil.MessageQueuePath, new BinaryLogFormatter(),
                                      MessagePriority.Normal, false, new TimeSpan(0, 1, 0), new TimeSpan(0, 1, 0),
                                      false, true, false, MessageQueueTransactionType.None));

            LogSource distributorSource = new LogSource("unnamed", SourceLevels.All);
            distributorSource.Listeners.Add(new MockTraceListener());
            Dictionary<string, LogSource> traceSources = new Dictionary<string, LogSource>();
            logWriter = new LogWriterImpl(new List<ILogFilter>(), traceSources, distributorSource, null, new LogSource("errors"), "default", false, false);
            eventLogger = new DistributorEventLogger();
            msmqDistributor = new MsmqLogDistributor(logWriter, CommonUtil.MessageQueuePath, eventLogger);
            msmqDistributor.StopReceiving = false;
        }
Example #29
0
        static void Main()
        {
            var loggingConfig = new LoggingConfiguration();
            var customizedWriter = new LogWriter(loggingConfig);

            var logWriterFactory = new LogWriterFactory();
            var defaultWriter = logWriterFactory.Create();

            var logEntry = new LogEntry
                {
                    EventId = 100,
                    Priority = 2,
                    Message = "Informational message",
                    Categories = { "Trace", "UI Events" }
                };

            new ManagedSecurityContextInformationProvider().PopulateDictionary(logEntry.ExtendedProperties);
            new DebugInformationProvider().PopulateDictionary(logEntry.ExtendedProperties);
            new ComPlusInformationProvider().PopulateDictionary(logEntry.ExtendedProperties);
            new UnmanagedSecurityContextInformationProvider().PopulateDictionary(logEntry.ExtendedProperties);

            defaultWriter.Write(logEntry);

            var traceManager = new TraceManager(defaultWriter);
            using (traceManager.StartTrace("Trace"))
            {
                defaultWriter.Write("Operation 1");
            }

            using (traceManager.StartTrace("UI Events", Guid.NewGuid()))
            {
                defaultWriter.Write("Operation 2", "Trace");
            }

            using (traceManager.StartTrace("Trace"))
            {
                using (traceManager.StartTrace("UI Events"))
                {
                    defaultWriter.Write("Operation 3");
                }
            }
        }
        public void GetTracerFromTraceManagerWithNoInstrumentation()
        {
            MockTraceListener.Reset();

            LogSource source = new LogSource("tracesource", new[] { new MockTraceListener() }, SourceLevels.All);

            List<LogSource> traceSources = new List<LogSource>(new LogSource[] { source });
            LogWriter lg = new LogWriter(new List<ILogFilter>(), new List<LogSource>(), source, null, new LogSource("errors"), "default", true, false);

            TraceManager tm = new TraceManager(lg);

            Assert.IsNotNull(tm);

            using (tm.StartTrace("testoperation"))
            {
                Assert.AreEqual(1, MockTraceListener.Entries.Count);
            }

            Assert.AreEqual(2, MockTraceListener.Entries.Count);
        }
Example #31
0
        private void ParseVulnerabilityInfoFromWassp(SQLiteCommand sqliteCommand, XmlReader xmlReader)
        {
            try
            {
                while (xmlReader.Read())
                {
                    if (xmlReader.IsStartElement())
                    {
                        switch (xmlReader.Name)
                        {
                        case "scanner":
                        {
                            ObtainWasspVersion(xmlReader, sqliteCommand);
                            break;
                        }

                        case "date":
                        {
                            sqliteCommand.Parameters["FirstDiscovered"].Value  =
                                sqliteCommand.Parameters["LastObserved"].Value =
                                    xmlReader.ObtainCurrentNodeValue(false);
                            break;
                        }

                        case "host":
                        {
                            sqliteCommand.Parameters["IP_Address"].Value         = xmlReader.GetAttribute("ip");
                            sqliteCommand.Parameters["DiscoveredHostName"].Value = xmlReader.GetAttribute("name").Trim();
                            sqliteCommand.Parameters["DisplayedHostName"].Value  = sqliteCommand.Parameters["DiscoveredHostName"].Value;
                            sqliteCommand.Parameters["MAC_Address"].Value        = xmlReader.GetAttribute("mac");
                            break;
                        }

                        case "test":
                        {
                            sqliteCommand.Parameters["UniqueVulnerabilityIdentifier"].Value =
                                xmlReader.GetAttribute("id");
                            break;
                        }

                        case "check":
                        {
                            sqliteCommand.Parameters["VulnerabilityTitle"].Value =
                                xmlReader.ObtainCurrentNodeValue(false);
                            break;
                        }

                        case "description":
                        {
                            sqliteCommand.Parameters["VulnerabilityDescription"].Value =
                                xmlReader.ObtainCurrentNodeValue(false);
                            break;
                        }

                        case "vulnerability":
                        {
                            string parsed = xmlReader.ObtainCurrentNodeValue(false).ToString();
                            Regex  regex  = new Regex(Properties.Resources.RegexWasspRawRisk);
                            sqliteCommand.Parameters["PrimaryRawRiskIndicator"].Value =
                                regex.Match(parsed).Value.ToRawRisk();
                            break;
                        }

                        case "control":
                        {
                            switch (xmlReader.GetAttribute("regulation"))
                            {
                            case "NIST":
                            {
                                break;
                            }

                            case "DOD":
                            {
                                break;
                            }
                            }

                            break;
                        }

                        case "result":
                        {
                            sqliteCommand.Parameters["Status"].Value =
                                xmlReader.ObtainCurrentNodeValue(false).ToString().ToVulneratorStatus();
                            break;
                        }

                        case "recommendation":
                        {
                            sqliteCommand.Parameters["FixText"].Value = xmlReader.ObtainCurrentNodeValue(false);
                            break;
                        }
                        }
                    }
                    else if (xmlReader.NodeType == XmlNodeType.EndElement && xmlReader.Name.Equals("test"))
                    {
                        sqliteCommand.Parameters["DeltaAnalysisIsRequired"].Value = "False";
                        if (sqliteCommand.Parameters["VulnerabilityVersion"].Value == DBNull.Value)
                        {
                            sqliteCommand.Parameters["VulnerabilityVersion"].Value = string.Empty;
                        }
                        if (sqliteCommand.Parameters["VulnerabilityRelease"].Value == DBNull.Value)
                        {
                            sqliteCommand.Parameters["VulnerabilityRelease"].Value = string.Empty;
                        }
                        databaseInterface.InsertVulnerabilitySource(sqliteCommand);
                        databaseInterface.InsertHardware(sqliteCommand);
                        databaseInterface.InsertAndMapIpAddress(sqliteCommand);
                        databaseInterface.InsertAndMapMacAddress(sqliteCommand);
                        databaseInterface.InsertVulnerability(sqliteCommand);
                        databaseInterface.MapVulnerabilityToSource(sqliteCommand);
                        databaseInterface.UpdateUniqueFinding(sqliteCommand);
                        databaseInterface.InsertUniqueFinding(sqliteCommand);
                    }
                }
            }
            catch (Exception exception)
            {
                LogWriter.LogError("Unable to parse vulnerability information.");
                throw exception;
            }
        }
Example #32
0
 internal static void DeInitialize()
 {
     UnloadPlugins();
     Profiler.Deatch();
     LogWriter.Deatch();
 }
 public EnterpriseLogger(LogWriter logWriter, LogEntryCreator logEntryCreator)
 {
     this.logWriter       = logWriter;
     this.logEntryCreator = logEntryCreator;
 }