Пример #1
0
        public void CanCreateLogger()
        {
            var loggerFactory = new LoggerFactory();

            Microsoft.Owin.Logging.ILogger logger = loggerFactory.Create("LoggerFactoryTests");

            Assert.NotNull(logger);
        }
Пример #2
0
        public void CanCreateLogger()
        {
            var loggerFactory = new LoggerFactory();

            var logger = loggerFactory.Create("LoggerFactoryTests");

            Assert.NotNull(logger);
        }
Пример #3
0
        private Tuple<ILoggerFactory, ConsoleSink> SetUpFactory(Func<string, LogLevel, bool> filter)
        {
            var t = SetUp(null);
            var logger = t.Item1;
            var sink = t.Item2;

            var provider = new Mock<ILoggerProvider>();
            provider.Setup(f => f.CreateLogger(
                It.IsAny<string>()))
                .Returns(logger);

            var factory = new LoggerFactory();
            factory.AddProvider(provider.Object);

            return new Tuple<ILoggerFactory, ConsoleSink>(factory, sink);
        }
Пример #4
0
        public void Dispose_ThrowException_SwallowsException()
        {
            // Arrange
            var factory = new LoggerFactory();
            var throwingProvider = new Mock<ILoggerProvider>();
            throwingProvider.As<IDisposable>()
                .Setup(p => p.Dispose())
                .Throws<Exception>();
            factory.AddProvider(throwingProvider.Object);

            // Act
            factory.Dispose();

            // Assert
            throwingProvider.As<IDisposable>()
                .Verify(p => p.Dispose(), Times.Once());
        }
Пример #5
0
        public void EventsAreWritten()
        {
            var eventSeen = false;
            ILogger log = new LoggerConfiguration()
                .WriteTo
                .Observers(events => events
                    .Do(evt => { eventSeen = true; })
                    .Subscribe())
                .CreateLogger();
            var loggerFactory = new LoggerFactory(log);

            loggerFactory
                .Create("LoggerFactoryTests")
                .WriteError("error");

            Assert.True(eventSeen);
        }
Пример #6
0
        public void CanOverrideTraceEventToLogLevelConversion()
        {
            LogEvent eventSeen = null;
            ILogger log = new LoggerConfiguration()
                .WriteTo
                .Observers(events => events
                    .Do(evt => { eventSeen = evt; })
                    .Subscribe())
                .CreateLogger();
            var loggerFactory = new LoggerFactory(log, traceEventType => LogEventLevel.Fatal);

            loggerFactory
                .Create("LoggerFactoryTests")
                .WriteError("error");

            Assert.AreEqual(eventSeen.Level, LogEventLevel.Fatal);
        }
Пример #7
0
        public void Dispose_ProvidersAreDisposed()
        {
            // Arrange
            var factory = new LoggerFactory();
            var disposableProvider1 = CreateProvider();
            var disposableProvider2 = CreateProvider();
            factory.AddProvider(disposableProvider1);
            factory.AddProvider(disposableProvider2);

            // Act
            factory.Dispose();

            // Assert
            Mock.Get<IDisposable>(disposableProvider1)
                    .Verify(p => p.Dispose(), Times.Once());
            Mock.Get<IDisposable>(disposableProvider2)
                     .Verify(p => p.Dispose(), Times.Once());
        }
Пример #8
0
        public static void MultipleLoggers_IsEnabledReturnsCorrectValue(SourceLevels first, SourceLevels second, bool expected)
        {
            // Arrange
            var firstSwitch = new SourceSwitch("FirstSwitch", "First Test Switch");
            firstSwitch.Level = first;

            var secondSwitch = new SourceSwitch("SecondSwitch", "Second Test Switch");
            secondSwitch.Level = second;

            var factory = new LoggerFactory();
            var logger = factory.CreateLogger("Test");

            // Act
            factory.AddTraceSource(firstSwitch, new ConsoleTraceListener());
            factory.AddTraceSource(secondSwitch, new ConsoleTraceListener());

            // Assert
            Assert.Equal(expected, logger.IsEnabled(LogLevel.Information));
        }
Пример #9
0
        public static void IsEnabledReturnsCorrectValue()
        {
            // Arrange
            var testSwitch = new SourceSwitch("TestSwitch", "Level will be set to warning for this test");
            testSwitch.Level = SourceLevels.Warning;

            var factory = new LoggerFactory();
            var logger = factory.CreateLogger("Test");

            // Act
            factory.AddTraceSource(testSwitch, new ConsoleTraceListener());

            // Assert
            Assert.True(logger.IsEnabled(LogLevel.Critical));
            Assert.True(logger.IsEnabled(LogLevel.Error));
            Assert.True(logger.IsEnabled(LogLevel.Warning));
            Assert.False(logger.IsEnabled(LogLevel.Information));
            Assert.False(logger.IsEnabled(LogLevel.Verbose));
        }
Пример #10
0
        public static void DiagnosticsScope_PushesAndPops_LogicalOperationStack()
        {
            // Arrange
            var baseState = "base";
            Trace.CorrelationManager.StartLogicalOperation(baseState);
            var state = "1337state7331";
            
            var factory = new LoggerFactory();
            var logger = factory.CreateLogger("Test");
            factory.AddTraceSource(new SourceSwitch("TestSwitch"), new ConsoleTraceListener());

            // Act
            var a = Trace.CorrelationManager.LogicalOperationStack.Peek();
            var scope = logger.BeginScopeImpl(state);
            var b = Trace.CorrelationManager.LogicalOperationStack.Peek();
            scope.Dispose();
            var c = Trace.CorrelationManager.LogicalOperationStack.Peek();

            // Assert
            Assert.Same(a, c);
            Assert.Same(state, b);
        }
Пример #11
0
        protected override void ConfigureJobServices(IServiceCollection services, IConfigurationRoot configurationRoot)
        {
            services.Configure <CertificateStoreConfiguration>(configurationRoot.GetSection(CertificateStoreConfigurationSectionName));
            SetupDefaultSubscriptionProcessorConfiguration(services, configurationRoot);

            services.AddTransient <IBrokeredMessageSerializer <CertificateValidationMessage>, CertificateValidationMessageSerializer>();
            services.AddTransient <IMessageHandler <CertificateValidationMessage>, CertificateValidationMessageHandler>();

            services.AddTransient <ICertificateStore>(p =>
            {
                var config = p.GetRequiredService <IOptionsSnapshot <CertificateStoreConfiguration> >().Value;
                var targetStorageAccount = CloudStorageAccount.Parse(config.DataStorageAccount);

                var storageFactory = new AzureStorageFactory(targetStorageAccount, config.ContainerName, LoggerFactory.CreateLogger <AzureStorage>());
                var storage        = storageFactory.Create();

                return(new CertificateStore(storage, LoggerFactory.CreateLogger <CertificateStore>()));
            });

            services.AddTransient <ICertificateVerifier, OnlineCertificateVerifier>();
            services.AddTransient <ICertificateValidationService, CertificateValidationService>();
            services.AddTransient <ITelemetryService, TelemetryService>();
            services.AddTransient <ISubscriptionProcessorTelemetryService, TelemetryService>();
            services.AddSingleton(new TelemetryClient());
        }
Пример #12
0
        public void ConsoleLogger_ReloadSettings_CanChangeLogLevel()
        {
            // Arrange
            var settings = new MockConsoleLoggerSettings()
            {
                Cancel = new CancellationTokenSource(),
                Switches =
                {
                    ["Test"] = LogLevel.Information,
                }
            };

            var loggerFactory = new LoggerFactory();
            loggerFactory.AddConsole(settings);

            var logger = loggerFactory.CreateLogger("Test");
            Assert.False(logger.IsEnabled(LogLevel.Verbose));

            settings.Switches["Test"] = LogLevel.Verbose;

            var cancellationTokenSource = settings.Cancel;
            settings.Cancel = new CancellationTokenSource();

            // Act
            cancellationTokenSource.Cancel();

            // Assert
            Assert.True(logger.IsEnabled(LogLevel.Verbose));
        }
Пример #13
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            // setup loging
            ILoggerFactory loggerFactory = new LoggerFactory().AddNLog();
            NLog.LogManager.LoadConfiguration($"nlog.config");
            services.AddSingleton(loggerFactory);
            services.AddLogging(); // Allow ILogger<T>

            // default mvc service settings
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                    .AddCookie(options =>
                    {
                        //options.Cookie.Domain = "www.jingtengtech.com";
                        options.Cookie.Expiration = TimeSpan.FromMinutes(10);
                    });

            services.AddAuthorization(options => options.AddPolicy("SuperAdminOnly",
                policy => policy.Requirements.Add(new RoleRequirement(new PortalRoles[] { PortalRoles.SuperAdmin })))
                );

            // Adds a default in-memory implementation of IDistributedCache.
            services.AddDistributedMemoryCache();

            services.AddSession(options =>
            {
                // Set let session expire after 10 minutes if request idle
                options.IdleTimeout = TimeSpan.FromSeconds(600);
                options.Cookie.HttpOnly = true;
            });

            // register authorization handler
            services.AddSingleton<IAuthorizationHandler, RolePolicyHandler>();

            // initiate core
            services.AddSingleton<IMapper>(ConfigureMapper());
            services.AddSingleton(new SimplePasswordHasher());

#if (DEBUG)
            services.AddSingleton<IConnectionFactory>(new ConnectionFactory(Configuration, "DefaultConnection")); //DefaultConnection
#endif
#if (RELEASE)
            services.AddSingleton<IConnectionFactory>(new ConnectionFactory(Configuration, "ProductionConnection"));
#endif

            // inject repositories
            services.AddScoped<IPortalLoginRepository, PortalLoginRepository>();

            // inject principal for specific classes
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            services.AddTransient<IPrincipal>(
                provider => provider.GetService<IHttpContextAccessor>().HttpContext.User);

            // Have to manually new DefaultSettings because of the .net core's shitty design
            var initConfiguration = new MyTemplate.Core.DefaultSettings(Configuration);
        }
Пример #14
0
 public static void SetLogger(ILoggerCreator loggerCreator)
 {
     LoggerFactory.SetLoggerFunction(loggerCreator);
 }
Пример #15
0
 protected ILoggerFactory CreateLoggerFactory()
 {
     return(_loggerFactory = LoggerFactory.Create(builder => builder.AddEventSourceLogger()));
 }
