Beispiel #1
0
        public void TestEventViewer()
        {
            var l = new Logger("bUtilitySource");
            l.Error("test logger 1");

            l.Error(new Exception("an exception sample"));
        }
        private ErrorSuccess<IVsixPackage, string> _LoadFromFile(string file, Logger log, ErrorSuccessFactory<IVsixPackage, string> ef)
        {
            log.Info($"Reading {file}");

            ZipArchive zipFile;
            try
            {
                zipFile = ZipFile.OpenRead(file);
            }
            catch (Exception ex)
            {
                log.Error($"{file} is not a zip archive.", ex);
                return ef.Error($"{file} is not a zip archive: {ex.Message}");
            }

            using (zipFile)
            {
                var manifestEntry = zipFile.Entries.FirstOrDefault(entry => entry.FullName == Entry.Manifest);
                if (manifestEntry == null)
                {
                    return ef.Error($"{file} does not contain a {Entry.Manifest} entry.");
                }

                return _CreateFromZipManifest(file, manifestEntry, log, ef);
            }
        }
Beispiel #3
0
		/// <summary>
		/// Build an Array of a particular type from a list of tokens.  
		/// The Type must be one that can be built with Convert.ChangeType.
		/// There are various ways to specify how many elements to parse.
		/// WARNING: This will throw an exception if any tokens cannot be
		/// converted.
		/// </summary>
		/// <param name="tokens">The ArrayList of tokens.</param>
		/// <param name="i">The starting (and ending) index.  This is
		/// modified, and left pointing at the last used token.</param>
		/// <param name="type">The Type of the array elements.</param>
		/// <param name="endToken">An optional end Token to look for.
		/// Parsing stops when a token equal to this is found.
		/// If this is null, then it is not used.</param>
		/// <param name="maxLength">The maximum number of array elements
		/// to parse.  If this is negative, then it is not used.</param>
		/// <param name="log">A Logger to use for messages.</param>
		/// <returns>The Array, or null for error.</returns>
		public static Array BuildArray(ArrayList tokens, ref int i, Type type,
			Token endToken, int maxLength, Logger log)
		{
			int len = tokens.Count;
			if (i >= len) 
			{
				log.Error("BuildArray: Input index too large.");
				return(null);
			}

			// put the objects into an array list first, since we don't
			// know length
			ArrayList list = new ArrayList();

			// allow null endToken specified
			if (endToken == null) endToken = new EofToken();

			Token token = null;
			token = (Token)tokens[i++];
			int arrayLength = 0;

			while ((!(token is EofToken)) && (token != endToken) && (i < len)
				&& ((maxLength < 0) || (arrayLength < maxLength)))
			{
				Object o = token.ConvertToType(type);
				list.Add(o);
				arrayLength++;
				token = (Token)tokens[i++];
			}
			i--; // went one past

			return(list.ToArray(type));
		}
        static void Main(string[] args)
        {
            ILayout simpleLayout = new SimpleLayout();
            IAppender consoleAppender = new ConsoleAppender(simpleLayout);
            ILogger logger = new Logger(consoleAppender);

            logger.Error("Error parsing JSON");
            logger.Info(string.Format("User {0} successfully registered.", "Pesho"));

            Console.WriteLine(new string('-', 20));

            //We create a second Appender and add it to the existing ILogger object
            IFileAppender fileAppender = new FileAppender(simpleLayout);
            fileAppender.File = "log.txt";

            logger.AddAppender(fileAppender);

            logger.Fatal("mscorlib.dll does not respond");
            logger.Critical("No connection string found in App.config");

            Console.WriteLine(new string('-', 20));

            //We set the new XML Layout on each Appender that the Logger object uses
            foreach (IAppender appender in logger.Appenders)
            {
                appender.Layout = new XmlLayout();
            }

            logger.Fatal("mscorlib.dll does not respond");
            logger.Critical("No connection string found in App.config");

            Console.WriteLine(new string('-', 20));

            //We set the Report Level Minimum at Error
            foreach (IAppender appender in logger.Appenders)
            {
                appender.ReportLevelMinimum = Enums.ReportLevel.Error;
            }

            logger.Info("Everything seems fine");
            logger.Warning("Warning: ping is too high - disconnect imminent");
            logger.Error("Error parsing request");
            logger.Critical("No connection string found in App.config");
            logger.Fatal("mscorlib.dll does not respond");

            Console.WriteLine(new string('-', 20));
        }
