Esempio n. 1
1
        public Program()
        {
            // a DI based application would get ILoggerFactory injected instead
            var factory = new LoggerFactory();

            // getting the logger immediately using the class's name is conventional
            _logger = factory.CreateLogger(typeof(Program).FullName);

            // providers may be added to an ILoggerFactory at any time, existing ILoggers are updated
            #if !DNXCORE50
            factory.AddNLog(new global::NLog.LogFactory());
            #endif
            factory.AddConsole();
            factory.AddConsole((category, logLevel) => logLevel >= LogLevel.Critical && category.Equals(typeof(Program).FullName));
        }
Esempio n. 2
0
        public void ConfigureServices()
        {
            IServiceProvider mainProv = CallContextServiceLocator.Locator.ServiceProvider;
            IApplicationEnvironment appEnv = mainProv.GetService<IApplicationEnvironment>();
            IRuntimeEnvironment runtimeEnv = mainProv.GetService<IRuntimeEnvironment>();

            ILoggerFactory logFactory = new LoggerFactory();
            logFactory.AddConsole(LogLevel.Information);

            ServiceCollection sc = new ServiceCollection();
            sc.AddInstance(logFactory);
            sc.AddSingleton(typeof(ILogger<>), typeof(Logger<>));
            sc.AddEntityFramework()
                .AddSqlite()
                .AddDbContext<StarDbContext>();

            sc.AddSingleton<ILibraryManager, LibraryManager>(factory => mainProv.GetService<ILibraryManager>() as LibraryManager);
            sc.AddSingleton<ICache, Cache>(factory => new Cache(new CacheContextAccessor()));
            sc.AddSingleton<IExtensionAssemblyLoader, ExtensionAssemblyLoader>();
            sc.AddSingleton<IStarLibraryManager, StarLibraryManager>();
            sc.AddSingleton<PluginLoader>();
            sc.AddSingleton(factory => mainProv.GetService<IAssemblyLoadContextAccessor>());
            sc.AddInstance(appEnv);
            sc.AddInstance(runtimeEnv);

            Services = sc;

            ServiceProvider = sc.BuildServiceProvider();
        }
Esempio n. 3
0
        private static async Task Run(string[] args)
        {
            try
            {
                // This wont work...
                // See https://github.com/aspnet/Configuration/issues/214
                //var config = new ConfigurationBuilder();
                //config.AddJsonFile("wiki.json");

                var jsonConfig = new JsonConfigurationSource("wiki.json");
                var config = new ConfigurationBuilder(jsonConfig);

                var builder = new ContainerBuilder();
                var module = new ConfigurationModule(config.Build());
                builder.RegisterModule(module);
                
                var loggerFactory = new LoggerFactory();
                loggerFactory.AddConsole(LogLevel.Information);
                builder.RegisterInstance(loggerFactory).As<ILoggerFactory>().SingleInstance();

                builder.RegisterType<GetDescriptionAction>().AsImplementedInterfaces().InstancePerDependency();
                builder.RegisterType<AddValueToAlternativeKeysAction>().AsImplementedInterfaces().InstancePerDependency();
                builder.Register(ctx => new CompositeDictEntryAction(ctx.Resolve<IEnumerable<IDictEntryAction>>()))
                    .Keyed<IDictEntryAction>(DictEntryActionKey);
                builder.Register(
                    ctx =>
                        new Wiki.Wiki(ctx.Resolve<HttpClient>(),
                            ctx.ResolveOptionalKeyed<IDictEntryAction>(DictEntryActionKey),
                            ctx.Resolve<ILoggerFactory>()))
                    .AsImplementedInterfaces()
                    .InstancePerDependency();
                builder.RegisterInstance(new DictConfig
                {
                    FilePath = Path.Combine("..", "..", "resources", "kindle_dict.html"),
                    OpfFilePath = Path.Combine("..", "..", "resources"),
                    TemplateFilePath = Path.Combine("..", "..", "resources", "knidle_dict_template.html"),
                    EntryTemplateFilePath = Path.Combine("..", "..", "resources", "knidle_dict_entry_template.html"),
                    OpfTemplateFilePath = Path.Combine("..", "..", "resources", "kindle_dict_template.opf"),
                }).SingleInstance();
                builder.RegisterType<Dict>().AsImplementedInterfaces().SingleInstance();

                var logger = loggerFactory.CreateLogger(typeof (Program).FullName);
                var container = builder.Build();

                var wiki = container.Resolve<IWiki>();
                logger.LogInformation("Getting wiki description...");
                var wikiDesc = await wiki.GetDescriptionAsync().ConfigureAwait(false);
                logger.LogInformation("Getting entries...");
                var entries = await wiki.GetEntriesAsync().ConfigureAwait(false);
                var dict = container.Resolve<IDict>();
                logger.LogInformation("Saving dictionary...");
                await dict.SaveAsync(wikiDesc, entries).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }
        }