Пример #16
0
 public void SetUp()
 {
     LoggerFactory.GetInstance().SetLogger(new SysoLogger(3));
 }
        public CollectorService(IEnumerable <string> work_on_this_users_only = null)
        {
            ServiceName  = asc_mail_collection_service_name;
            EventLog.Log = "Application";

            // These Flags set whether or not to handle that specific
            // type of event. Set to true if you need it, false otherwise.
            CanHandlePowerEvent         = false;
            CanHandleSessionChangeEvent = false;
            CanPauseAndContinue         = false;
            CanShutdown = true;
            CanStop     = true;
            try
            {
                _log = LoggerFactory.GetLogger(LoggerFactory.LoggerType.Nlog, "CollectorService");

                _log.Info("Connecting to db...");

                _manager = new MailBoxManager(25, _log);

                var auth_error_warning_timeout =
                    ConfigurationManager.AppSettings["mail.AuthErrorSendWarningAlertTimeout"] != null
                        ? TimeSpan.FromSeconds(
                        Convert.ToInt32(ConfigurationManager.AppSettings["mail.AuthErrorSendWarningAlertTimeout"]))
                        : TimeSpan.FromHours(2);

                _manager.AuthErrorWarningTimeout = auth_error_warning_timeout;

                _log.Info("Auth login error warning timeout is {0}.", auth_error_warning_timeout.ToString());

                var auth_error_disable_mailbox_timeout =
                    ConfigurationManager.AppSettings["mail.AuthErrorDisableMailboxTimeout"] != null
                        ? TimeSpan.FromSeconds(
                        Convert.ToInt32(ConfigurationManager.AppSettings["mail.AuthErrorDisableMailboxTimeout"]))
                        : TimeSpan.FromDays(3);

                _log.Info("Auth login error disable mailbox timeout is {0}.", auth_error_disable_mailbox_timeout.ToString());

                _manager.AuthErrorDisableTimeout = auth_error_disable_mailbox_timeout;

                _log.Info("Creating collector service...");

                var handlers_log   = LoggerFactory.GetLogger(LoggerFactory.LoggerType.Nlog, "MessageHandlers");
                var queue_settings = MailQueueSettings.FromConfig;
                if (work_on_this_users_only != null)
                {
                    queue_settings.WorkOnUsersOnly = work_on_this_users_only.ToList();
                }
                else
                {
                    var user_to_work_on = ConfigurationManager.AppSettings["mail.OneUserMode"];
                    if (!string.IsNullOrEmpty(user_to_work_on))
                    {
                        queue_settings.WorkOnUsersOnly.Add(user_to_work_on);
                    }
                }

                _manager.TenantOverdueDays = queue_settings.OverdueDays;

                var handlers = MessageHandlersSettings.FromConfig(handlers_log, "mail");

                var enable_activity_log = ConfigurationManager.AppSettings["mail.EnableActivityLog"] == null || Convert.ToBoolean(ConfigurationManager.AppSettings["mail.EnableActivityLog"]);

                _manager.EnableActivityLog = enable_activity_log;

                _log.Info("Db aggregator activity log is {0}.", enable_activity_log ? "enabled" : "disabled");

                _collector = new Collector(_manager, queue_settings, handlers);

                _log.Info("Service is ready.");

                AggregatorLogger.Instance.Initialize(_manager, GetServiceIp());
                _log.Info("Aggregator logger initialized.");
            }
            catch (Exception ex)
            {
                _log.Fatal("CollectorService error under constuct: {0}", ex.ToString());
            }
        }
Пример #18
0
        public void GetInstanceThrowsExceptionWhenHttpContextIsNull()
        {
            var factory = new LoggerFactory();

            Logger logger = factory.GetInstance(null);
        }
Пример #19
0
        public void GetAllThrowsExceptionWhenHttpContextIsNull()
        {
            var factory = new LoggerFactory();

            IEnumerable<Logger> loggers = factory.GetAll(null);
        }
Пример #20
0
        private async Task LoggingToMemoryWithoutDICore(LogFileAccessMode accessMode)
        {
            const string logsDirName = "Logs";

            var fileProvider = new MemoryFileProvider();

            var filterOptions = new LoggerFilterOptions {
                MinLevel = LogLevel.Trace
            };

            var options = new FileLoggerOptions
            {
                FileAppender   = new MemoryFileAppender(fileProvider),
                BasePath       = logsDirName,
                FileAccessMode = accessMode,
                FileEncoding   = Encoding.UTF8,
                MaxQueueSize   = 100,
                DateFormat     = "yyMMdd",
                CounterFormat  = "000",
                MaxFileSize    = 10,
                Files          = new[]
                {
                    new LogFileOptions
                    {
                        Path       = "<date>/<date:MM>/logger.log",
                        DateFormat = "yyyy",
                        MinLevel   = new Dictionary <string, LogLevel>
                        {
                            ["Karambolo.Extensions.Logging.File"] = LogLevel.None,
                            [LogFileOptions.DefaultCategoryName]  = LogLevel.Information,
                        }
                    },
                    new LogFileOptions
                    {
                        Path     = "test-<date>-<counter>.log",
                        MinLevel = new Dictionary <string, LogLevel>
                        {
                            ["Karambolo.Extensions.Logging.File"] = LogLevel.Information,
                            [LogFileOptions.DefaultCategoryName]  = LogLevel.None,
                        }
                    },
                },
                TextBuilder   = new CustomLogEntryTextBuilder(),
                IncludeScopes = true,
            };

            var completeCts = new CancellationTokenSource();
            var context     = new TestFileLoggerContext(completeCts.Token, completionTimeout: Timeout.InfiniteTimeSpan);

            context.SetTimestamp(new DateTime(2017, 1, 1, 0, 0, 0, DateTimeKind.Utc));

            var diagnosticEventReceived = false;

            context.DiagnosticEvent += _ => diagnosticEventReceived = true;

            var ex = new Exception();

            var provider = new FileLoggerProvider(context, Options.Create(options));

            try
            {
                using (var loggerFactory = new LoggerFactory(new[] { provider }, filterOptions))
                {
                    ILogger <LoggingTest> logger1 = loggerFactory.CreateLogger <LoggingTest>();

                    logger1.LogInformation("This is a nice logger.");
                    using (logger1.BeginScope("SCOPE"))
                    {
                        logger1.LogWarning(1, "This is a smart logger.");
                        logger1.LogTrace("This won't make it.");

                        using (logger1.BeginScope("NESTED SCOPE"))
                        {
                            ILogger logger2 = loggerFactory.CreateLogger("X");
                            logger2.LogWarning("Some warning.");
                            logger2.LogError(0, ex, "Some failure!");
                        }
                    }
                }
            }
            finally
            {
#if NETCOREAPP3_1 || NET5_0
                await provider.DisposeAsync();
#else
                await Task.CompletedTask;
                provider.Dispose();
#endif
            }

            Assert.True(provider.Completion.IsCompleted);

            Assert.False(diagnosticEventReceived);

            var logFile = (MemoryFileInfo)fileProvider.GetFileInfo($"{logsDirName}/test-{context.GetTimestamp().ToLocalTime():yyMMdd}-000.log");
            Assert.True(logFile.Exists && !logFile.IsDirectory);

            var lines = logFile.ReadAllText(out Encoding encoding).Split(new[] { Environment.NewLine }, StringSplitOptions.None);
            Assert.Equal(Encoding.UTF8, encoding);
            Assert.Equal(new[]
            {
                $"[info]: {typeof(LoggingTest)}[0] @ {context.GetTimestamp().ToLocalTime():o}",
                $"        This is a nice logger.",
                ""
            }, lines);

            logFile = (MemoryFileInfo)fileProvider.GetFileInfo($"{logsDirName}/test-{context.GetTimestamp().ToLocalTime():yyMMdd}-001.log");
            Assert.True(logFile.Exists && !logFile.IsDirectory);

            lines = logFile.ReadAllText(out encoding).Split(new[] { Environment.NewLine }, StringSplitOptions.None);
            Assert.Equal(Encoding.UTF8, encoding);
            Assert.Equal(new[]
            {
                $"[warn]: {typeof(LoggingTest)}[1] @ {context.GetTimestamp().ToLocalTime():o}",
                $"        => SCOPE",
                $"        This is a smart logger.",
                ""
            }, lines);

            logFile = (MemoryFileInfo)fileProvider.GetFileInfo(
                $"{logsDirName}/{context.GetTimestamp().ToLocalTime():yyyy}/{context.GetTimestamp().ToLocalTime():MM}/logger.log");
            Assert.True(logFile.Exists && !logFile.IsDirectory);

            lines = logFile.ReadAllText(out encoding).Split(new[] { Environment.NewLine }, StringSplitOptions.None);
            Assert.Equal(Encoding.UTF8, encoding);
            Assert.Equal(new[]
            {
                $"[warn]: X[0] @ {context.GetTimestamp().ToLocalTime():o}",
                $"        => SCOPE => NESTED SCOPE",
                $"        Some warning.",
                $"[fail]: X[0] @ {context.GetTimestamp().ToLocalTime():o}",
                $"        => SCOPE => NESTED SCOPE",
                $"        Some failure!",
            }
                         .Concat(ex.ToString().Split(new[] { Environment.NewLine }, StringSplitOptions.None))
                         .Append(""), lines);
        }
Пример #21
0
 public static void ClassInitialze(TestContext context)
 {
     // Initialize default log factory
     LoggerFactory.SetCurrent(new TraceSourceLogFactory());
 }