Beispiel #5
0
        private static void ExampleOne()
        {
            ILayout simpleLayout = new SimpleLayout();
            IAppender consoleAppender =
                 new ConsoleAppender(simpleLayout);
            ILogger logger = new Logger(consoleAppender);

            logger.Error("Error parsing JSON.");
            logger.Info(string.Format("User {0} successfully registered.", "Pesho"));
        }
        public void LoggerGenerateOutputTest()
        {
            Logger logger = new Logger(System.Reflection.Assembly.GetExecutingAssembly());
            logger.Exception("exception #1");
            logger.Exception("exception #2");
            logger.Exception("exception #3");
            logger.Exception("exception #4");

            logger.Error("Error 1");
            logger.Error("Error 2");
            logger.Error("Error 3");

            logger.Warn("Warn 1");
            logger.Warn("Warn 2");
            logger.Warn("Warn 3");

            string id = logger.LogResume();

            Assert.Pass(id);
        }
Beispiel #7
0
        private static void ExampleTwo()
        {
            var simpleLayout = new SimpleLayout();

            var consoleAppender = new ConsoleAppender(simpleLayout);
            var fileAppender = new FileAppender(simpleLayout);
            fileAppender.File = "log.txt";

            var logger = new Logger(consoleAppender, fileAppender);
            logger.Error("Error parsing JSON.");
            logger.Info(string.Format("User {0} successfully registered.", "Pesho"));
            logger.Warn("Warning - missing files.");
        }
        public ErrorSuccess<IVsixPackage, string> LoadFromFile(string file, Logger log)
        {
            var ef = new ErrorSuccessFactory<IVsixPackage, string>();

            try
            {
                return _LoadFromFile(file, log, ef);
            }
            catch (Exception ex)
            {
                log.Error($"An unexpected error occurred while trying to read {file} as a vsix.", ex);
                return ef.Error($"An unexpected error occurred while trying to read {file} as a vsix: {ex.Message}");
            }
        }
Beispiel #9
0
        private static void ExampleFour()
        {
            var simpleLayout = new SimpleLayout();
            var consoleAppender = new ConsoleAppender(simpleLayout);
            consoleAppender.ReportLevel = ReportLevel.Error;

            var logger = new Logger(consoleAppender);

            logger.Info("Everything seems fine");
            logger.Warn("Warning: ping is too high - disconnect imminent");
            logger.Error("Error parsing request");
            logger.Critical("No connection string found in App.config");
            logger.Fatal("mscorlib.dll does not respond");
        }
        public CSharpProject(ISolution solution, 
                             Logger logger, 
                             string folderPath, 
                             IFileSystem fileSystem)
            : base(fileSystem, logger)
        {
            _fileSystem = fileSystem;
            _logger = logger;
            _solution = solution;

            Files = new List<CSharpFile>();
            References = new List<IAssemblyReference>();

            DirectoryInfoBase folder;

            try
            {
                folder = _fileSystem.DirectoryInfo.FromDirectoryName(folderPath);
            }
            catch (DirectoryNotFoundException)
            {
                logger.Error("Directory not found - " + folderPath);
                return;
            }

            var files = folder.GetFiles("*.cs", SearchOption.AllDirectories);
            foreach (var file in files)
            {
                _logger.Debug("Loading " + file.FullName);
                Files.Add(new CSharpFile(this, file.FullName));
            }

            this.ProjectContent = new CSharpProjectContent()
                .SetAssemblyName(AssemblyName)
                .AddAssemblyReferences(References)
                .AddOrUpdateFiles(Files.Select(f => f.ParsedFile));

            AddMsCorlib();
            AddReference(LoadAssembly(FindAssembly("System.Core")));


            var dlls = folder.GetFiles("*.dll", SearchOption.AllDirectories);
            foreach (var dll in dlls)
            {
                _logger.Debug("Loading assembly " + dll.FullName);
                AddReference(dll.FullName);
            }
        }
Beispiel #11
0
		public void Error()
		{
			// arrange
			var logger = new Logger();
			var logs = new StringBuilder();
			logger.SetWriter(new StringWriter(logs));
			logger.AddCategory("error");

			// act
			logger.Debug("debug message");
			logger.Info("info message");
			logger.Error("error message");

			// assert
			Assert.Equal("error message", logs.ToString().Trim());
		}