Esempio n. 4
0
        static void Main(string[] args)
        {
            ILoggerFactory loggerFactory = new LoggerFactory();
            loggerFactory.AddProvider(new DiagnosticsLoggerProvider());
            loggerFactory.AddConsole();

            FooManager manager = new FooManager(loggerFactory);
            manager.Run();
        }
Esempio n. 5
0
        public void Execute(string[] args)
        {
            var options = new Options();
            Parser.Default.ParseArguments(args, options);

            var factory = new LoggerFactory();
            factory.AddConsole();

            var logger = factory.CreateLogger("category-1");

            int number = options.Number;
            for (int i = 0; i < number; i++)
                logger.LogInformation("message " + i);
        }
Esempio n. 6
0
        public async static Task ProcessedImagesTrigger([QueueTrigger(QueueNames.Seen)]CloudQueueMessage message, CancellationToken cancellationToken)
        {
            var connectionFactory = new StorageConnectionFactory(CloudConfigurationManager.GetSetting("storageAccountConnection"));
            var factory = new LoggerFactory();
            factory.AddConsole();
            factory.AddEventLog();

            var logger = factory.CreateLogger("ToprakWebjobs");
            var imageRepository = new ImageRepository(connectionFactory, logger);
            var queueRepository = new QueueRepository(connectionFactory, logger);
            IResultsRepository resultsRepository = new ResultsRepository(CloudConfigurationManager.GetSetting("Database"), logger);

            var envelope = TutanakDataEnvelope.GorulmusTutanakMesajiFactory(message.AsString);
            envelope.TutanakData.Image = (new Uri(envelope.TutanakData.Image)).Segments[2];

            await resultsRepository.RecordResult(envelope);

            var imageSeen = envelope.TutanakData;

            var results = (await resultsRepository.GetTutanakResultsAsync(imageSeen.Image)).ToList();

            var compareProperties =
                typeof(GorulmusTutanakMesaji).GetProperties()
                    .Where(p => p.GetCustomAttributes(false).All(a => a.GetType() != typeof(NoCompareAttribute)))
                    .OrderBy(p => p.Name)
                    .Select(p => p.Name);

            var resultHashGroups =
                results.Select(
                    r =>
                    compareProperties.Select(p => r.GetType().GetProperty(p).GetValue(r)).Aggregate((i, j) => $"{i},{j}"))
                    .GroupBy(h => h)
                    .Select(g => g.Count())
                    .OrderByDescending(c => c).ToList();

            var sameReadLimit = Convert.ToInt32(CloudConfigurationManager.GetSetting("SameReadLimit"));

            if (resultHashGroups.Any() && resultHashGroups.Max() >= sameReadLimit)
            {
                await imageRepository.TransferToProcessed(imageSeen.Image, cancellationToken);
                await resultsRepository.RecordReadSuccessResult(envelope);
            } else 
            {
                await
                    queueRepository.AddMessageAsync(
                        QueueNames.ToBeProcessed,
                        new CloudQueueMessage(imageRepository.GetUnprocessedUri(imageSeen.Image).AbsoluteUri),
                        cancellationToken);
            }
        }