Пример #22
0
        public bool SendDocument()
        {
            // Test logging
            ILogger loggger = LoggerFactory.Create();

            loggger.Info("Logging works.");

            bool result = false;

            try
            {
                // define the RaspConfigurationFile to use
                switch (this.uddiType)
                {
                case UddiType.Production:
                {
                    ConfigurationManager.AppSettings["RaspConfigurationFile"] = "RaspConfiguration.Live.xml";
                    Console.WriteLine("Sending the document through production uddi.");
                    break;
                }

                ////case UddiType.Test:
                ////    {
                ////        ConfigurationManager.AppSettings["RaspConfigurationFile"] = "RaspConfiguration.Test.xml";
                ////        Console.WriteLine("Sending the document through test uddi.");
                ////        break;
                ////    }

                default:
                {
                    throw new NotImplementedException("The uddiType '" + this.uddiType.ToString() + "' not regonized.");
                }
                }

                //CacheConfig v = ConfigurationHandler.GetConfigurationSection<CacheConfig>();

                // Load the document
                XmlDocument xdoc     = new XmlDocument();
                FileInfo    fileInfo = new FileInfo(this.xmlDocumentUrl);

                if (fileInfo.Exists == false)
                {
                    Console.WriteLine("Error - The file does not exist");
                    Console.WriteLine(fileInfo.FullName);
                    // this.Exit();
                    result = false;
                }
                else
                {
                    Console.WriteLine("Start sending the document.");
                    Console.WriteLine(fileInfo.FullName);

                    xdoc.Load(fileInfo.FullName);

                    // Create the OIOSI message object to send, and add the mandatory
                    // MessageIdentifier header
                    OiosiMessage message = new OiosiMessage(xdoc);

                    // Prepare the request

                    Preparation preparation = new Preparation();

                    IRaspRequest request = preparation.PrepareRequest(message, this.uddiType);

                    // Let the user configure his mail account
                    if (request.RequestUri.Scheme == "mailto")
                    {
                        throw new NotImplementedException("Mail sending not implemented - no longer part of RASP.");
                        //GUI.GetMailSettings(request);
                    }

                    // Use the OIOSI library class Request to send the document
                    Console.WriteLine("Starting to send...");
                    Response response;

                    request.GetResponse(message, Guid.NewGuid().ToString(), out response);

                    // Print out the reply
                    GUI.PrintResponse(response);

                    result = true;
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception.ToString());
            }

            return(result);
        }
Пример #23
0
        public FunctionsSyncManagerTests()
        {
            _testRootScriptPath     = Path.GetTempPath();
            _testHostConfigFilePath = Path.Combine(_testRootScriptPath, ScriptConstants.HostMetadataFileName);
            FileUtility.DeleteFileSafe(_testHostConfigFilePath);

            _hostOptions = new ScriptApplicationHostOptions
            {
                ScriptPath   = @"x:\root",
                IsSelfHost   = false,
                LogPath      = @"x:\tmp\log",
                SecretsPath  = @"x:\secrets",
                TestDataPath = @"x:\sampledata"
            };

            string testHostName = "appName.azurewebsites.net";

            _vars = new Dictionary <string, string>
            {
                { EnvironmentSettingNames.WebSiteAuthEncryptionKey, TestHelpers.GenerateKeyHexString() },
                { EnvironmentSettingNames.AzureWebsiteHostName, testHostName }
            };

            ResetMockFileSystem();

            _loggerProvider = new TestLoggerProvider();
            var loggerFactory = new LoggerFactory();

            loggerFactory.AddProvider(_loggerProvider);
            _contentBuilder  = new StringBuilder();
            _mockHttpHandler = new MockHttpHandler(_contentBuilder);
            var httpClient                = CreateHttpClient(_mockHttpHandler);
            var factory                   = new TestOptionsFactory <ScriptApplicationHostOptions>(_hostOptions);
            var tokenSource               = new TestChangeTokenSource();
            var changeTokens              = new[] { tokenSource };
            var optionsMonitor            = new OptionsMonitor <ScriptApplicationHostOptions>(factory, changeTokens, factory);
            var secretManagerProviderMock = new Mock <ISecretManagerProvider>(MockBehavior.Strict);
            var secretManagerMock         = new Mock <ISecretManager>(MockBehavior.Strict);

            secretManagerProviderMock.SetupGet(p => p.Current).Returns(secretManagerMock.Object);
            var hostSecretsInfo = new HostSecretsInfo();

            hostSecretsInfo.MasterKey    = "aaa";
            hostSecretsInfo.FunctionKeys = new Dictionary <string, string>
            {
                { "TestHostFunctionKey1", "aaa" },
                { "TestHostFunctionKey2", "bbb" }
            };
            hostSecretsInfo.SystemKeys = new Dictionary <string, string>
            {
                { "TestSystemKey1", "aaa" },
                { "TestSystemKey2", "bbb" }
            };
            secretManagerMock.Setup(p => p.GetHostSecretsAsync()).ReturnsAsync(hostSecretsInfo);
            Dictionary <string, string> functionSecretsResponse = new Dictionary <string, string>()
            {
                { "TestFunctionKey1", "aaa" },
                { "TestFunctionKey2", "bbb" }
            };

            secretManagerMock.Setup(p => p.GetFunctionSecretsAsync("function1", false)).ReturnsAsync(functionSecretsResponse);

            var configuration      = ScriptSettingsManager.BuildDefaultConfiguration();
            var hostIdProviderMock = new Mock <IHostIdProvider>(MockBehavior.Strict);

            hostIdProviderMock.Setup(p => p.GetHostIdAsync(CancellationToken.None)).ReturnsAsync("testhostid123");
            _mockWebHostEnvironment = new Mock <IScriptWebHostEnvironment>(MockBehavior.Strict);
            _mockWebHostEnvironment.SetupGet(p => p.InStandbyMode).Returns(false);
            _mockEnvironment = new Mock <IEnvironment>(MockBehavior.Strict);
            _mockEnvironment.Setup(p => p.GetEnvironmentVariable(EnvironmentSettingNames.AzureWebsiteArmCacheEnabled)).Returns("1");
            _mockEnvironment.Setup(p => p.GetEnvironmentVariable(EnvironmentSettingNames.AzureWebsiteContainerReady)).Returns("1");
            _mockEnvironment.Setup(p => p.GetEnvironmentVariable(EnvironmentSettingNames.CoreToolsEnvironment)).Returns((string)null);
            _mockEnvironment.Setup(p => p.GetEnvironmentVariable(EnvironmentSettingNames.WebSiteAuthEncryptionKey)).Returns("1");
            _mockEnvironment.Setup(p => p.GetEnvironmentVariable(EnvironmentSettingNames.AzureWebsiteInstanceId)).Returns("1");
            _mockEnvironment.Setup(p => p.GetEnvironmentVariable(EnvironmentSettingNames.AzureWebsiteHostName)).Returns(testHostName);
            _mockEnvironment.Setup(p => p.GetEnvironmentVariable(EnvironmentSettingNames.SkipSslValidation)).Returns((string)null);
            _mockEnvironment.Setup(p => p.GetEnvironmentVariable(EnvironmentSettingNames.AzureWebJobsSecretStorageType)).Returns("blob");
            _hostNameProvider     = new HostNameProvider(_mockEnvironment.Object, loggerFactory.CreateLogger <HostNameProvider>());
            _functionsSyncManager = new FunctionsSyncManager(configuration, hostIdProviderMock.Object, optionsMonitor, new OptionsWrapper <LanguageWorkerOptions>(CreateLanguageWorkerConfigSettings()), loggerFactory.CreateLogger <FunctionsSyncManager>(), httpClient, secretManagerProviderMock.Object, _mockWebHostEnvironment.Object, _mockEnvironment.Object, _hostNameProvider);

            _expectedSyncTriggersPayload = "[{\"authLevel\":\"anonymous\",\"type\":\"httpTrigger\",\"direction\":\"in\",\"name\":\"req\",\"functionName\":\"function1\"}," +
                                           "{\"name\":\"myQueueItem\",\"type\":\"orchestrationTrigger\",\"direction\":\"in\",\"queueName\":\"myqueue-items\",\"connection\":\"DurableStorage\",\"functionName\":\"function2\",\"taskHubName\":\"TestHubValue\"}," +
                                           "{\"name\":\"myQueueItem\",\"type\":\"activityTrigger\",\"direction\":\"in\",\"queueName\":\"myqueue-items\",\"connection\":\"DurableStorage\",\"functionName\":\"function3\",\"taskHubName\":\"TestHubValue\"}]";
        }
 public TestSimpleDbExtractor()
 {
     _loggerFactory = new LoggerFactory();
 }
Пример #25
0
 static void Main(string[] args)
 {
     var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole());
     var factory       = new MessageHandlerFactory(loggerFactory, null);
 }
