Beispiel #1
0
        static async Task Main(string[] args)
        {
            Console.WriteLine("Starting...");

            var services = new ServiceCollection();

            services.AddLogging(LoggingBuilder =>
            {
                LoggingBuilder.AddConsole();
            });
            services.AddEventBus(CONNECTION_STRING, TOPIC_NAME, SUBSCRIPTION_NAME);

            services.AddTransient <ItemCreatedEventHandler>();
            services.AddTransient <ItemDeletedEventHandler>();

            var serviceProvider = services.BuildServiceProvider();
            var eventBus        = serviceProvider.GetRequiredService <IEventBus>();

            eventBus.Subscribe <ItemCreatedEvent, ItemCreatedEventHandler>();
            eventBus.Subscribe <ItemDeletedEvent, ItemDeletedEventHandler>();

            var id = Guid.NewGuid().ToString();

            await eventBus.PublishAsync(new ItemCreatedEvent(id));

            await eventBus.PublishAsync(new ItemDeletedEvent(id));

            Console.ReadKey();
        }
Beispiel #2
0
        public TestFunctionHost(string scriptPath, string logPath,
                                Action <IWebJobsBuilder> configureJobHost = null,
                                Action <IConfigurationBuilder> configureAppConfiguration = null,
                                Action <IServiceCollection> configureServices            = null)
        {
            _appRoot = scriptPath;

            _hostOptions = new ScriptApplicationHostOptions
            {
                IsSelfHost     = true,
                ScriptPath     = _appRoot,
                LogPath        = logPath,
                SecretsPath    = Environment.CurrentDirectory, // not used
                HasParentScope = true
            };

            var optionsMonitor = TestHelpers.CreateOptionsMonitor(_hostOptions);
            var builder        = new WebHostBuilder()
                                 .ConfigureLogging(b =>
            {
                b.AddProvider(_loggerProvider);
            })
                                 .ConfigureServices(services =>
            {
                services.Replace(new ServiceDescriptor(typeof(ISecretManagerProvider), new TestSecretManagerProvider(new TestSecretManager())));
                services.Replace(ServiceDescriptor.Singleton <IServiceProviderFactory <IServiceCollection> >(new WebHostServiceProviderFactory()));
                services.Replace(new ServiceDescriptor(typeof(IOptions <ScriptApplicationHostOptions>), new OptionsWrapper <ScriptApplicationHostOptions>(_hostOptions)));
                services.Replace(new ServiceDescriptor(typeof(IOptionsMonitor <ScriptApplicationHostOptions>), optionsMonitor));

                services.AddSingleton <IConfigureBuilder <IConfigurationBuilder> >(_ => new DelegatedConfigureBuilder <IConfigurationBuilder>(c =>
                {
                    c.AddTestSettings();
                    configureAppConfiguration?.Invoke(c);
                }));

                configureServices?.Invoke(services);
            })
                                 .AddScriptHostBuilder(webJobsBuilder =>
            {
                var loggingBuilder = new LoggingBuilder(webJobsBuilder.Services);
                loggingBuilder.AddProvider(_loggerProvider);
                loggingBuilder.AddFilter <TestLoggerProvider>(_ => true);

                webJobsBuilder.AddAzureStorage();

                configureJobHost?.Invoke(webJobsBuilder);
            })
                                 .UseStartup <Startup>();

            _testServer = new TestServer(builder);

            HttpClient             = new HttpClient(new UpdateContentLengthHandler(_testServer.CreateHandler()));
            HttpClient.BaseAddress = new Uri("https://localhost/");

            var manager = _testServer.Host.Services.GetService <IScriptHostManager>();

            _hostService = manager as WebJobsScriptHostService;

            StartAsync().GetAwaiter().GetResult();
        }
Beispiel #3
0
    /// <summary>
    /// Creates an instance of <see cref="WebAssemblyHostBuilder"/> with the minimal configuration.
    /// </summary>
    internal WebAssemblyHostBuilder(IJSUnmarshalledRuntime jsRuntime, JsonSerializerOptions jsonOptions)
    {
        // Private right now because we don't have much reason to expose it. This can be exposed
        // in the future if we want to give people a choice between CreateDefault and something
        // less opinionated.
        _jsonOptions   = jsonOptions;
        Configuration  = new WebAssemblyHostConfiguration();
        RootComponents = new RootComponentMappingCollection();
        Services       = new ServiceCollection();
        Logging        = new LoggingBuilder(Services);

        // Retrieve required attributes from JSRuntimeInvoker
        InitializeNavigationManager(jsRuntime);
        InitializeRegisteredRootComponents(jsRuntime);
        InitializePersistedState(jsRuntime);
        InitializeDefaultServices();

        var hostEnvironment = InitializeEnvironment(jsRuntime);

        HostEnvironment = hostEnvironment;

        _createServiceProvider = () =>
        {
            return(Services.BuildServiceProvider(validateScopes: WebAssemblyHostEnvironmentExtensions.IsDevelopment(hostEnvironment)));
        };
    }