Beispiel #12
0
 private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
 {
     try
     {
         Logger logger = new Logger();
         Exception ex = (Exception)e.ExceptionObject;
         logger.Error("Unhandled exception occured in application. " + ex.Message, ex);
         Console.WriteLine("MyHandler caught : " + ex.Message);
         Console.WriteLine("Runtime terminating: {0}", e.IsTerminating);
         ErrorModal form = new ErrorModal(ex.Message);
         form.ShowDialog();
     }
     catch (Exception)
     {
     }
 }
 /// <summary>
 /// Costruttore senza ID del sensore, trovato automaticamente dal software
 /// Prende il primo termometro che trova 
 /// </summary>
 /// <param name="Name"></param>
 /// <param name="Simulation"></param>
 /// <param name="Logger"></param>
 public Temperature_DS1822(string Name, bool Simulation, Logger Logger)
     : base(Name, Simulation, Logger)
 {
     Logger.Debug("Temperature_DS1822_Constructor senza ID. SensorId automatico");
     if (!Simulation)
     {
         // creazione del termometro; se il parametro DeviceIndex = 0 usa il primo sensore che trova
         try
         {
             termometro = new Ds18b20Connection(0);
         }
         catch (Exception ex)
         {
             Logger.Error("Temperature_DS1822_Constructor senza ID. " + ex.Message);
             return;
         }
     }
     Initialization();
 }
Beispiel #14
0
        public void TestLogging()
        {
            var config = new FileConfiguration
                {
                    CreateDateFolder = true,
                    DaysToKeep = 3,
                    Path = AppDomain.CurrentDomain.BaseDirectory
                };

            var target = new FileTarget("Everything", config);

            target.Enqueue(new LogEntry
                {
                    CreatedAt = DateTime.Now,
                    LogLevel = LogLevel.Debug,
                    Message = "Hello world",
                    LoggedType = GetType(),
                    MethodName = MethodBase.GetCurrentMethod().Name,
                    ThreadId = Thread.CurrentThread.ManagedThreadId,
                    UserName = Thread.CurrentPrincipal.Identity.Name
                               ?? Environment.UserName
                });

            var target2 = new PaddedFileTarget("EVeryone", config);
            target2.Enqueue(new LogEntry
                {
                    CreatedAt = DateTime.Now,
                    LogLevel = LogLevel.Debug,
                    Message = "Hello world",
                    LoggedType = GetType(),
                    MethodName = MethodBase.GetCurrentMethod().Name,
                    ThreadId = Thread.CurrentThread.ManagedThreadId,
                    UserName = Thread.CurrentPrincipal.Identity.Name
                               ?? Environment.UserName
                });

            var logger = new Logger(GetType(), new[] {target2, target});
            logger.Info("Hello");
            logger.Debug("Hello");
            logger.Warning("Hello");
            logger.Error("Hello");
        }
 public Temperature_DS1822(string Name, bool Simulation, string SensorId,Logger Logger)
     : base(Name, Simulation, Logger)
 {
     Logger.Debug("Temperature_DS1822_Constructor con ID. SensorId: " + SensorId);
     // creazione del termometro con l'Id passato
     if (!Simulation)
     {
         try
         {
             termometro = new Ds18b20Connection(SensorId);
         }
         catch (Exception ex)
         {
             Logger.Error("Temperature_DS1822_Constructor con ID. SensorId" + ex.Message);
             return;
         }
     }
     IdSensor = SensorId;
     Initialization();
 }
Beispiel #16
0
        public void TestLogging()
        {
            var config = new FileConfiguration
                             {
                                 CreateDateFolder = true,
                                 DaysToKeep = 3,
                                 Path = @"d:\logfiles"
                             };

            var target = new FileTarget("Everything", config);

            target.Enqueue(new LogEntry
                               {
                                   CreatedAt = DateTime.Now,
                                   LogLevel = LogLevel.Debug,
                                   Message = "Hello world",
                                   StackFrames = new StackTrace().GetFrames(),
                                   ThreadId = Thread.CurrentThread.ManagedThreadId,
                                   UserName = Thread.CurrentPrincipal.Identity.Name
                                              ?? Environment.UserName
                               });

            var target2 = new PaddedFileTarget("EVeryone", config);
            target2.Enqueue(new LogEntry
                                {
                                    CreatedAt = DateTime.Now,
                                    LogLevel = LogLevel.Debug,
                                    Message = "Hello world",
                                    StackFrames = new StackTrace().GetFrames(),
                                    ThreadId = Thread.CurrentThread.ManagedThreadId,
                                    UserName = Thread.CurrentPrincipal.Identity.Name
                                               ?? Environment.UserName
                                });

            var logger = new Logger(GetType(), new[] {target2, target});
            logger.Info("Hello");
            logger.Debug("Hello");
            logger.Warning("Hello");
            logger.Error("Hello");
        }
