예제 #1
0
        static async Task Main(string[] args)
        {
            var logger = new SimpleConsoleLogger(nameof(ScriptHost));

            try
            {
                if (args.Length == 0)
                {
                    logger.LogInformation(@$ "v{Assembly.GetEntryAssembly().GetName().Version} © metaseed
* run script
  cs <scriptPath> [-- arg0 arg1...]
        public void Should_Export()
        {
            var consoleOutput = new StringBuilder();
            var consoleLogger = new SimpleConsoleLogger(consoleOutput);
            var summary       = MockFactory.CreateSummary(typeof(MockFactory.MockBenchmarkClass));
            var subject       = new GraylogExporter("some_product", "some_app", "somehost.com", 5558)
            {
                HostName = "SomeHost", Enabled = false
            };

            subject.ExportToFiles(summary, consoleLogger);
            Assert.Equal(File.ReadAllText("Benchmark/expected_console_output.txt"), consoleOutput.ToString(), ignoreLineEndingDifferences: true);
        }
예제 #3
0
        private static List <string> GetLogLines(string category, Action <ILogger> action)
        {
            var     builder = new StringBuilder();
            ILogger logger  = new SimpleConsoleLogger(category, new StringWriter(builder));

            action(logger);
            var           reader = new StringReader(builder.ToString());
            List <string> ret    = new List <string>();

            while (reader.ReadLine() is string line)
            {
                ret.Add(line);
            }
            return(ret);
        }
예제 #4
0
        public void Initialize()
        {
            var logger = new SimpleConsoleLogger();

            _configurationProvider            = new DiscoveryConfigurationProvider(new NetworkHelper(logger));
            _configurationProvider.DbBasePath = Path.Combine(Path.GetTempPath(), "PeerStorageTests");

            var dbPath = Path.Combine(_configurationProvider.DbBasePath, FullDbOnTheRocks.PeersDbPath);

            if (Directory.Exists(dbPath))
            {
                Directory.GetFiles(dbPath).ToList().ForEach(File.Delete);
            }

            _nodeFactory = new NodeFactory();
            _peerStorage = new PeerStorage(_configurationProvider, _nodeFactory, logger, new PerfService(logger));
        }
예제 #5
0
        /// <summary>
        /// Create new instance of Facebook client class
        /// </summary>
        /// <param name="username">Facebook email or phone number</param>
        /// <param name="password">Facebook password</param>
        /// <exception cref="ArgumentException">Occur when email or password did not provided</exception>
        /// <exception cref="NodeNotFoundException">Login form DOM not found.</exception>
        public FacebookClient(string user, string password, ILogger log = null)
        {
            _http = new HttpHandler();

            if (log == null)
            {
                _logger = new SimpleConsoleLogger();
            }
            else
            {
                _logger = log;
            }

            Username = user;
            Password = password;

            Authorize();
        }
예제 #6
0
    private static async Task Main(string[] args)
    {
        List <Account> accounts = new List <Account>();
        ISimpleLogger  logger;

#if DEBUG
        logger = new SimpleConsoleLogger();
#else
        logger = new SimpleFileLogger(AppContext.BaseDirectory);
#endif

        try
        {
            var builder = new ConfigurationBuilder()
                          .SetBasePath(AppContext.BaseDirectory)
                          .AddJsonFile("appsettings.json");

            IConfigurationRoot configuration = builder.Build();
            configuration.GetSection("accounts").Bind(accounts);

            using (var service = new VkCelebrationSchedulerService(accounts, logger))
            {
#if DEBUG
                await service.RunAsConsole(args);
#else
                ServiceBase.Run(service);
#endif
            }
        }
        catch (Exception ex)
        {
            logger.WriteException(ex);
            logger.WriteLine("=====================================================");
        }
        finally
        {
            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
    }
예제 #7
0
        public void ConsoleLoggerCausesNoException()
        {
            var logger = new SimpleConsoleLogger("Test");

            logger.LogWarning("A test message");
        }
예제 #8
0
        internal static async Task RunAsync()
        {
            Console.WriteLine("Initializing container: " + Program.Experiment);
            var blobClient = Program.Account.CreateCloudBlobClient();

            Container = blobClient.GetContainerReference(Program.Experiment);
            if (!(await Container.ExistsAsync()))
            {
                Console.WriteLine("Container does not exist. Aborting...");
                return;
            }


            Console.WriteLine("Initializing queue: " + Program.Experiment);
            var queueClient = Program.Account.CreateCloudQueueClient();

            Queue = queueClient.GetQueueReference(Program.Experiment);
            if (!(await Queue.ExistsAsync()))
            {
                Console.WriteLine("Queue does not exist. Aborting...");
                return;
            }

            if (!string.IsNullOrEmpty(Program.OutputDirectory) && !Directory.Exists(Program.OutputDirectory))
            {
                Directory.CreateDirectory(Program.OutputDirectory);
            }


            DateTime lastRefresh = DateTime.Now.AddDays(-1);

            Console.WriteLine("Worker is running. Press 'a' to abort.");
            while (true)
            {
                bool          error     = false;
                StringBuilder debugInfo = new StringBuilder();
                debugInfo.AppendLine(DateTime.Now.ToString());
                string debugFileName = null;

                if (Console.KeyAvailable && Console.ReadKey().Key == ConsoleKey.A)
                {
                    Console.WriteLine("Aborting...");
                    return;
                }

                var msg = await Queue.GetMessageAsync(timeOut, null, null);

                if (msg == null)
                {
                    Console.WriteLine("No more tasks in queue.");
                    return;
                }
                try
                {
                    Console.WriteLine($"{DateTime.Now}: Loading benchmark...");
                    Console.WriteLine(msg.AsString);
                    debugInfo.AppendLine(msg.AsString);
                    var config = BenchmarkConfig.FromJsonString(msg.AsString);
                    debugFileName = config.ToShortString();
                    Console.WriteLine($"{DateTime.Now}: Building benchmark...");
                    var benchmark = BenchmarkBuilder.Build(config);
                    var logger    = new SimpleConsoleLogger();
                    logger.Logged += (m, e, l) =>
                    {
                        debugInfo.AppendLine(m);
                        if (e != null)
                        {
                            debugInfo.AppendLine(e.ToString());
                        }
                        if (l == LogLevel.Error || l == LogLevel.Critical)
                        {
                            error = true;
                        }
                    };
                    benchmark.Logger = logger;
                    Console.WriteLine($"{DateTime.Now}: Starting benchmark...");
                    var results = benchmark.Execute(true);
                    Console.WriteLine($"{DateTime.Now}: Generating results...");
                    string filename = config.ToShortString() + ".xlsx";
                    if (!string.IsNullOrWhiteSpace(Program.OutputDirectory))
                    {
                        filename = Path.Combine(Program.OutputDirectory, filename);
                    }
                    benchmark.Dump(filename, config.ToKeyValuePairs());
                    Console.WriteLine($"{DateTime.Now}: Uploading results...");

                    string cloudFilename = config.ToShortString() + ".xlsx";
                    var    blob          = Container.GetBlockBlobReference(cloudFilename);
                    await blob.DeleteIfExistsAsync();

                    await blob.UploadFromFileAsync(filename);
                }
                catch (Exception exc)
                {
                    debugInfo.AppendLine(exc.ToString());
                    error = true;
                }
                if (error)
                {
                    debugFileName = $"{debugFileName ?? Guid.NewGuid().ToString()}.txt";
                    var cloudFilename = debugFileName;

                    if (!string.IsNullOrWhiteSpace(Program.OutputDirectory))
                    {
                        debugFileName = Path.Combine(Program.OutputDirectory, debugFileName);
                    }
                    File.WriteAllText(debugFileName, debugInfo.ToString());
                    var blob = Container.GetBlockBlobReference(cloudFilename);
                    await blob.DeleteIfExistsAsync();

                    await blob.UploadFromFileAsync(debugFileName);
                }

                await Queue.DeleteMessageAsync(msg);
            }
        }
예제 #9
0
        private static async Task <int> RunAsync(CommandLineParameters commandlineParameters)
        {
            var loggerOptions = commandlineParameters.Verbose
                ? new SimpleConsoleLoggerConfiguration(LogLevel.Debug, true, true)
                : new SimpleConsoleLoggerConfiguration(LogLevel.Information, false, true);

            // for validation of command line parameters, directly create a console logger
            // bypassing the DI container because we need to validate the parameters
            // before setting up DI
            var logger = new SimpleConsoleLogger(loggerOptions, "");

            if (!ValidateCommandlineParameters(commandlineParameters, logger))
            {
                return(1);
            }

            var configurationFilePath = !String.IsNullOrEmpty(commandlineParameters.ConfigurationFilePath)
                ? commandlineParameters.ConfigurationFilePath
                : Path.Combine(commandlineParameters.RepositoryPath, s_DefaultConfigurationFileName);

            var configuration = ChangeLogConfigurationLoader.GetConfiguration(configurationFilePath, commandlineParameters);

            using (var gitRepository = new GitRepository(configuration.RepositoryPath))
            {
                var containerBuilder = new ContainerBuilder();

                containerBuilder.RegisterType <ConfigurationValidator>();
                containerBuilder.RegisterInstance(configuration).SingleInstance();
                containerBuilder.RegisterInstance(gitRepository).SingleInstance().As <IGitRepository>();

                containerBuilder.RegisterLogging(loggerOptions);

                containerBuilder.RegisterType <ChangeLogPipeline>();

                containerBuilder.RegisterType <LoadCurrentVersionTask>();
                containerBuilder.RegisterType <LoadVersionsFromTagsTask>();
                containerBuilder.RegisterType <ParseCommitsTask>();
                containerBuilder.RegisterType <FilterVersionsTask>();
                containerBuilder.RegisterType <FilterEntriesTask>();
                containerBuilder.RegisterType <RenderTemplateTask>();

                containerBuilder.RegisterIntegrations();

                try
                {
                    containerBuilder.RegisterTemplate(configuration.Template);
                }
                catch (InvalidTemplateConfigurationException ex)
                {
                    logger.LogCritical($"Failed to load template: {ex.Message}");
                    return(1);
                }

                using (var container = containerBuilder.Build())
                {
                    var configurationValidator = container.Resolve <ConfigurationValidator>();

                    if (!configurationValidator.Validate(configuration))
                    {
                        logger.LogCritical($"Validation of configuration failed");
                        return(1);
                    }

                    // Note: The order of the tasks added here is important.
                    // E.g. In order for commits for versions loaded correctly, ParseCommitsTask needs to run before FilterVersionsTask
                    var pipeline = new ChangeLogPipelineBuilder(container)
                                   .AddTask <LoadCurrentVersionTask>()
                                   .AddTask <LoadVersionsFromTagsTask>()
                                   .AddTask <ParseCommitsTask>()
                                   .AddTask <FilterVersionsTask>()
                                   .AddTask <FilterEntriesTask>()
                                   .AddIntegrationTasks()
                                   .AddTask <RenderTemplateTask>()
                                   .Build();

                    var result = await pipeline.RunAsync();

                    return(result.Success ? 0 : 1);
                }
            }
        }
예제 #10
0
파일: Worker.cs 프로젝트: kayyer/sigstat
        internal static async Task RunAsync(string inputDir, string outputDir, int procId, int maxThreads)
        {
            //stop worker process after 3 days
            DateTime stopTime = DateTime.Now.AddHours(71);

            //delayed start
            await Task.Delay(100 *procId);

            OutputDirectory = Directory.CreateDirectory(outputDir);

            var initSuccess = await Init(inputDir);

            if (!initSuccess)
            {
                return;
            }

            Console.WriteLine($"{DateTime.Now}: Worker is running.");
            if (!Console.IsInputRedirected)
            {
                Console.WriteLine("Press 'A' to abort.");
            }

            while (DateTime.Now < stopTime)
            {
                StringBuilder debugInfo = new StringBuilder();
                debugInfo.AppendLine(DateTime.Now.ToString());

                if (!Console.IsInputRedirected)
                {
                    if (Console.KeyAvailable && Console.ReadKey().Key == ConsoleKey.A)
                    {
                        Console.WriteLine($"{DateTime.Now}: Aborting...");
                        return;
                    }
                }


                var logger = new SimpleConsoleLogger();//default log level: Information
                logger.Logged += (m, e, l) =>
                {
                    debugInfo.AppendLine(m);
                    if (e != null)
                    {
                        debugInfo.AppendLine(e.ToString());
                    }
                    if (l == LogLevel.Error || l == LogLevel.Critical)
                    {
                        CurrentResultType = "Error";
                    }
                };

                CurrentBenchmark = await GetNextBenchmark();

                if (CurrentBenchmark is null)
                {
                    return;
                }
                CurrentBenchmark.Logger = logger;

                Console.WriteLine($"{DateTime.Now}: Starting benchmark...");

                try
                {
                    if (maxThreads > 0)
                    {
                        CurrentResults = CurrentBenchmark.Execute(maxThreads);
                    }
                    else
                    {
                        CurrentResults = CurrentBenchmark.Execute(true);//default: no restriction
                    }
                    CurrentResultType = "Success";
                }
                catch (Exception exc)
                {
                    CurrentResultType = "Error";
                    Console.WriteLine(exc.ToString());
                    debugInfo.AppendLine(exc.ToString());
                    var debugFileName = $"Result_{CurrentBenchmarkId}_Log.txt";

                    debugFileName = Path.Combine(OutputDirectory.ToString(), debugFileName);
                    File.WriteAllText(debugFileName, debugInfo.ToString());

                    if (!Program.Offline)
                    {
                        var blob = Container.GetBlockBlobReference($"Results/{debugFileName}");
                        await blob.DeleteIfExistsAsync();

                        await blob.UploadFromFileAsync(debugFileName);
                    }
                    continue;
                }

                await ProcessResults();

                if (Program.Offline)
                {//delete input config and lock after processing
                    File.Delete(Path.Combine(InputDirectory.ToString(), CurrentBenchmarkId + ".json"));
                    File.Delete(Path.Combine(InputDirectory.ToString(), CurrentBenchmarkId + ".json.lock"));
                }
                else
                {
                    await Queue.DeleteMessageAsync(CurrentMessage);
                }

                //LogProcessor.Dump(logger);
                // MongoDB
                // TableStorage
                // Json => utólag, json-ben szűrni lehet
                // DynamoDB ==> MongoDB $$$$$$$
                // DateTime, MachineName, ....ExecutionTime,..., ResultType, Result json{40*60 táblázat}
                //benchmark.Dump(filename, config.ToKeyValuePairs());
            }
        }
예제 #11
0
        static void Main(string[] args)
        {
            SimpleConsoleLogger logger = null;
            int    coverWidth          = 500;
            int    coverHeight         = 500;
            int    imageQuality        = 90;
            bool   recursive           = false;
            bool   showHelp            = false;
            string path = null;
            string overwriteImageName = null;

            var cmdOptions = new OptionSet()
            {
                {
                    "d|dir=", "Directory containing MP3 files, which should be processed",
                    opt => path = opt
                },
                {
                    "w|width=", "New max width of images",
                    opt => {
                        if (opt != null)
                        {
                            if (!int.TryParse(opt, out coverWidth))
                            {
                                showHelp = true;
                            }
                        }
                    }
                },
                {
                    "h|height=", "New max height of images",
                    opt => {
                        if (opt != null)
                        {
                            if (!int.TryParse(opt, out coverHeight))
                            {
                                showHelp = true;
                            }
                        }
                    }
                },
                {
                    "q|quality=", "Compress image after resizing (value: 0 - 100)",
                    opt => {
                        if (opt != null)
                        {
                            if (!int.TryParse(opt, out imageQuality))
                            {
                                showHelp = true;
                            }
                        }
                    }
                },
                {
                    "o|overwrite=", "Overwrites or adds an album cover, if an image file with the name VALUE lies in the same folder as the MP3 files. If no such image can be found, the tool resizes the embedded image",
                    opt =>
                    {
                        overwriteImageName = opt;
                    }
                },
                {
                    "r|recursive", "Also process files in subdirectories",
                    opt => recursive = opt != null
                },
                {
                    "v|verbose", "Show progress and other messages",
                    opt => {
                        if (opt != null)
                        {
                            logger = new SimpleConsoleLogger(SimpleConsoleLogger.LogLevels.INFO);
                        }
                        else
                        {
                            logger = new SimpleConsoleLogger(SimpleConsoleLogger.LogLevels.SILENT);
                        }
                    }
                },
                {
                    "help", "Show information about usage",
                    opt => showHelp = opt != null
                }
            };

            List <string> extraArgs = null;

            try
            {
                extraArgs = cmdOptions.Parse(args);
            }
            catch (OptionException)
            {
                System.Console.WriteLine("Oops something went wrong. Try 'Mp3AlbumCoverResizer --help' for more information.");
                return;
            }

            if (showHelp)
            {
                ShowHelp(cmdOptions);
                return;
            }

            if (path == null)
            {
                System.Console.WriteLine(@"No path to an directory with MP3 files provided. Please use 'Mp3AlbumCoverResizer -d ""C:\My Music\Amon Amarth\""' to choose a directory.");
                return;
            }

            var resizer = new AlbumCoverResizer(logger, coverWidth, coverHeight, imageQuality)
            {
                OverwriteImageFromFile = overwriteImageName != null,
                OverwriteImageName     = overwriteImageName
            };

            resizer.Resize(path, recursive);
        }
예제 #12
0
        private static async Task <int> RunAsync(CommandLineParameters commandlineParameters)
        {
            var loggerOptions = commandlineParameters.Verbose
                ? new SimpleConsoleLoggerConfiguration(LogLevel.Debug, true, true)
                : new SimpleConsoleLoggerConfiguration(LogLevel.Information, false, true);

            // for validation of command line parameters, directly create a console logger
            // bypassing the DI container because we need to validate the parameters
            // before setting up DI
            var logger = new SimpleConsoleLogger(loggerOptions, "");

            if (!ValidateCommandlineParameters(commandlineParameters, logger))
            {
                return(1);
            }

            if (!TryGetRepositoryPath(commandlineParameters, logger, out var repositoryPath))
            {
                return(1);
            }

            if (!TryOpenRepository(repositoryPath, logger, out var gitRepository))
            {
                return(1);
            }

            var configurationFilePath = GetConfigurationFilePath(commandlineParameters, repositoryPath);

            if (File.Exists(configurationFilePath))
            {
                logger.LogDebug($"Using configuration file '{configurationFilePath}'");
            }
            else
            {
                logger.LogDebug("Continuing without loading a configuration file, because no configuration file was wound");
            }


            // pass repository path to configuration loader to make it available through the configuration system
            var dynamicSettings = new DynamicallyDeterminedSettings()
            {
                RepositoryPath = repositoryPath
            };

            var configuration = ChangeLogConfigurationLoader.GetConfiguration(configurationFilePath, commandlineParameters, dynamicSettings);

            using (gitRepository)
            {
                var containerBuilder = new ContainerBuilder();

                containerBuilder.RegisterType <ConfigurationValidator>();
                containerBuilder.RegisterInstance(configuration).SingleInstance();
                containerBuilder.RegisterInstance(gitRepository).SingleInstance().As <IGitRepository>();

                containerBuilder.RegisterLogging(loggerOptions);

                containerBuilder.RegisterType <ChangeLogPipeline>();

                containerBuilder.RegisterType <LoadCurrentVersionTask>();
                containerBuilder.RegisterType <LoadVersionsFromTagsTask>();
                containerBuilder.RegisterType <LoadCommitsTask>();
                containerBuilder.RegisterType <LoadMessageOverridesFromGitNotesTask>();
                containerBuilder.RegisterType <LoadMessageOverridesFromFileSystemTask>();
                containerBuilder.RegisterType <ParseCommitsTask>();
                containerBuilder.RegisterType <ParseCommitReferencesTask>();
                containerBuilder.RegisterType <FilterVersionsTask>();
                containerBuilder.RegisterType <FilterEntriesTask>();
                containerBuilder.RegisterType <ResolveEntryReferencesTask>();
                containerBuilder.RegisterType <AddCommitFooterTask>();
                containerBuilder.RegisterType <ParseWebLinksTask>();
                containerBuilder.RegisterType <RenderTemplateTask>();

                containerBuilder.RegisterIntegrations();

                try
                {
                    containerBuilder.RegisterTemplate(configuration.Template);
                }
                catch (InvalidTemplateConfigurationException ex)
                {
                    logger.LogError($"Failed to load template: {ex.Message}");
                    return(1);
                }

                using (var container = containerBuilder.Build())
                {
                    var configurationValidator = container.Resolve <ConfigurationValidator>();
                    var validationResult       = configurationValidator.Validate(configuration);

                    if (!validationResult.IsValid)
                    {
                        foreach (var error in validationResult.Errors)
                        {
                            logger.LogError($"Invalid configuration: {error.ErrorMessage}");
                        }

                        logger.LogError($"Validation of configuration failed");
                        return(1);
                    }

                    var pipeline = new ChangeLogPipelineBuilder(container)
                                   .AddTask <LoadCurrentVersionTask>()
                                   .AddTask <LoadVersionsFromTagsTask>()
                                   .AddTask <LoadCommitsTask>()
                                   .AddTaskIf <LoadMessageOverridesFromGitNotesTask>(
                        configuration.MessageOverrides.Enabled && configuration.MessageOverrides.Provider == ChangeLogConfiguration.MessageOverrideProvider.GitNotes
                        )
                                   .AddTaskIf <LoadMessageOverridesFromFileSystemTask>(
                        configuration.MessageOverrides.Enabled && configuration.MessageOverrides.Provider == ChangeLogConfiguration.MessageOverrideProvider.FileSystem
                        )
                                   .AddTask <ParseCommitsTask>()
                                   .AddTask <ParseCommitReferencesTask>()
                                   .AddTask <ParseWebLinksTask>()
                                   .AddTask <FilterVersionsTask>()
                                   .AddTask <FilterEntriesTask>()
                                   .AddTask <ResolveEntryReferencesTask>()
                                   .AddTask <AddCommitFooterTask>()
                                   .AddIntegrationTasks()
                                   .AddTask <RenderTemplateTask>()
                                   .Build();

                    var result = await pipeline.RunAsync();

                    return(result.Success ? 0 : 1);
                }
            }
        }
예제 #13
0
 public SimpleConsoleLoggerProvider()
 {
     logger = new SimpleConsoleLogger();
 }