Пример #26
0
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            String configFolder         = "config";
            String fileName             = "Minerva.properties";
            String filePath             = configFolder + "\\" + fileName;
            IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForSite();

            Stream primaryPropertyStream = null;

            try
            {
                storage.CreateDirectory("config");
                primaryPropertyStream = new IsolatedStorageFileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite, storage);
            }
            catch (IsolatedStorageException)
            {
                // Intended blank
            }
            catch (FileNotFoundException)
            {
                // Intended blank
            }

            String             urlString          = "/Minerva.Client;component/" + filePath;
            StreamResourceInfo streamResourceInfo = Application.GetResourceStream(new Uri(urlString, UriKind.Relative));

            if (streamResourceInfo == null)
            {
#if DEVELOP
                urlString = "/Minerva.Client;component/" + configFolder + "/Osthus.properties";
#else
                urlString = "/Minerva.Client;component/" + configFolder + "/Osthus_Production.properties";
#endif
                streamResourceInfo = Application.GetResourceStream(new Uri(urlString, UriKind.Relative));
            }

            Properties properties = Properties.Application;

            if (streamResourceInfo != null)
            {
                properties.Load(streamResourceInfo.Stream);
            }

            String servicePort = DictionaryExtension.ValueOrDefault(e.InitParams, "serviceport");
            String serviceHost = DictionaryExtension.ValueOrDefault(e.InitParams, "servicehost");

            DictionaryExtension.Loop(e.InitParams, delegate(String key, String value)
            {
                properties.Set(key, value);
            });

            if (servicePort != null)
            {
                properties[ServiceConfigurationConstants.ServiceHostPort] = servicePort;
            }
            if (serviceHost != null)
            {
                properties[ServiceConfigurationConstants.ServiceHostName] = serviceHost;
            }

            properties.Load(primaryPropertyStream);

            Properties.System[ServiceWCFConfigurationConstants.TransferObjectsScope] = ".+";
            Properties.System[EventConfigurationConstants.PollingActive]             = "true";
            Properties.System[ServiceConfigurationConstants.NetworkClientMode]       = "true";
            Properties.System[ServiceConfigurationConstants.GenericTransferMapping]  = "false";
            Properties.System[ServiceConfigurationConstants.IndependentMetaData]     = "false";

            properties[ServiceConfigurationConstants.ServiceBaseUrl] = "${" + ServiceConfigurationConstants.ServiceProtocol + "}://"
                                                                       + "${" + ServiceConfigurationConstants.ServiceHostName + "}" + ":"
                                                                       + "${" + ServiceConfigurationConstants.ServiceHostPort + "}"
                                                                       + "${" + ServiceConfigurationConstants.ServicePrefix + "}";

            properties[ServiceConfigurationConstants.ServiceProtocol] = "http";
            properties[ServiceConfigurationConstants.ServiceHostName] = "localhost.";
            properties[ServiceConfigurationConstants.ServiceHostPort] = "9080";
            properties[ServiceConfigurationConstants.ServicePrefix]   = "/helloworld";

            LoggerFactory.LoggerType = typeof(De.Osthus.Ambeth.Log.ClientLogger);

            Log = LoggerFactory.GetLogger(typeof(App), properties);

            if (Log.InfoEnabled)
            {
                ISet <String> allPropertiesSet = properties.CollectAllPropertyKeys();

                List <String> allPropertiesList = new List <String>(allPropertiesSet);

                allPropertiesList.Sort();

                Log.Info("Property environment:");
                foreach (String property in allPropertiesList)
                {
                    Log.Info("Property " + property + "=" + properties[property]);
                }
            }

            Type         type         = storage.GetType();
            PropertyInfo propertyInfo = null;
            while (type != null)
            {
                propertyInfo = type.GetProperty("RootDirectory", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public);
                if (propertyInfo != null)
                {
                    break;
                }
                type = type.BaseType;
            }
            AssemblyHelper.RegisterAssemblyFromType(typeof(BytecodeModule));
            AssemblyHelper.RegisterAssemblyFromType(typeof(CacheBootstrapModule));
            AssemblyHelper.RegisterAssemblyFromType(typeof(CacheBytecodeModule));
            AssemblyHelper.RegisterAssemblyFromType(typeof(CacheDataChangeBootstrapModule));
            AssemblyHelper.RegisterAssemblyFromType(typeof(DataChangeBootstrapModule));
            AssemblyHelper.RegisterAssemblyFromType(typeof(EventBootstrapModule));
            AssemblyHelper.RegisterAssemblyFromType(typeof(IocBootstrapModule));
            AssemblyHelper.RegisterAssemblyFromType(typeof(MergeBootstrapModule));
            AssemblyHelper.RegisterAssemblyFromType(typeof(CompositeIdModule));
            AssemblyHelper.RegisterAssemblyFromType(typeof(PrivilegeBootstrapModule));
            AssemblyHelper.RegisterAssemblyFromType(typeof(SecurityBootstrapModule));
            AssemblyHelper.RegisterAssemblyFromType(typeof(ServiceBootstrapModule));
            AssemblyHelper.RegisterAssemblyFromType(typeof(MethodDescription));

            AssemblyHelper.RegisterAssemblyFromType(typeof(MinervaCoreBootstrapModule));
            AssemblyHelper.RegisterAssemblyFromType(typeof(RESTBootstrapModule));
            AssemblyHelper.RegisterAssemblyFromType(typeof(XmlBootstrapModule));
            AssemblyHelper.RegisterAssemblyFromType(typeof(FilterDescriptor));

            AssemblyHelper.RegisterAssemblyFromType(typeof(HelloWorldModule));
            AssemblyHelper.InitAssemblies("ambeth\\..+", "minerva\\..+");

            properties[XmlConfigurationConstants.PackageScanPatterns]   = @"De\.Osthus(?:\.Ambeth|\.Minerva)(?:\.[^\.]+)*(?:\.Transfer|\.Model|\.Service)\..+";
            properties[CacheConfigurationConstants.FirstLevelCacheType] = "SINGLETON";
            properties[CacheConfigurationConstants.OverwriteToManyRelationsInChildCache] = "false";
            properties[CacheConfigurationConstants.UpdateChildCache]        = "true";
            properties[MinervaCoreConfigurationConstants.EntityProxyActive] = "true";
            properties[ServiceConfigurationConstants.TypeInfoProviderType]  = typeof(MergeTypeInfoProvider).FullName;

            // Set this to false, to test with mocks (offline)
            bool Online = true;

            properties[CacheConfigurationConstants.CacheServiceBeanActive]           = Online.ToString();
            properties[EventConfigurationConstants.EventServiceBeanActive]           = Online.ToString();
            properties[MergeConfigurationConstants.MergeServiceBeanActive]           = Online.ToString();
            properties[SecurityConfigurationConstants.SecurityServiceBeanActive]     = Online.ToString();
            properties[HelloWorldConfigurationConstants.HelloWorldServiceBeanActive] = Online.ToString();
            properties[MergeConfigurationConstants.MergeServiceMockType]             = typeof(HelloWorldMergeMock).FullName;
//already default:            properties[RESTConfigurationConstants.HttpAcceptEncodingZipped] = "true";
//already default:            properties[RESTConfigurationConstants.HttpContentEncodingZipped] = "true";
//already default:            properties[RESTConfigurationConstants.HttpUseClient] = "true";

            IServiceContext bootstrapContext = BeanContextFactory.CreateBootstrap(properties);

            try
            {
                // Create child context and override root context
                BeanContext = bootstrapContext.CreateService(delegate(IBeanContextFactory bcf)
                {
                    bcf.RegisterAnonymousBean <MainPageModule>();
                    bcf.RegisterAnonymousBean(typeof(HelloWorldModule));
                    AssemblyHelper.HandleTypesFromCurrentDomainWithAnnotation <FrameworkModuleAttribute>(delegate(Type bootstrapModuleType)
                    {
                        //if (!typeof(IInitializingBootstrapMockModule).IsAssignableFrom(bootstrapModuleType))
                        {
                            if (Log.InfoEnabled)
                            {
                                Log.Info("Autoresolving bootstrap module: '" + bootstrapModuleType.FullName + "'");
                            }
                            bcf.RegisterAnonymousBean(bootstrapModuleType);
                        }
                    });
                    bcf.RegisterExternalBean("app", this);
                }, typeof(RESTBootstrapModule));
                FlattenHierarchyProxy.Context = BeanContext;

                BeanContext.GetService <IThreadPool>().Queue(delegate()
                {
                    double result  = BeanContext.GetService <IHelloWorldService>().DoFunnyThings(5, "hallo");
                    double result2 = BeanContext.GetService <IHelloWorldService>().DoFunnyThings(6, "hallo");
                    if (Math.Abs(result - result2) != 1)
                    {
                        throw new Exception("Process execution failed with unexpected result value: " + result + "/" + result2);
                    }
                    Log.Info("" + result);
                    //Type enhancedType = BeanContext.GetService<IBytecodeEnhancer>().GetEnhancedType(typeof(TestEntity), EntityEnhancementHint.HOOK);
                    //TestEntity instance = (TestEntity)Activator.CreateInstance(enhancedType);
                    //instance.Id = 1;
                    //IEntityMetaData metaData = BeanContext.GetService<IEntityMetaDataProvider>().GetMetaData(enhancedType);
                    //IObjRelation result3 = ((IValueHolderContainer)instance).GetSelf("Relation");
                    //Object targetCache = ((IValueHolderContainer)instance).TargetCache;
                    //((IValueHolderContainer)instance).TargetCache = new ChildCache();
                    //Console.WriteLine("TestT");
                });
                SynchronizationContext syncContext = BeanContext.GetService <SynchronizationContext>();

                syncContext.Post((object state) =>
                {
                    RootVisual = BeanContext.GetService <UIElement>("mainPage");
                }, null);
            }
            catch (Exception ex)
            {
                if (Log.ErrorEnabled)
                {
                    Log.Error(ex);
                }
                throw;
            }
        }
Пример #27
0
 protected override void OnConfiguring(DbContextOptionsBuilder options)
 {
     options.UseLoggerFactory(LoggerFactory.Create(builder => builder.AddDebug()));
     options.UseSqlServer(_connectionStrings.SQL);
 }
Пример #28
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            var sqlLoggerFactory = new LoggerFactory();

            sqlLoggerFactory.AddConsole(Configuration.GetSection("SqlLogging"));

            var entityFramework = services;

            if (WebAppConfiguration.TDataBaseServerType == Message.TDataBaseServerType.PostgreSQL)
            {
                entityFramework = entityFramework.AddEntityFrameworkNpgsql().AddDbContext <ApplicationDbContext>(options =>
                                                                                                                 options.UseNpgsql(WebAppConfiguration.DatabaseConnectionString).UseLoggerFactory(sqlLoggerFactory));
            }
            else if (WebAppConfiguration.TDataBaseServerType == Message.TDataBaseServerType.SqlServer)
            {
                entityFramework = entityFramework.AddEntityFrameworkSqlServer().AddDbContext <ApplicationDbContext>(options =>
                                                                                                                    options.UseSqlServer(WebAppConfiguration.DatabaseConnectionString).UseLoggerFactory(sqlLoggerFactory));
            }
            else
            {
                _logger.LogError("Unknown database connection type");
            }

            services.AddIdentity <ApplicationUser, IdentityRole>(
                o => {
                o.Password.RequireDigit           = false;
                o.Password.RequireLowercase       = false;
                o.Password.RequireUppercase       = false;
                o.Password.RequireNonAlphanumeric = false;
                o.Password.RequiredLength         = 6;
            }).AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();

            //Link my own Localizer
            services.AddSingleton <IStringLocalizerFactory, StringLocalizerFactory>();

            services.AddLocalization(options => options.ResourcesPath = "Resources");

            services.Configure <IdentityOptions>(options =>
            {
                options.Cookies.ApplicationCookie.ExpireTimeSpan = TimeSpan.FromDays(10);
                options.Cookies.ApplicationCookie.LoginPath      = new Microsoft.AspNetCore.Http.PathString("/Site/Account/Login");
                options.Cookies.ApplicationCookie.Events         = new CookieAuthenticationEvents
                {
                    OnRedirectToAccessDenied = ctx => {
                        if (ctx.Request.Path.StartsWithSegments("/api"))
                        {
                            ctx.Response.StatusCode = 403;
                        }
                        else
                        {
                            ctx.Response.Redirect(ctx.RedirectUri);
                        }
                        return(Task.FromResult(0));
                    },
                    OnRedirectToLogin = ctx => {
                        if (ctx.Request.Path.StartsWithSegments("/api") && ctx.Response.StatusCode == 200)
                        {
                            ctx.Response.StatusCode = 401;
                        }
                        else
                        {
                            ctx.Response.Redirect(ctx.RedirectUri);
                        }
                        return(Task.FromResult(0));
                    },
                };
            });


            /*
             * services.Configure<CookieAuthenticationOptions>(opt =>
             * {
             *  opt.AccessDeniedPath = "/Site/Home/Index";
             *  opt.LogoutPath = "/Site/Account/Login";
             *  opt.LoginPath = "/Site/Account/Login";
             * });
             */

            services.AddMvc().AddViewLocalization(options => options.ResourcesPath = "Resources").AddDataAnnotationsLocalization();

            services.AddAuthorization(options =>
            {
                options.AddPolicy("AllowLocalhost",
                                  policy => policy.Requirements.Add(new LoopBackAuthorizeRequirement()));
            });
            services.AddSingleton <IAuthorizationHandler, LoopBackAuthorizeHandler>();

            //Add service for manage cache data
            services.AddMemoryCache();

            // Add application services.
            services.AddTransient <IEmailSender, AuthMessageSender>();
            services.AddTransient <ISmsSender, AuthMessageSender>();
            services.AddTransient <ViewHelper>();

            ConfigureServiceDataLayer(services);

            services.Configure <RequestLocalizationOptions>(options =>
            {
                DefineLocalization(options);
            });

            WebAppConfiguration.ServiceProvider = services.BuildServiceProvider();
        }