Beispiel #17
0
 void TryLogger(Logger logger)
 {
     bool thrown = false;
      string message = "msg";
      try
      {
     logger.Always(message);
     logger.Debug(message);
     logger.Detailed(message);
     logger.Error(message);
     logger.Event(message);
     logger.Fatal(message);
     logger.Info(message);
     logger.Warning(message);
      }
      catch (Exception)
      {
     thrown = true;
      }
      Assert.IsFalse(thrown);
 }
Beispiel #18
0
		// ---------------------------------------------------------------------
		#region TestSelf
		// ---------------------------------------------------------------------
		/// <summary>
		/// Simple self test.
		/// </summary>
		/// <returns>bool - true for success, false for failure.</returns>
		public static bool TestSelf()
		{
			Logger log = new Logger("testSelf");
			log.Verbosity = VerbosityLevel.Debug;
			log.Info("Starting...");

			//
			// try parseSpec style
			//
			string parseSpec = "file=s, type:s, v, d, number=s";
			string[] testArgs = {"-file", "fileName", "-type", "-v", "hello", 
				"-number", "-3.2"};
			string errorMessage = null;

			Opts opts = new Opts();
			opts.ParseSpec = parseSpec;
			log.Info("ParseSpec:");
			opts.DisplayParseSpec("    ");

			if (!opts.Parse(testArgs, out errorMessage))
			{
				log.Error("Unable to parse test string.");
				log.Error("Error message is '{0}'", errorMessage);
				return(false);
			}

			log.Info("After parse:");
			opts.Display("    ");

			// check results
			if (opts.Options["file"] == null)
			{
				log.Error("Parse didn't get -file option");
				return(false);
			}
			log.Info("-file argument was {0}", opts.Options["file"]);

			if (opts.Options.ContainsKey("v")) log.Info("-v option was found");
			else
			{
				log.Error("Parse didn't find -v option");
				return(false);
			}
			
			if (opts.Options.ContainsKey("type"))
			{
				log.Info("-type arg was '{0}'", opts.Options["type"]);
			}
			else
			{
				log.Error("Parse didn't find -type option");
				return(false);
			}

			//
			// try usageSpec style
			//
			log.Info("----------------------------------------------------------");
			log.Info("UsageSpec style of use.");
			string usageSpec = "cmd -file fileName -type [typeName] [-v|-d] [-number num] file ...";
			log.Info("Input usage: {0}", usageSpec);
			opts.UsageSpec = usageSpec;
			log.Info("UsageSpec:");
			opts.DisplayParseSpec("    ");

			if (!opts.Parse(testArgs, out errorMessage))
			{
				log.Error("Unable to parse test string.");
				log.Error("Error message is '{0}'", errorMessage);
				return(false);
			}

			if (opts.Options.ContainsKey("v"))
			{
				log.Info("-v was specified");
			}

			log.Info("After parse:");
			opts.Display("    ");

			// done
			log.Info("Done.");
			return(true);
		}
        public virtual void Init()
        {
            Log = new Logger(_info.Name ?? _info.WatcherType.Substring(_info.WatcherType.LastIndexOf('.') + 1));

            string basePath = AppDomain.CurrentDomain.BaseDirectory;

            //Input folder must be specified - either absolute, or relative
            //(in which case it becomes a subfolder of the AppDomain current folder)
            //Input must exist -- we do this to avoid creating random folders on disk
            //if there's a typo in the configuration
            _inputFolder = MakeRootedPath(basePath, _info.InputFolder);

            //All other folders are children of input folder by default
            //If a folder is overriden in a config file, do any of
            // a) If override is rooted, use that explicit path
            // b) Else append to input folder
            if (!_info.NoDefaultFolders) {
                _archiveFolder = SetupConfiguredFolder(_inputFolder, _info.ArchiveFolder, "processed");
                if (!_info.DeleteMeansDelete)
                    _deletedFolder = SetupConfiguredFolder(_inputFolder, _info.DeletedFolder, "deleted");
                _errorFolder = SetupConfiguredFolder(_inputFolder, _info.ErrorFolder, "error");
            }

            //Some processors want a separate output folder to output transformed files
            //(as opposed to 'Processed' folder that archives unchanged input files after they are processed)
            _outputFolder = MakeRootedPath(basePath, _info.OutputFolder);
            //Some processors will use an URI for output
            _uri = _info.Url;

            if (_info.WatchSubfolders && (IsSubFolderOf(_inputFolder, _archiveFolder) || IsSubFolderOf(_inputFolder, _deletedFolder) || IsSubFolderOf(_inputFolder, _errorFolder))) {
                _info.WatchSubfolders = false;
                Log.Error("Will not watch subfolders as some of the configured folders are subfolders of input folder");
            }
            if (_info.NoDefaultFolders) {
                Log.Info("Registering watcher '{0}': input from '{1}{2}', leave files in place.", _info.WatcherType, _inputFolder, _info.WatchSubfolders ? "\\*" + _info.Filter : "");
            } else {
                Log.Info("Registering watcher '{0}': input from '{1}{3}', archive to '{2}'", _info.WatcherType, _inputFolder, _archiveFolder, _info.WatchSubfolders ? "\\*" + _info.Filter : "");
            }
            if (!Directory.Exists(_inputFolder)) {
                Log.Error("Input folder {0} does not exist. Please create the folder and restart this service.", _inputFolder);
            }
            if (!string.IsNullOrWhiteSpace(_outputFolder)) {
                Log.Info("Transformed output will go into '{0}'", _outputFolder);
            }

            _watcher = new FileSystemWatcher(_inputFolder);
            _watcher.Created += new FileSystemEventHandler(FileCreated);
            if (!string.IsNullOrEmpty(_info.Filter)) {
                _watcher.Filter = _info.Filter;
            }
            _watcher.IncludeSubdirectories = _info.WatchSubfolders;
            _watcher.EnableRaisingEvents = true;

            SetUpTimers();
        }
        internal void ValidateConfiguration(Logger logger)
        {
            if (AreDefaults) return;

            Type type = null;               
            try
            {
                type = TypeUtils.ResolveType(FullTypeName);
            }
            catch (Exception exception)
            {
                string errStr = String.Format("Unable to find grain class type {0} specified in configuration; Failing silo startup.", FullTypeName);
                logger.Error(ErrorCode.Loader_TypeLoadError, errStr, exception);
                throw new OrleansException(errStr, exception);
            }

            if (type == null)
            {
                string errStr = String.Format("Unable to find grain class type {0} specified in configuration; Failing silo startup.", FullTypeName);
                logger.Error(ErrorCode.Loader_TypeLoadError_2, errStr);
                throw new OrleansException(errStr);
            }
            var typeInfo = type.GetTypeInfo();
            // postcondition: returned type must implement IGrain.
            if (!typeof(IGrain).IsAssignableFrom(type))
            {
                string errStr = String.Format("Type {0} must implement IGrain to be used Application configuration context.",type.FullName);
                logger.Error(ErrorCode.Loader_TypeLoadError_3, errStr);
                throw new OrleansException(errStr);
            }
            // postcondition: returned type must either be an interface or a class.
            
            if (!typeInfo.IsInterface && !typeInfo.IsClass)
            {
                string errStr = String.Format("Type {0} must either be an interface or class used Application configuration context.",type.FullName);
                logger.Error(ErrorCode.Loader_TypeLoadError_4, errStr);
                throw new OrleansException(errStr);
            }
        }