Esempio n. 7
0
        // This function will get triggered/executed when a new message is written 
        // on an Azure Queue called queue.
        public async static Task NewImagesTrigger([QueueTrigger(QueueNames.NewImages)]CloudQueueMessage message, CancellationToken cancellationToken)
        {
            var connectionFactory = new StorageConnectionFactory(CloudConfigurationManager.GetSetting("storageAccountConnection"));
            var factory = new LoggerFactory();
            factory.AddConsole();
            factory.AddEventLog();

            var logger = factory.CreateLogger("ToprakWebjobs");

            var imageManager = new ImageManagerService(connectionFactory, logger);

            await imageManager.AddToCirculation(true, cancellationToken);

        }
Esempio n. 8
0
        public Program()
        {
            // a DI based application would get ILoggerFactory injected instead
            var factory = new LoggerFactory();

            // getting the logger immediately using the class's name is conventional
            _logger = factory.CreateLogger(typeof(Program).FullName);

            // providers may be added to an ILoggerFactory at any time, existing ILoggers are updated
            #if !DNXCORE50
            factory.AddNLog(new global::NLog.LogFactory());

            factory.AddSerilog(new Serilog.LoggerConfiguration()
                .Enrich.WithMachineName()
                .Enrich.WithProcessId()
                .Enrich.WithThreadId()
                .MinimumLevel.Debug()
                .WriteTo.RollingFile("file-{Date}.txt", outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} {Level}:{EventId} [{SourceContext}] {Message}{NewLine}{Exception}")
                .WriteTo.Sink(new RollingFileSink("file-{Date}.json", new JsonFormatter(), null, null))
                .WriteTo.Sink(new FileSink("dump.txt", new RawFormatter(), null)));
            #endif
            factory.AddConsole();
            factory.AddConsole((category, logLevel) => logLevel >= LogLevel.Critical && category.Equals(typeof(Program).FullName));
        }
Esempio n. 9
0
        // Please set the following connection strings in app.config for this WebJob to run:
        // AzureWebJobsDashboard and AzureWebJobsStorage

        public static void Main()
        {
            var connectionFactory = new StorageConnectionFactory(CloudConfigurationManager.GetSetting("storageAccountConnection"));
            var factory = new LoggerFactory();
            factory.AddConsole();
            factory.AddEventLog();
            var logger = factory.CreateLogger("ToprakWebjobs");

            AppDomain.CurrentDomain.UnhandledException +=
                (sender, args) => { logger.LogCritical(args.ExceptionObject.ToString()); };
        
            var host = new JobHost();
            // The following code ensures that the WebJob will be running continuously
            host.RunAndBlock();
        }
Esempio n. 10
0
        public void ConfigureServices(IServiceCollection services)
        {
            var loggerFactory = new LoggerFactory { MinimumLevel = LogLevel.Debug };
            loggerFactory.AddConsole();
            loggerFactory.AddDebug();

            services.AddMvc(
                config =>
                    {
                        config.Filters.Add(new GlobalFilter(loggerFactory));
                    });

            services.AddScoped<ConsoleLogActionOneFilter>();
            services.AddScoped<ConsoleLogActionTwoFilter>();
            services.AddScoped<ClassConsoleLogActionBaseFilter>();
            services.AddScoped<ClassConsoleLogActionOneFilter>();
        }
Esempio n. 11
0
 public Program()
 {
     var loggerFactory = new LoggerFactory();
     loggerFactory.AddConsole();
     _logger = loggerFactory.CreateLogger<Program>();
 }
Esempio n. 12
0
 public SmokeTests()
 {
     var loggerFactory = new LoggerFactory();
     loggerFactory.AddConsole();
     _logger = loggerFactory.CreateLogger<SmokeTests>();
 }
Esempio n. 13
0
 private ILoggerFactory ConfigureLogging()
 {
     var loggerFactory = new LoggerFactory();
     loggerFactory.AddConsole(RuntimeLogging.Filter);
     #if DEBUG
     loggerFactory.MinimumLevel = LogLevel.Debug;
     #endif
     return loggerFactory;
 }