Пример #29
0
        static async Task Main(string[] args)
        {
            // DI
            var services = new ServiceCollection();

            var loggerFactory = LoggerFactory.Create(logging =>
            {
                logging.AddConsole();
                logging.SetMinimumLevel(LogLevel.Debug);
            });

            Func <HttpRequestMessage, IAsyncPolicy <HttpResponseMessage> > retryFunc = (request) =>
            {
                return(Policy.HandleResult <HttpResponseMessage>(r => {
                    var grpcStatus = StatusManager.GetStatusCode(r);
                    return r.StatusCode != HttpStatusCode.OK && grpcStatus != StatusCode.OK && grpcStatus != StatusCode.InvalidArgument;
                })
                       .WaitAndRetryAsync(3, (input) => TimeSpan.FromSeconds(3 + input), (result, timeSpan, retryCount, context) =>
                {
                    var grpcStatus = StatusManager.GetStatusCode(result.Result);
                    Console.WriteLine($"Request failed with {grpcStatus}. Retry");
                }));
            };

            /*
             * // https://grpcwebdemo.azurewebsites.net
             * // gRPC
             * services.AddGrpcClient<CountryServiceClient>(o =>
             * {
             *  o.Address = new Uri("https://localhost:5001");
             * }).AddPolicyHandler(retryFunc);
             * var provider = services.BuildServiceProvider();
             * var client = provider.GetRequiredService<CountryServiceClient>();
             */

            // gRPC-Web
            var handler = new GrpcWebHandler(GrpcWebMode.GrpcWebText, new HttpClientHandler());
            var channel = GrpcChannel.ForAddress("https://grpcwebdemo.azurewebsites.net", new GrpcChannelOptions
            {
                HttpClient    = new HttpClient(handler),
                LoggerFactory = loggerFactory
            });
            var clientWeb = new CountryServiceClient(channel);

            try
            {
                /*
                 * // Create
                 * var createdCountry = await client.CreateAsync(new CountryCreateRequest { Name = "Japan", Description = "" }); // Remove Name or Description to test validation
                 * var country = new Country
                 * {
                 *  CountryId = createdCountry.Id,
                 *  CountryName = createdCountry.Name,
                 *  Description = createdCountry.Description
                 * };
                 * Console.WriteLine($"Country {country.CountryName} ({country.CountryId}) created!");
                 *
                 *
                 * // GetById
                 * var foundCountry = await client.GetByIdAsync(new CountrySearchRequest { CountryId = country.CountryId });
                 * country = new Country
                 * {
                 *  CountryId = foundCountry.Id,
                 *  CountryName = foundCountry.Name,
                 *  Description = foundCountry.Description
                 * };
                 * Console.WriteLine($"Found country {country.CountryName} ({country.CountryId})");
                 *
                 *
                 * // Update
                 * var updatedCountry = await client.UpdateAsync(new CountryRequest { Id = country.CountryId, Name = "Japan", Description = "rising sun country, Nippon!!!" });
                 * country = new Country
                 * {
                 *  CountryId = updatedCountry.Id,
                 *  CountryName = updatedCountry.Name,
                 *  Description = updatedCountry.Description
                 * };
                 * Console.WriteLine($"Country {country.CountryName} ({country.CountryId}) updated with new description: {country.Description}");
                 *
                 * // Delete
                 * await client.DeleteAsync(new CountrySearchRequest { CountryId = country.CountryId });
                 * Console.WriteLine($"Deleted country {country.CountryName} ({country.CountryId})");
                 */

                /*
                 * // Get all gRPC
                 * var countries = (await client.GetAllAsync(new EmptyRequest())).Countries.Select(x => new Country
                 * {
                 *  CountryId = x.Id,
                 *  Description = x.Description,
                 *  CountryName = x.Name
                 * }).ToList();
                 *
                 * Console.WriteLine("Found countries");
                 * countries.ForEach(x => Console.WriteLine($"Found country {x.CountryName} ({x.CountryId}) {x.Description}"));
                 */


                // Get all gRPC - web
                var countriesweb = (await clientWeb.GetAllAsync(new EmptyRequest())).Countries.Select(x => new Country
                {
                    CountryId   = x.Id,
                    Description = x.Description,
                    CountryName = x.Name
                }).ToList();

                Console.WriteLine("Found countries with gRPC-Web");
                countriesweb.ForEach(x => Console.WriteLine($"Found country with gRPC-Web:  {x.CountryName} ({x.CountryId}) {x.Description}"));


                //var handler2 = new GrpcWebHandler(GrpcWebMode.GrpcWebText, new HttpClientHandler());
                //var channel2 = GrpcChannel.ForAddress("https://grpcweb.azurewebsites.net/", new GrpcChannelOptions
                //{
                //    HttpClient = new HttpClient(handler2),
                //    LoggerFactory = loggerFactory
                //});
                //var clientweb2 = new Greeter.GreeterClient(channel2);
                //var response = await clientweb2.SayHelloAsync(new HelloRequest { Name = ".NET" });

                //Console.WriteLine(response.Message);
            }
            catch (RpcException e)
            {
                var errors = e.GetValidationErrors(); // Gets validation errors list
                Console.WriteLine(e.Message);
            }
        }
Пример #30
0
        private async Task RebuildPackageReports(CloudBlobContainer destinationContainer, DateTime reportGenerationTime)
        {
            var dirtyPackageIds = await ReportDataCollector.GetDirtyPackageIds(LoggerFactory.CreateLogger <ReportDataCollector>(), _statisticsDatabase, reportGenerationTime);

            if (!dirtyPackageIds.Any())
            {
                return;
            }

            // first process the top 100 packages
            var top100 = dirtyPackageIds.Take(100);
            var reportDataCollector = new ReportDataCollector(LoggerFactory.CreateLogger <ReportDataCollector>(), _storedProceduresPerPackageId[ReportNames.RecentPopularityDetailByPackageId], _statisticsDatabase);
            var top100Task          = Parallel.ForEach(top100, new ParallelOptions {
                MaxDegreeOfParallelism = 4
            }, dirtyPackageId =>
            {
                var packageId     = dirtyPackageId.PackageId.ToLowerInvariant();
                var reportBuilder = new RecentPopularityDetailByPackageReportBuilder(LoggerFactory.CreateLogger <RecentPopularityDetailByPackageReportBuilder>(), ReportNames.RecentPopularityDetailByPackageId, "recentpopularity/" + _recentPopularityDetailByPackageReportBaseName + packageId);

                ProcessReport(LoggerFactory, destinationContainer, reportBuilder, reportDataCollector, reportGenerationTime, Tuple.Create("@PackageId", 128, dirtyPackageId.PackageId)).Wait();
                ApplicationInsightsHelper.TrackReportProcessed(reportBuilder.ReportName + " report", packageId);
            });

            // once top 100 is processed, continue with the rest
            if (top100Task.IsCompleted)
            {
                var excludingTop100 = dirtyPackageIds.Skip(100);

                top100Task = Parallel.ForEach(excludingTop100, new ParallelOptions {
                    MaxDegreeOfParallelism = 8
                },
                                              dirtyPackageId =>
                {
                    // generate all reports
                    var reportGenerators = new Dictionary <ReportBuilder, ReportDataCollector>
                    {
                        {
                            new RecentPopularityDetailByPackageReportBuilder(
                                LoggerFactory.CreateLogger <RecentPopularityDetailByPackageReportBuilder>(),
                                ReportNames.RecentPopularityDetailByPackageId,
                                "recentpopularity/" + _recentPopularityDetailByPackageReportBaseName +
                                dirtyPackageId.PackageId.ToLowerInvariant()),
                            new ReportDataCollector(
                                LoggerFactory.CreateLogger <ReportDataCollector>(),
                                _storedProceduresPerPackageId[ReportNames.RecentPopularityDetailByPackageId],
                                _statisticsDatabase)
                        }
                    };

                    foreach (var reportGenerator in reportGenerators)
                    {
                        ProcessReport(LoggerFactory, destinationContainer, reportGenerator.Key, reportGenerator.Value,
                                      reportGenerationTime, Tuple.Create("@PackageId", 128, dirtyPackageId.PackageId)).Wait();
                        ApplicationInsightsHelper.TrackReportProcessed(reportGenerator.Key.ReportName + " report",
                                                                       dirtyPackageId.PackageId.ToLowerInvariant());
                    }
                });

                if (top100Task.IsCompleted)
                {
                    var runToCursor = dirtyPackageIds.First().RunToCuror;
                    await ReportDataCollector.UpdateDirtyPackageIdCursor(_statisticsDatabase, runToCursor);
                }
            }
        }