Beispiel #21
0
        public void error_just_delegates_to_all_listeners()
        {
            var l1 = MockRepository.GenerateMock<ILogListener>();
            var l2 = MockRepository.GenerateMock<ILogListener>();
            var l3 = MockRepository.GenerateMock<ILogListener>();

            var logger = new Logger(new ILogListener[] { l1, l2, l3 }, NulloModifiers);

            var ex = new NotImplementedException();
            logger.Error("some message", ex);

            l1.AssertWasCalled(x => x.Error("some message", ex));
            l2.AssertWasCalled(x => x.Error("some message", ex));
            l3.AssertWasCalled(x => x.Error("some message", ex));
        }
Beispiel #22
0
        public void logger_will_not_throw_an_exception_if_one_listener_blows_chunks_for_error()
        {
            var l1 = MockRepository.GenerateMock<ILogListener>();
            var l2 = MockRepository.GenerateMock<ILogListener>();
            var l3 = MockRepository.GenerateMock<ILogListener>();

            var logger = new Logger(new ILogListener[] { l1, l2, l3 }, NulloModifiers);

            var ex = new NotImplementedException();

            l2.Expect(x => x.Error("some message", ex)).Throw(new NotSupportedException());

            logger.Error("some message", ex);

            l1.AssertWasCalled(x => x.Error("some message", ex));
            l2.AssertWasCalled(x => x.Error("some message", ex));
            l3.AssertWasCalled(x => x.Error("some message", ex));
        }
        public CSharpProject(ISolution solution, Logger logger, string folderPath)
        {
            _logger = logger;
            _solution = solution;

            Files = new List<CSharpFile>();
            References = new List<IAssemblyReference>();

            DirectoryInfo folder;

            try
            {
                folder = new DirectoryInfo(folderPath);
            }
            catch(DirectoryNotFoundException)
            {
                logger.Error("Directory not found - " + folderPath);
                return;
            }

            var files = folder.EnumerateFiles("*.cs", SearchOption.AllDirectories);
            foreach (var file in files)
            {
                _logger.Debug("Loading " + file.FullName);
                Files.Add(new CSharpFile(this, file.FullName));
            }

            var dlls = folder.EnumerateFiles("*.dll", SearchOption.AllDirectories);
            foreach (var dll in dlls)
            {
                Console.WriteLine(dll.FullName);
                AddReference(dll.FullName);
            }

            AddMsCorlib();
            AddReference(LoadAssembly(FindAssembly("System.Core")));
            AddAllKpmPackages();
            this.ProjectContent = new CSharpProjectContent()
                .SetAssemblyName(AssemblyName)
                .AddAssemblyReferences(References)
                .AddOrUpdateFiles(Files.Select(f => f.ParsedFile));
        }