Beispiel #4
0
        static void Main(string[] args)
        {
            var sw = Stopwatch.StartNew();

            var loggingBuilder = new LoggingBuilder();

            loggingBuilder.AppContext.Add("Host", Environment.MachineName);
            loggingBuilder.LogProviders.Add(new ConsoleLogProvider {
                ShouldLogContext = true
            });

            var logger = loggingBuilder.BuildLogger();

            logger.LoggerContext.Add("Operation", "Sample");

            logger.Event("SampleStarted");

            logger.Trace("Sample message 1", TraceSeverity.Verbose);
            logger.Trace("Sample message 2", TraceSeverity.Warning);
            logger.Trace("Sample message 3", TraceSeverity.Error);

            sw.Stop();
            logger.Metric("AppDuration", sw.ElapsedMilliseconds);

            logger.Flush();
        }
Beispiel #5
0
 public static IHostBuilder CreateHostBuilder(string[] args) =>
 Host.CreateDefaultBuilder(args).ConfigureLogging(LoggingBuilder => {
     object p = LoggingBuilder.AddLog4Net();
 })
 .ConfigureWebHostDefaults(webBuilder =>
 {
     webBuilder.UseStartup <Startup>();
 });
Beispiel #6
0
 public Init(IServiceCollection services)
 {
     services.AddLogging(LoggingBuilder =>
     {
         LoggingBuilder.AddNLog("nlog.config");
     });
     services.AddScoped <AppFunctionUi>();
 }
Beispiel #7
0
 public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
 WebHost.CreateDefaultBuilder(args)
 .ConfigureLogging((context, LoggingBuilder) =>
 {
     LoggingBuilder.AddFilter("System", LogLevel.Warning);     // 忽略系统的其他日志
     LoggingBuilder.AddFilter("Microsoft", LogLevel.Warning);
     LoggingBuilder.AddLog4Net();
 })
 .UseStartup <Startup>();
 public void OneTimeSetUp() {
     var builder = new LoggingBuilder();
     var loggerFactory = builder.BuildLoggerFactory();
     loggerFactory.UseAsHibernateLoggerFactory();
     var config = new Configuration();
     ConfigNHibernate(config);
     sessionFactory = config.BuildSessionFactory();
     cfg = config;
 }
Beispiel #9
0
 public AppHostBuilder(IDictionary <object, object> properties = null)
 {
     services             = new ServiceCollection();
     configurationBuilder = new ConfigurationBuilder();
     loggingBuilder       = new LoggingBuilder(services);
     Properties           = properties == null
         ? new Dictionary <object, object>()
         : new Dictionary <object, object>(properties);
     context = new HostBuilderContext(Properties);
 }
Beispiel #10
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();

            //add contexts
            services.AddScoped <IAccountContext, SQLAccountContext>();
            services.AddScoped <IPostContext, SQLPostContext>();
            services.AddScoped <IForumContext, SQLForumContext>();
            services.AddScoped <IMessageContext, SQLMessageContext>();
            services.AddScoped <IReplyContext, SQLReplyContext>();
            services.AddScoped <IPostUpdateContext, SQLPostContext>();

            //add containers
            services.AddScoped <AccountContainer>();
            services.AddScoped <PostContainer>();
            services.AddScoped <MessageContainer>();
            services.AddScoped <ForumContainer>();
            services.AddScoped <ReplyContainer>();

            services.AddHttpContextAccessor();
            services.AddSession();
            services.AddLogging(LoggingBuilder =>
            {
                LoggingBuilder.AddFile("app.log", append: true);
            });

            //identity
            services.Configure <IdentityOptions>(options =>
            {
                // Password settings.
                options.Password.RequireDigit           = true;
                options.Password.RequireLowercase       = true;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = true;
                options.Password.RequiredLength         = 6;
                options.Password.RequiredUniqueChars    = 1;

                // User settings.
                options.User.AllowedUserNameCharacters =
                    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
                options.User.RequireUniqueEmail = false;
            });

            services.ConfigureApplicationCookie(options =>
            {
                // Cookie settings
                options.Cookie.HttpOnly = true;
                options.ExpireTimeSpan  = TimeSpan.FromMinutes(5);

                options.LoginPath         = "/Identity/Account/Login";
                options.AccessDeniedPath  = "/Identity/Account/AccessDenied";
                options.SlidingExpiration = true;
            });
        }
 public static IHostBuilder CreateHostBuilder(string[] args) =>
 Host.CreateDefaultBuilder(args)
 .UseServiceProviderFactory(new AutofacServiceProviderFactory())
 .ConfigureWebHostDefaults(webBuilder =>
 {
     webBuilder.UseStartup <Startup>();
 }).ConfigureLogging((context, LoggingBuilder) =>          //ILogger
 {
     LoggingBuilder.AddFilter("System", LogLevel.Warning); // 忽略系统的其他日志
     LoggingBuilder.AddFilter("Microsoft", LogLevel.Warning);
 }).UseLog4Net();