Пример #31
0
        private const long MAX_DEBUG_LOG_FILE_SIZE = 2000000; // If debug log is in use roll it every N MB.

        static void Main(string[] args)
        {
            ServicePointManager.DefaultConnectionLimit = 100;
            IWebHost host      = null;
            var      processor = new ConsoleLoggerProcessor();
            CustomConsoleLogProvider loggerProvider = new CustomConsoleLogProvider(processor);
            var loggerFactory = new LoggerFactory();

            loggerFactory.AddProvider(loggerProvider);
            var logger = loggerFactory.CreateLogger("Configuration");

            try
            {
                // This is the only way that LoadArgs can print to console. Because LoadArgs is called by the HostBuilder before Logs.Configure is called
                var conf = new DefaultConfiguration()
                {
                    Logger = logger
                }.CreateConfiguration(args);
                if (conf == null)
                {
                    return;
                }
                Logs.Configure(loggerFactory);
                new BTCPayServerOptions().LoadArgs(conf);
                Logs.Configure(null);
                /////

                host = new WebHostBuilder()
                       .UseKestrel()
                       .UseIISIntegration()
                       .UseContentRoot(Directory.GetCurrentDirectory())
                       .UseConfiguration(conf)
                       .ConfigureLogging(l =>
                {
                    l.AddFilter("Microsoft", LogLevel.Error);
                    l.AddFilter("Microsoft.AspNetCore.Antiforgery.Internal", LogLevel.Critical);
                    l.AddProvider(new CustomConsoleLogProvider(processor));

                    // Use Serilog for debug log file.
                    var debugLogFile = BTCPayServerOptions.GetDebugLog(conf);
                    if (string.IsNullOrEmpty(debugLogFile) != false)
                    {
                        return;
                    }
                    Serilog.Log.Logger = new LoggerConfiguration()
                                         .Enrich.FromLogContext()
                                         .MinimumLevel.Is(BTCPayServerOptions.GetDebugLogLevel(conf))
                                         .WriteTo.File(debugLogFile, rollingInterval: RollingInterval.Day, fileSizeLimitBytes: MAX_DEBUG_LOG_FILE_SIZE, rollOnFileSizeLimit: true, retainedFileCountLimit: 1)
                                         .CreateLogger();

                    l.AddSerilog(Serilog.Log.Logger);
                })
                       .UseStartup <Startup>()
                       .Build();
                host.StartAsync().GetAwaiter().GetResult();
                var urls = host.ServerFeatures.Get <IServerAddressesFeature>().Addresses;
                foreach (var url in urls)
                {
                    logger.LogInformation("Listening on " + url);
                }
                host.WaitForShutdown();
            }
            catch (ConfigException ex)
            {
                if (!string.IsNullOrEmpty(ex.Message))
                {
                    Logs.Configuration.LogError(ex.Message);
                }
            }
            finally
            {
                processor.Dispose();
                if (host == null)
                {
                    Logs.Configuration.LogError("Configuration error");
                }
                if (host != null)
                {
                    host.Dispose();
                }
                Serilog.Log.CloseAndFlush();
                loggerProvider.Dispose();
            }
        }
Пример #32
0
 public void SomeVideosWereFound(Video[] videos, string channelId)
 {
     DbWriter.Write(videos, channelId, LoggerFactory.GetTestLogger());
 }
        public async Task ShouldRouteToCorrect_Request_WithManyHandlers()
        {
            var textDocumentSyncHandler =
                TextDocumentSyncHandlerExtensions.With(DocumentSelector.ForPattern("**/*.cs"), "csharp");
            var textDocumentSyncHandler2 =
                TextDocumentSyncHandlerExtensions.With(DocumentSelector.ForPattern("**/*.cake"), "csharp");

            textDocumentSyncHandler.Handle(Arg.Any <DidSaveTextDocumentParams>(), Arg.Any <CancellationToken>())
            .Returns(Unit.Value);
            textDocumentSyncHandler2.Handle(Arg.Any <DidSaveTextDocumentParams>(), Arg.Any <CancellationToken>())
            .Returns(Unit.Value);

            var codeActionHandler = Substitute.For <ICodeActionHandler>();

            codeActionHandler.GetRegistrationOptions().Returns(new CodeActionRegistrationOptions {
                DocumentSelector = DocumentSelector.ForPattern("**/*.cs")
            });
            codeActionHandler
            .Handle(Arg.Any <CodeActionParams>(), Arg.Any <CancellationToken>())
            .Returns(new CommandOrCodeActionContainer());

            var registry           = new TestLanguageServerRegistry();
            var codeActionDelegate =
                Substitute.For <Func <CodeActionParams, CancellationToken, Task <CommandOrCodeActionContainer> > >();

            codeActionDelegate.Invoke(Arg.Any <CodeActionParams>(), Arg.Any <CancellationToken>())
            .Returns(new CommandOrCodeActionContainer());
            registry.OnCodeAction(
                codeActionDelegate,
                new CodeActionRegistrationOptions {
                DocumentSelector = DocumentSelector.ForPattern("**/*.cake")
            }
                );

            var textDocumentIdentifiers = new TextDocumentIdentifiers();

            AutoSubstitute.Provide(textDocumentIdentifiers);
            var handlerCollection =
                new SharedHandlerCollection(
                    SupportedCapabilitiesFixture.AlwaysTrue, textDocumentIdentifiers, Substitute.For <IResolverContext>(),
                    new LspHandlerTypeDescriptorProvider(
                        new[] {
                typeof(FoundationTests).Assembly, typeof(LanguageServer).Assembly, typeof(LanguageClient).Assembly, typeof(IRegistrationManager).Assembly,
                typeof(LspRequestRouter).Assembly
            }
                        )
                    )
            {
                textDocumentSyncHandler, textDocumentSyncHandler2, codeActionHandler
            };

            AutoSubstitute.Provide <IHandlerCollection>(handlerCollection);
            AutoSubstitute.Provide <IEnumerable <ILspHandlerDescriptor> >(handlerCollection);
            AutoSubstitute.Provide <IHandlerMatcher>(new TextDocumentMatcher(LoggerFactory.CreateLogger <TextDocumentMatcher>(), textDocumentIdentifiers));
            var mediator = AutoSubstitute.Resolve <LspRequestRouter>();

            var id      = Guid.NewGuid().ToString();
            var @params = new CodeActionParams {
                TextDocument = new TextDocumentIdentifier(new Uri("file:///c:/test/123.cake"))
            };

            var request = new Request(
                id, TextDocumentNames.CodeAction,
                JObject.Parse(JsonConvert.SerializeObject(@params, new LspSerializer(ClientVersion.Lsp3).Settings))
                );

            await mediator.RouteRequest(mediator.GetDescriptors(request), request, CancellationToken.None);

            await codeActionHandler.Received(0).Handle(Arg.Any <CodeActionParams>(), Arg.Any <CancellationToken>());

            await codeActionDelegate.Received(1).Invoke(Arg.Any <CodeActionParams>(), Arg.Any <CancellationToken>());
        }
Пример #34
0
            /// <summary>
            /// 从指定url获取数据
            /// </summary>
            /// <param name="url"></param>
            /// <returns></returns>
            public static ResponseData GetResult(string url)
            {
                try
                {
                    ResponseData   data            = new ResponseData();
                    string         responseContent = string.Empty;
                    HttpWebRequest request         = (HttpWebRequest)WebRequest.Create(url);
                    request.Timeout = 10000;
                    var response = request.GetResponse();
                    if (response == null)
                    {
                        return(data);
                    }

                    var contentType = response.ContentType.ToLower().Split(new char[] { ';' })[0];

                    //是文本类型直接返回
                    string[] contentTypes = { "application/json", "text/xml", "text/html", "text/plain" };
                    if (contentTypes.Contains(contentType))
                    {
                        using (Stream stream = response.GetResponseStream())
                        {
                            StreamReader reader = new StreamReader(stream, Encoding.GetEncoding(REQUESTENCODING));
                            data.Content = reader.ReadToEnd();
                            reader.Dispose();
                        }

                        LoggerFactory.GetLogger().Debug(string.Format("HttpGet-{0}:{1}", url, data.Content));

                        return(data);
                    }
                    //文件类型,处理文件
                    Dictionary <string, string> dic = new Dictionary <string, string>();
                    foreach (var key in response.Headers.AllKeys)
                    {
                        string _key = key.ToLower();
                        var    k    = _key.Replace("-", "");
                        //获取文件 content-disposition,主要用户Get时获取filename
                        if (_key == "content-disposition")
                        {
                            var dispositions = response.Headers[key].Split(new char[] { ';' });
                            if (dispositions.Length > 0)
                            {
                                foreach (var disposition in dispositions)
                                {
                                    var items = disposition.Split(new char[] { '=' });
                                    if (items.Length >= 2)
                                    {
                                        dic.Add(items[0].Trim(), items[1].Replace("\"", ""));
                                    }
                                }
                            }
                            continue;
                        }
                        dic.Add(k, response.Headers[key]);
                    }

                    data.Content = JsonHelper.Encode(dic);
                    var responseStream = response.GetResponseStream();
                    var mstream        = new MemoryStream();
                    responseStream.CopyTo(mstream);
                    data.Stream = mstream;
                    responseStream.Dispose();
                    response.Close();
                    return(data);
                }
                catch (Exception ex)
                {
                    LoggerFactory.GetLogger().Error(string.Format("HttpGet发生错误-{0}", url));
                    throw ex;
                }
            }
Пример #35
0
 static ImageTest()
 {
     LoggerFactory.GetInstance().SetLogger(new SysoLogger(5));
 }
 public MembershipTableCleanupAgentTests(ITestOutputHelper output)
 {
     this.output        = output;
     this.loggerFactory = new LoggerFactory(new[] { new XunitLoggerProvider(this.output) });
 }
Пример #37
0
        public void ConsoleLogger_ReloadSettings_CanReloadMultipleTimes()
        {
            // Arrange
            var settings = new MockConsoleLoggerSettings()
            {
                Cancel = new CancellationTokenSource(),
                Switches =
                {
                    ["Test"] = LogLevel.Information,
                }
            };

            var loggerFactory = new LoggerFactory();
            loggerFactory.AddConsole(settings);

            var logger = loggerFactory.CreateLogger("Test");
            Assert.False(logger.IsEnabled(LogLevel.Verbose));

            // Act & Assert
            for (var i = 0; i < 10; i++)
            {
                settings.Switches["Test"] = i % 2 == 0 ? LogLevel.Information : LogLevel.Verbose;

                var cancellationTokenSource = settings.Cancel;
                settings.Cancel = new CancellationTokenSource();

                cancellationTokenSource.Cancel();

                Assert.Equal(i % 2 == 1, logger.IsEnabled(LogLevel.Verbose));
            }
        }