Beispiel #24
0
        public void Logger_NoRoutes()
        {
            const string message = "message";
            ILogger logger = new Logger();

            logger.Critical(message);
            logger.Error(message);
            logger.Warning(message);
            logger.Informational(message);
            logger.Debug(message);
            logger.Diagnostic(message);
            logger.ChangeEvent(message, message);//string is not a good example here, but the function isn't called anyway

            //yes, nothing happens.
            //this test is here to ensure no exceptions occur when leaving handlers unspecified for the logger
        }
        // ---------------------------------------------------------------------
        #region TestSelf
        // ---------------------------------------------------------------------
        /// <summary>
        /// Simple self test.  See StreamTokenizerTestCase for full
        /// tests.
        /// </summary>
        /// <returns>bool - true for success, false for failure.</returns>
        public static bool TestSelf()
        {
            Logger log = new Logger("testSelf");
            log.Verbosity = VerbosityLevel.Debug;
            log.Info("Starting...");
            string testString;
            ArrayList tokens;

            // setup tokenizer
            StreamTokenizer tokenizer = new StreamTokenizer();
            tokenizer.Settings.SetupForCodeParse();
            tokenizer.Verbosity = VerbosityLevel.Debug;

            //
            // try string parse
            //
            log.Write("--------------------------------------------------------\n");
            log.Info("string parse:");
            log.Write("--------------------------------------------------------\n");
            tokens = new ArrayList();
            testString = "-1.2ej";
            tokenizer.Settings.DoUntermCheck = false;
            tokenizer.Settings.GrabWhitespace = false;

            if (!tokenizer.TokenizeString(testString, tokens))
            {
                log.Error("Unable to parse into token vector.");
                return (false);
            }

            foreach (Token t in tokens) log.Info("Token = '{0}'", t);
            tokens = new ArrayList();

            //
            // try NextToken style
            //
            //			log.Write("--------------------------------------------------------\n");
            //			log.Info("NextToken use");
            //			log.Write("--------------------------------------------------------\n");
            //string fileName = "st-testSelf.tmp";
            //testString = "this is a simple string";
            //tokenizer.TextReader = new StringReader(testString);
            //tokenizer.TextReader = File.OpenText(fileName);
            //Token token;
            //while (tokenizer.NextToken(out token)) log.Info("Token = '{0}'", token);

            //
            // try TokenizeFile
            //
            log.Write("--------------------------------------------------------\n");
            log.Info("Tokenize missing file");
            log.Write("--------------------------------------------------------\n");
            string nonExistentFileName = "ThisFile better not exist";
            bool caughtIt = false;
            try
            {
                tokenizer.TokenizeFile(nonExistentFileName);
            }
            catch (FileNotFoundException e)
            {
                log.Info("Correctly caught exception: {0}: {1}", e.GetType(), e.Message);
                caughtIt = true;
            }
            if (!caughtIt)
            {
                log.Error("Didn't get a file not found exception from TokenizeFile.");
                return (false);
            }

            //
            // test line numbers in tokens
            //

            // done
            log.Info("Done.");
            return (true);
        }
Beispiel #26
0
 public static void Fatal(Logger log, Exception ex)
 {
     Exception actualEx = null;
     if (ex.InnerException != null)
     {
         actualEx = ex.InnerException;
         while (actualEx.InnerException != null)
         {
             actualEx = actualEx.InnerException;
         }
     }
     log.Error("Exception: ", ex);
     if (actualEx != null)
     {
         log.Fatal("Inner exception: ", actualEx);
     }
 }