Beispiel #12
0
        public void OneTimeSetUp()
        {
            var builder       = new LoggingBuilder();
            var loggerFactory = builder.BuildLoggerFactory();

            loggerFactory.UseAsHibernateLoggerFactory();
            cfg = ConfigNHibernate();
            cfg.AddIdentityMappings();
            AddAttributesMapping(cfg);
            sessionFactory = cfg.BuildSessionFactory();
        }
Beispiel #13
0
        public WebApplicationHostBuilder(IHostBuilder hostBuilder)
        {
            _hostBuilder = hostBuilder;

            Services = new ServiceCollection();

            // HACK: MVC and Identity do this horrible thing to get the hosting environment as an instance
            // from the service collection before it is built. That needs to be fixed...
            Environment = new WebHostEnvironment();
            Services.AddSingleton(Environment);

            // REVIEW: Since the configuration base is tied to the content root, it needs to be specified as part of
            // builder creation. It's not changing in the current design.
            Configuration = new ConfigurationBuilder().SetBasePath(Environment.ContentRootPath);
            Logging       = new LoggingBuilder(Services);
        }
Beispiel #14
0
        public UserStoreTest()
        {
            var builder       = new LoggingBuilder();
            var loggerFactory = builder.BuildLoggerFactory();

            loggerFactory.UseAsHibernateLoggerFactory();
            var cfg = ConfigNHibernate();

            cfg.AddIdentityMappings();
            AddXmlMapping(cfg);
            var sessionFactory = cfg.BuildSessionFactory();

            store = new UserStore <NHIdentityUser, NHIdentityRole>(
                sessionFactory.OpenSession(),
                new IdentityErrorDescriber()
                );
        }
Beispiel #15
0
        public UserStoreTest()
        {
            var builder       = new LoggingBuilder();
            var loggerFactory = builder.BuildLoggerFactory();

            loggerFactory.UseAsHibernateLoggerFactory();
            var cfg  = new Configuration();
            var file = Path.Combine(
                AppDomain.CurrentDomain.BaseDirectory,
                "hibernate.config"
                );

            cfg.Configure(file);
            cfg.AddIdentityMappingsForPostgres();
            var sessionFactory = cfg.BuildSessionFactory();

            store = new UserStore <NHIdentityUser, NHIdentityRole>(sessionFactory.OpenSession());
        }
        private static IServiceProvider GetServiceProvider(Action <IServiceCollection> configureServices)
        {
            IServiceProvider services = null;
            var serviceBuilder        = new ServiceCollection();

            serviceBuilder.AddLogging();
            var loggingBuilder = new LoggingBuilder(serviceBuilder);

            ConfigureLogging(loggingBuilder);

            if (configureServices != null)
            {
                configureServices(serviceBuilder);
            }

            services = serviceBuilder.BuildServiceProvider();

            return(services);
        }
        public static LoggingBuilder AddApplicationInsights(this LoggingBuilder builder, IExecutionEnvironment environment, string instrumentationKey)
        {
            var config = TelemetryConfiguration.Active;

            config.TelemetryChannel.DeveloperMode = environment.IsDevelopment();
            config.InstrumentationKey             = instrumentationKey;
            config.DisableTelemetry = string.IsNullOrWhiteSpace(instrumentationKey);

            // Add to NLog
            var aiTarget = new ApplicationInsightsTarget()
            {
                Name = "ApplicationInsights",
                InstrumentationKey = config.InstrumentationKey
            };

            builder.Configuration.AddTarget(aiTarget.Name, aiTarget);
            builder.Configuration.AddRuleForAllLevels(aiTarget);

            return(builder);
        }
        internal WebApplicationBuilder(Assembly callingAssembly, Action <IHostBuilder> configureHost)
        {
            Services = new ServiceCollection();

            // HACK: MVC and Identity do this horrible thing to get the hosting environment as an instance
            // from the service collection before it is built. That needs to be fixed...
            var environment = new WebHostEnvironment(callingAssembly);

            Environment = environment;
            Services.AddSingleton(Environment);

            Configuration = new Configuration();

            // Run this inline to populate the configuration
            configureHost(new ConfigurationHostBuilder(Configuration, Environment));

            Configuration.SetBasePath(environment.ContentRootPath);
            Logging = new LoggingBuilder(Services);
            Server  = _deferredWebHostBuilder = new DeferredWebHostBuilder(Configuration, environment);
            Host    = _deferredHostBuilder = new DeferredHostBuilder(Configuration, configureHost, environment);
        }