Пример #38
0
 public DownloadBase(enDataProviderType dataProviderType)
 {
     _dataProviderType = dataProviderType;
     _logger           = LoggerFactory.GetInstance();
 }
        public static Task <RazorLanguageServer> CreateAsync(Stream input, Stream output, Trace trace, Action <RazorLanguageServerBuilder> configure = null)
        {
            Serializer.Instance.JsonSerializer.Converters.RegisterRazorConverters();

            // Custom ClientCapabilities deserializer to extract experimental capabilities
            Serializer.Instance.JsonSerializer.Converters.Add(ExtendableClientCapabilitiesJsonConverter.Instance);

            ILanguageServer server   = null;
            var             logLevel = RazorLSPOptions.GetLogLevelForTrace(trace);
            var             initializedCompletionSource = new TaskCompletionSource <bool>();

            server = OmniSharp.Extensions.LanguageServer.Server.LanguageServer.PreInit(options =>
                                                                                       options
                                                                                       .WithInput(input)
                                                                                       .WithOutput(output)
                                                                                       // StreamJsonRpc has both Serial and Parallel requests. With WithContentModifiedSupport(true) (which is default) when a Serial
                                                                                       // request is made any Parallel requests will be cancelled because the assumption is that Serial requests modify state, and that
                                                                                       // therefore any Parallel request is now invalid and should just try again. A specific instance of this can be seen when you
                                                                                       // hover over a TagHelper while the switch is set to true. Hover is parallel, and a lot of our endpoints like
                                                                                       // textDocument/_ms_onAutoInsert, and razor/languageQuery are Serial. I BELIEVE that specifically what happened is the serial
                                                                                       // languageQuery event gets fired by our semantic tokens endpoint (which fires constantly), cancelling the hover, which red-bars.
                                                                                       // We can prevent that behavior entirely by doing WithContentModifiedSupport, at the possible expense of some delays due doing all requests in serial.
                                                                                       //
                                                                                       // I recommend that we attempt to resolve this and switch back to WithContentModifiedSupport(true) in the future,
                                                                                       // I think that would mean either having 0 Serial Handlers in the whole LS, or making VSLanguageServerClient handle this more gracefully.
                                                                                       .WithContentModifiedSupport(false)
                                                                                       .WithSerializer(Serializer.Instance)
                                                                                       .OnInitialized(async(s, request, response, cancellationToken) =>
            {
                var handlersManager        = s.GetRequiredService <IHandlersManager>();
                var jsonRpcHandlers        = handlersManager.Descriptors.Select(d => d.Handler);
                var registrationExtensions = jsonRpcHandlers.OfType <IRegistrationExtension>().Distinct();
                if (registrationExtensions.Any())
                {
                    var capabilities      = new ExtendableServerCapabilities(response.Capabilities, registrationExtensions);
                    response.Capabilities = capabilities;
                }
                var fileChangeDetectorManager = s.Services.GetRequiredService <RazorFileChangeDetectorManager>();
                await fileChangeDetectorManager.InitializedAsync();

                // Workaround for https://github.com/OmniSharp/csharp-language-server-protocol/issues/106
                var languageServer = (OmniSharp.Extensions.LanguageServer.Server.LanguageServer)server;
                if (request.Capabilities.Workspace.Configuration.IsSupported)
                {
                    // Initialize our options for the first time.
                    var optionsMonitor = languageServer.Services.GetRequiredService <RazorLSPOptionsMonitor>();

                    // Explicitly not passing in the same CancellationToken as that might get cancelled before the update happens.
                    _ = Task.Delay(TimeSpan.FromSeconds(3))
                        .ContinueWith(async(_) => await optionsMonitor.UpdateAsync(), TaskScheduler.Default);
                }
            })
                                                                                       .WithHandler <RazorDocumentSynchronizationEndpoint>()
                                                                                       .WithHandler <RazorCompletionEndpoint>()
                                                                                       .WithHandler <RazorHoverEndpoint>()
                                                                                       .WithHandler <RazorLanguageEndpoint>()
                                                                                       .WithHandler <RazorDiagnosticsEndpoint>()
                                                                                       .WithHandler <RazorConfigurationEndpoint>()
                                                                                       .WithHandler <RazorFormattingEndpoint>()
                                                                                       .WithHandler <RazorSemanticTokensEndpoint>()
                                                                                       .AddHandlerLink(LanguageServerConstants.RazorSemanticTokensEditEndpoint, LanguageServerConstants.LegacyRazorSemanticTokensEditEndpoint)
                                                                                       .AddHandlerLink(LanguageServerConstants.RazorSemanticTokensEndpoint, LanguageServerConstants.LegacyRazorSemanticTokensEndpoint)
                                                                                       .WithHandler <RazorSemanticTokensLegendEndpoint>()
                                                                                       .WithHandler <OnAutoInsertEndpoint>()
                                                                                       .WithHandler <CodeActionEndpoint>()
                                                                                       .WithHandler <CodeActionResolutionEndpoint>()
                                                                                       .WithHandler <MonitorProjectConfigurationFilePathEndpoint>()
                                                                                       .WithHandler <RazorComponentRenameEndpoint>()
                                                                                       .WithHandler <RazorDefinitionEndpoint>()
                                                                                       .WithServices(services =>
            {
                services.AddLogging(builder => builder
                                    .SetMinimumLevel(logLevel)
                                    .AddLanguageProtocolLogging(logLevel));

                var filePathNormalizer = new FilePathNormalizer();
                services.AddSingleton <FilePathNormalizer>(filePathNormalizer);

                var foregroundDispatcher = new DefaultForegroundDispatcher();
                services.AddSingleton <ForegroundDispatcher>(foregroundDispatcher);

                var generatedDocumentPublisher = new DefaultGeneratedDocumentPublisher(foregroundDispatcher, new Lazy <OmniSharp.Extensions.LanguageServer.Protocol.Server.ILanguageServer>(() => server));
                services.AddSingleton <ProjectSnapshotChangeTrigger>(generatedDocumentPublisher);
                services.AddSingleton <GeneratedDocumentPublisher>(generatedDocumentPublisher);

                var documentVersionCache = new DefaultDocumentVersionCache(foregroundDispatcher);
                services.AddSingleton <DocumentVersionCache>(documentVersionCache);
                services.AddSingleton <ProjectSnapshotChangeTrigger>(documentVersionCache);
                var containerStore = new DefaultGeneratedDocumentContainerStore(
                    foregroundDispatcher,
                    documentVersionCache,
                    generatedDocumentPublisher);
                services.AddSingleton <GeneratedDocumentContainerStore>(containerStore);
                services.AddSingleton <ProjectSnapshotChangeTrigger>(containerStore);

                services.AddSingleton <RemoteTextLoaderFactory, DefaultRemoteTextLoaderFactory>();
                services.AddSingleton <ProjectResolver, DefaultProjectResolver>();
                services.AddSingleton <DocumentResolver, DefaultDocumentResolver>();
                services.AddSingleton <RazorProjectService, DefaultRazorProjectService>();
                services.AddSingleton <ProjectSnapshotChangeTrigger, BackgroundDocumentGenerator>();
                services.AddSingleton <RazorDocumentMappingService, DefaultRazorDocumentMappingService>();
                services.AddSingleton <RazorFileChangeDetectorManager>();

                services.AddSingleton <ProjectSnapshotChangeTrigger, RazorServerReadyPublisher>();

                services.AddSingleton <ClientNotifierServiceBase, DefaultClientNotifierService>();

                services.AddSingleton <IOnLanguageServerStarted, DefaultClientNotifierService>();

                // Options
                services.AddSingleton <RazorConfigurationService, DefaultRazorConfigurationService>();
                services.AddSingleton <RazorLSPOptionsMonitor>();
                services.AddSingleton <IOptionsMonitor <RazorLSPOptions>, RazorLSPOptionsMonitor>();

                // File change listeners
                services.AddSingleton <IProjectConfigurationFileChangeListener, ProjectConfigurationStateSynchronizer>();
                services.AddSingleton <IProjectFileChangeListener, ProjectFileSynchronizer>();
                services.AddSingleton <IRazorFileChangeListener, RazorFileSynchronizer>();

                // File Change detectors
                services.AddSingleton <IFileChangeDetector, ProjectConfigurationFileChangeDetector>();
                services.AddSingleton <IFileChangeDetector, ProjectFileChangeDetector>();
                services.AddSingleton <IFileChangeDetector, RazorFileChangeDetector>();

                // Document processed listeners
                services.AddSingleton <DocumentProcessedListener, RazorDiagnosticsPublisher>();
                services.AddSingleton <DocumentProcessedListener, UnsynchronizableContentDocumentProcessedListener>();

                services.AddSingleton <HostDocumentFactory, DefaultHostDocumentFactory>();
                services.AddSingleton <ProjectSnapshotManagerAccessor, DefaultProjectSnapshotManagerAccessor>();
                services.AddSingleton <TagHelperFactsService, DefaultTagHelperFactsService>();
                services.AddSingleton <TagHelperTooltipFactory, DefaultTagHelperTooltipFactory>();

                // Completion
                services.AddSingleton <TagHelperCompletionService, DefaultTagHelperCompletionService>();
                services.AddSingleton <RazorCompletionFactsService, DefaultRazorCompletionFactsService>();
                services.AddSingleton <RazorCompletionItemProvider, DirectiveCompletionItemProvider>();
                services.AddSingleton <RazorCompletionItemProvider, DirectiveAttributeCompletionItemProvider>();
                services.AddSingleton <RazorCompletionItemProvider, DirectiveAttributeParameterCompletionItemProvider>();
                services.AddSingleton <RazorCompletionItemProvider, DirectiveAttributeTransitionCompletionItemProvider>();
                services.AddSingleton <RazorCompletionItemProvider, MarkupTransitionCompletionItemProvider>();
                services.AddSingleton <RazorCompletionItemProvider, TagHelperCompletionProvider>();

                // Auto insert
                services.AddSingleton <RazorOnAutoInsertProvider, HtmlSmartIndentOnAutoInsertProvider>();
                services.AddSingleton <RazorOnAutoInsertProvider, CloseRazorCommentOnAutoInsertProvider>();
                services.AddSingleton <RazorOnAutoInsertProvider, CloseTextTagOnAutoInsertProvider>();
                services.AddSingleton <RazorOnAutoInsertProvider, AttributeSnippetOnAutoInsertProvider>();

                // Formatting
                services.AddSingleton <RazorFormattingService, DefaultRazorFormattingService>();

                // Formatting Passes
                services.AddSingleton <IFormattingPass, HtmlFormattingPass>();
                services.AddSingleton <IFormattingPass, CSharpFormattingPass>();
                services.AddSingleton <IFormattingPass, CSharpOnTypeFormattingPass>();
                services.AddSingleton <IFormattingPass, FormattingDiagnosticValidationPass>();
                services.AddSingleton <IFormattingPass, FormattingContentValidationPass>();

                // Razor Code actions
                services.AddSingleton <RazorCodeActionProvider, ExtractToCodeBehindCodeActionProvider>();
                services.AddSingleton <RazorCodeActionResolver, ExtractToCodeBehindCodeActionResolver>();
                services.AddSingleton <RazorCodeActionProvider, ComponentAccessibilityCodeActionProvider>();
                services.AddSingleton <RazorCodeActionResolver, CreateComponentCodeActionResolver>();
                services.AddSingleton <RazorCodeActionResolver, AddUsingsCodeActionResolver>();

                // CSharp Code actions
                services.AddSingleton <CSharpCodeActionProvider, TypeAccessibilityCodeActionProvider>();
                services.AddSingleton <CSharpCodeActionProvider, ImplementInterfaceAbstractClassCodeActionProvider>();
                services.AddSingleton <CSharpCodeActionProvider, DefaultCSharpCodeActionProvider>();
                services.AddSingleton <CSharpCodeActionResolver, DefaultCSharpCodeActionResolver>();
                services.AddSingleton <CSharpCodeActionResolver, AddUsingsCSharpCodeActionResolver>();

                // Other
                services.AddSingleton <RazorSemanticTokensInfoService, DefaultRazorSemanticTokensInfoService>();
                services.AddSingleton <RazorHoverInfoService, DefaultRazorHoverInfoService>();
                services.AddSingleton <HtmlFactsService, DefaultHtmlFactsService>();
                services.AddSingleton <WorkspaceDirectoryPathResolver, DefaultWorkspaceDirectoryPathResolver>();
                services.AddSingleton <RazorComponentSearchEngine, DefaultRazorComponentSearchEngine>();

                if (configure != null)
                {
                    var builder = new RazorLanguageServerBuilder(services);
                    configure(builder);
                }

                // Defaults: For when the caller hasn't provided them through the `configure` action.
                services.TryAddSingleton <LanguageServerFeatureOptions, DefaultLanguageServerFeatureOptions>();
            }));

            try
            {
                var factory = new LoggerFactory();
                var logger  = factory.CreateLogger <RazorLanguageServer>();
                var assemblyInformationAttribute = typeof(RazorLanguageServer).Assembly.GetCustomAttribute <AssemblyInformationalVersionAttribute>();
                logger.LogInformation("Razor Language Server version " + assemblyInformationAttribute.InformationalVersion);
                factory.Dispose();
            }
            catch
            {
                // Swallow exceptions from determining assembly information.
            }

            var razorLanguageServer = new RazorLanguageServer(server);

            IDisposable exitSubscription = null;

            exitSubscription = server.Exit.Subscribe((_) =>
            {
                exitSubscription.Dispose();
                razorLanguageServer.Dispose();
            });

            return(Task.FromResult(razorLanguageServer));
        }