Beispiel #27
0
        public CSharpProject(ISolution solution,
                             IFileSystem fileSystem,
                             Logger logger, 
                             string title, 
                             string fileName, 
                             Guid id)
            : base(fileSystem, logger)
        {
            _fileSystem = fileSystem;
            _logger = logger;
            _solution = solution;
            Title = title;
            if (fileSystem is FileSystem)
            {
                fileName = fileName.ForceNativePathSeparator();
            }
            FileName = fileName;
            ProjectId = id;
            Files = new List<CSharpFile>();
            Microsoft.Build.Evaluation.Project project;

            try
            {
                project = new Microsoft.Build.Evaluation.Project(_fileSystem, fileName);
            }
            catch (DirectoryNotFoundException)
            {
                logger.Error("Directory not found - " + FileName);
                return;
            }
            catch (FileNotFoundException)
            {
                logger.Error("File not found - " + FileName);
                return;
            }

            AssemblyName = project.GetPropertyValue("AssemblyName");

            SetCompilerSettings(project);

            AddCSharpFiles(project);

            References = new List<IAssemblyReference>();
            this.ProjectContent = new CSharpProjectContent()
                .SetAssemblyName(AssemblyName)
                .AddOrUpdateFiles(Files.Select(f => f.ParsedFile));

            AddMsCorlib();

            bool hasSystemCore = false;
            foreach (var item in project.GetItems("Reference"))
            {
                var assemblyFileName = GetAssemblyFileNameFromHintPath(project, item);
                //If there isn't a path hint or it doesn't exist, try searching
                if (assemblyFileName == null)
                    assemblyFileName = FindAssembly(item.EvaluatedInclude);

                //If it isn't in the search paths, try the GAC
                if (assemblyFileName == null && PlatformService.IsWindows)
                    assemblyFileName = FindAssemblyInNetGac(item.EvaluatedInclude);

                if (assemblyFileName != null)
                {
                    if (_fileSystem.Path.GetFileName(assemblyFileName).Equals("System.Core.dll", StringComparison.OrdinalIgnoreCase))
                        hasSystemCore = true;

                    _logger.Debug("Loading assembly " + item.EvaluatedInclude);
                    try
                    {
                        AddReference(LoadAssembly(assemblyFileName));
                    }
                    catch (Exception e)
                    {
                        _logger.Error(e);
                    }

                }
                else
                    _logger.Error("Could not find referenced assembly " + item.EvaluatedInclude);
            }
            if (!hasSystemCore && FindAssembly("System.Core") != null)
                AddReference(LoadAssembly(FindAssembly("System.Core")));

            AddProjectReferences(project);
        }
Beispiel #28
0
        public void error_just_delegates_to_all_listeners_2()
        {
            var l1 = MockRepository.GenerateMock<ILogListener>();
            var l2 = MockRepository.GenerateMock<ILogListener>();
            var l3 = MockRepository.GenerateMock<ILogListener>();

            var logger = new Logger(SystemTime.Default(), new ILogListener[] { l1, l2, l3 });

            var ex = new NotImplementedException();
            var correlationId = Guid.NewGuid();
            logger.Error(correlationId, "some message", ex);

            l1.AssertWasCalled(x => x.Error(correlationId, "some message", ex));
            l2.AssertWasCalled(x => x.Error(correlationId, "some message", ex));
            l3.AssertWasCalled(x => x.Error(correlationId, "some message", ex));
        }
        public async Task ErrorLogsWhenLogLevelAtError()
        {
            // Arrange
            Logger logger = new Logger(_runtimeEnvironment.Object, _queue.Object, _source.Object, _extension.Object, LogLevelEnum.Error, _correlationIdProvider.Object);

            // Act
            await logger.Error("a message");

            // Assert
            _queue.Verify(x => x.EnqueueAsync(It.IsAny<LogQueueItem>()));
        }
Beispiel #30
0
		/// <summary>
		/// Simple test of some ParseUtil methods.
		/// </summary>
		/// <returns>bool - true for all passed, false otherwise</returns>
		public static bool TestSelf()
		{
			Logger log = new Logger("ParseUtil: TestSelf");
			log.Info("Starting...");

			StreamTokenizer tokenizer = new StreamTokenizer();
			tokenizer.Verbosity = VerbosityLevel.Warn;

			// FindMatch
			ArrayList alist = new ArrayList();
			tokenizer.TokenizeString("{ [ ] '}' }", alist);
			foreach(Token t in alist) log.Debug("Token = {0}", t);

			Token[] tarray = (Token[])alist.ToArray(typeof(Token));
			int i = 0;
			if (!FindMatch(tarray, ref i, '{'))
			{
				log.Error("FindMatch failed to match { char");
				return(false);
			}

			if (i != 4)
			{
				log.Error("FindMatch got the wrong answer {0}", i);
				return(false);
			}
			else log.Info("FindMatch worked.");

			//
			// try BuildArray
			//
			ArrayList tokens = new ArrayList();
			tokenizer.TokenizeString("1 2 3 4 5", tokens);
			foreach(Token t in tokens) log.Debug("Token = {0}", t);

			i = 0;
			Int16[] shorts = (short[])ParseUtil.BuildArray(tokens, ref i, typeof(Int16), null,
				-1, log);
		
			if (shorts == null) 
			{
				log.Error("Unable to BuildArray of shorts.");
				return(false);
			}

			log.Info("Parsed shorts:");
			foreach(Int16 s in shorts)
			{
				log.Write("{0}, ", s);
			}
			log.WriteLine("");

			//
			// try BuildArray of floats, char terminated
			//
			tokens.Clear();
			tokenizer.TokenizeString("1 2 ; 3 4", tokens);
			foreach(Token t in tokens) log.Debug("Token = {0}", t);

			i = 0;
			Single[] floats = (float[])ParseUtil.BuildArray(tokens, ref i, typeof(Single), 
				new CharToken(';'), -1, log);
		
			if (floats == null) 
			{
				log.Error("Unable to BuildArray of floats.");
				return(false);
			}

			log.Info("Parsed floats:");
			foreach(float f in floats)
			{
				log.Write("{0}, ", f);
			}
			log.WriteLine("");

			if (i != 2)
			{
				log.Error("BuildArray left i = {0} which is incorrect");
				return(false);
			}

			//
			// try BuildArray on high-precision floats
			//
			tokens.Clear();
			float f1 = 1.23456f;
			float f2 = 2.34567f;
			tokenizer.TokenizeString(String.Format("{0:f6} {1:f6}", f1,f2), tokens);
			foreach(Token t in tokens) log.Debug("Token = {0}", t);

			i = 0;
			floats = (float[])ParseUtil.BuildArray(tokens, ref i, typeof(Single), 
				null, -1, log);
		
			if (floats == null) 
			{
				log.Error("Unable to BuildArray of floats.");
				return(false);
			}

			log.Info("Parsed floats:");
			foreach(float f in floats)
			{
				log.Write("{0}, ", f);
			}
			log.WriteLine("");

			if (floats[0] != f1)
			{
				log.Error("BuildArray produced float {0:f6} instead of {1:f6}",
					floats[0], f1);
				return(false);
			}

			//
			// try BuildArray of chars, maxLength terminated
			//
			log.Info("Chars, terminated by maxLength");
			tokens.Clear();
			tokenizer.TokenizeString("12 2 ; 3 4", tokens);
			foreach(Token t in tokens) log.Debug("Token = {0}", t);

			i = 0;
			char[] chars = (char[])ParseUtil.BuildArray(tokens, ref i, typeof(Char), 
				null, 3, log);
		
			if (chars == null) 
			{
				log.Error("Unable to BuildArray of chars.");
				return(false);
			}

			log.Info("Parsed chars:");
			foreach(char f in chars)
			{
				log.Write("{0}, ", f);
			}
			log.WriteLine("");

			if (i != 4)
			{
				log.Error("BuildArray left i = {0} which is incorrect", i);
				return(false);
			}

			//
			// try BuildArray of hex numbers
			//
			log.Info("Hex numbers");
			tokens.Clear();
			tokenizer.Settings.ParseHexNumbers = true;
			tokenizer.TokenizeString("0xfff, 0xffe", tokens);
			foreach(Token t in tokens) log.Debug("Token = {0}", t);

			i = 0;
			ushort[] ushorts = (ushort[])ParseUtil.BuildArray(tokens, ref i, typeof(ushort), 
				null, 3, log);
		
			if (ushorts == null) 
			{
				log.Error("Unable to BuildArray of ushorts.");
				return(false);
			}

			log.Info("Parsed ushorts:");
			foreach(ushort us in ushorts)
			{
				log.Write("{0}, ", us);
			}
			log.WriteLine("");

//			if (i != 4)
//			{
//				log.Error("BuildArray left i = {0} which is incorrect", i);
//				return(false);
//			}

			log.Info("All PASSED");
			return(true);
		}