Пример #40
0
        public async Task EnvironmentVariableForLauncherArgsIsPreferred(HostingModel hostingModel)
        {
            var deploymentParameters = Fixture.GetBaseDeploymentParameters(hostingModel);

            using var publishedApp = await deploymentParameters.ApplicationPublisher.Publish(deploymentParameters, LoggerFactory.CreateLogger("test"));

            deploymentParameters.EnvironmentVariables["ANCM_LAUNCHER_ARGS"] = Path.ChangeExtension(Path.Combine(publishedApp.Path, deploymentParameters.ApplicationPublisher.ApplicationPath), ".dll");
            deploymentParameters.WebConfigActionList.Add(WebConfigHelpers.AddOrModifyAspNetCoreSection("arguments", "nope"));

            await StartAsync(deploymentParameters);
        }
Пример #41
0
        public override async Task Run()
        {
            var reportGenerationTime = DateTime.UtcNow;
            var destinationContainer = _cloudStorageAccount.CreateCloudBlobClient().GetContainerReference(_statisticsContainerName);

            Logger.LogDebug("Generating reports from {DataSource}/{InitialCatalog} and saving to {AccountName}/{Container}", _statisticsDatabase.DataSource, _statisticsDatabase.InitialCatalog, _cloudStorageAccount.Credentials.AccountName, destinationContainer.Name);

            var reportBuilderLogger   = LoggerFactory.CreateLogger <ReportBuilder>();
            var reportCollectorLogger = LoggerFactory.CreateLogger <ReportDataCollector>();

            if (string.IsNullOrEmpty(_reportName))
            {
                // generate all reports
                var reportGenerators = new Dictionary <ReportBuilder, ReportDataCollector>
                {
                    { new ReportBuilder(reportBuilderLogger, ReportNames.NuGetClientVersion), new ReportDataCollector(reportCollectorLogger, _storedProcedures[ReportNames.NuGetClientVersion], _statisticsDatabase) },
                    { new ReportBuilder(reportBuilderLogger, ReportNames.Last6Weeks), new ReportDataCollector(reportCollectorLogger, _storedProcedures[ReportNames.Last6Weeks], _statisticsDatabase) },
                    { new ReportBuilder(reportBuilderLogger, ReportNames.RecentCommunityPopularity), new ReportDataCollector(reportCollectorLogger, _storedProcedures[ReportNames.RecentCommunityPopularity], _statisticsDatabase) },
                    { new ReportBuilder(reportBuilderLogger, ReportNames.RecentCommunityPopularityDetail), new ReportDataCollector(reportCollectorLogger, _storedProcedures[ReportNames.RecentCommunityPopularityDetail], _statisticsDatabase) },
                    { new ReportBuilder(reportBuilderLogger, ReportNames.RecentPopularity), new ReportDataCollector(reportCollectorLogger, _storedProcedures[ReportNames.RecentPopularity], _statisticsDatabase) },
                    { new ReportBuilder(reportBuilderLogger, ReportNames.RecentPopularityDetail), new ReportDataCollector(reportCollectorLogger, _storedProcedures[ReportNames.RecentPopularityDetail], _statisticsDatabase) }
                };

                foreach (var reportGenerator in reportGenerators)
                {
                    await ProcessReport(LoggerFactory, destinationContainer, reportGenerator.Key, reportGenerator.Value, reportGenerationTime);

                    ApplicationInsightsHelper.TrackReportProcessed(reportGenerator.Key.ReportName + " report");
                }

                await RebuildPackageReports(destinationContainer, reportGenerationTime);
                await CleanInactiveRecentPopularityDetailByPackageReports(destinationContainer, reportGenerationTime);
            }
            else
            {
                // generate only the specific report
                var reportBuilder       = new ReportBuilder(reportBuilderLogger, _reportName);
                var reportDataCollector = new ReportDataCollector(reportCollectorLogger, _storedProcedures[_reportName], _statisticsDatabase);

                await ProcessReport(LoggerFactory, destinationContainer, reportBuilder, reportDataCollector, reportGenerationTime);
            }

            Logger.LogInformation("Generated reports from {DataSource}/{InitialCatalog} and saving to {AccountName}/{Container}", _statisticsDatabase.DataSource, _statisticsDatabase.InitialCatalog, _cloudStorageAccount.Credentials.AccountName, destinationContainer.Name);

            // totals reports
            var stopwatch = Stopwatch.StartNew();

            // build downloads.v1.json
            var targets = new List <StorageContainerTarget>();

            targets.Add(new StorageContainerTarget(_cloudStorageAccount, _statisticsContainerName));
            foreach (var dataContainerName in _dataContainerNames)
            {
                targets.Add(new StorageContainerTarget(_dataStorageAccount, dataContainerName));
            }
            var downloadCountReport = new DownloadCountReport(LoggerFactory.CreateLogger <DownloadCountReport>(), targets, _statisticsDatabase, _galleryDatabase);
            await downloadCountReport.Run();

            stopwatch.Stop();
            ApplicationInsightsHelper.TrackMetric(DownloadCountReport.ReportName + " Generation Time (ms)", stopwatch.ElapsedMilliseconds);
            ApplicationInsightsHelper.TrackReportProcessed(DownloadCountReport.ReportName);
            stopwatch.Restart();

            // build stats-totals.json
            var galleryTotalsReport = new GalleryTotalsReport(LoggerFactory.CreateLogger <GalleryTotalsReport>(), _cloudStorageAccount, _statisticsContainerName, _statisticsDatabase, _galleryDatabase);
            await galleryTotalsReport.Run();

            stopwatch.Stop();
            ApplicationInsightsHelper.TrackMetric(GalleryTotalsReport.ReportName + " Generation Time (ms)", stopwatch.ElapsedMilliseconds);
            ApplicationInsightsHelper.TrackReportProcessed(GalleryTotalsReport.ReportName);


            // build tools.v1.json
            var toolsReport = new DownloadsPerToolVersionReport(LoggerFactory.CreateLogger <DownloadsPerToolVersionReport>(), _cloudStorageAccount, _statisticsContainerName, _statisticsDatabase, _galleryDatabase);
            await toolsReport.Run();

            stopwatch.Stop();
            ApplicationInsightsHelper.TrackMetric(DownloadsPerToolVersionReport.ReportName + " Generation Time (ms)", stopwatch.ElapsedMilliseconds);
            ApplicationInsightsHelper.TrackReportProcessed(DownloadsPerToolVersionReport.ReportName);
            stopwatch.Restart();
        }
		public static void Configure(IConfiguration configuration)
		{
			LoggerProvider = new DynamicLoggerProvider(new ConsoleLoggerSettings().FromConfiguration(configuration));
			LoggerFactory = new LoggerFactory();
			LoggerFactory.AddProvider(LoggerProvider);
		}