public static void AddAppServices(this IServiceCollection services, IWebHostEnvironment env, IConfiguration config)
        {
            var mailOptions    = new MailingOptions();
            var twilioOptions  = new TwilioOptions();
            var loggingOptions = new LoggingOptions();

            config.GetSection(MailingOptions.SectionName).Bind(mailOptions);
            config.GetSection(TwilioOptions.SectionName).Bind(twilioOptions);
            config.GetSection(LoggingOptions.SectionName).Bind(loggingOptions);

            services.AddScoped <IDataManager, DataManager>();
            services.AddScoped <IEmailService>(x => new EmailService(
                                                   mailOptions.Sender, mailOptions.SmtpServer, mailOptions.SmtpPort, mailOptions.Username, mailOptions.Password
                                                   ));
            services.AddScoped <IImageService, ImageService>();
            services.AddScoped <ISmsService>(x => new SmsService(
                                                 twilioOptions.Sender, twilioOptions.AccountSid, twilioOptions.AuthToken
                                                 ));
            services.AddLogging(opt =>
            {
                opt.AddConsole();
                opt.AddFile(Path.Combine(env.WebRootPath, loggingOptions.CommonLogFilePath));
                opt.AddFile(Path.Combine(env.WebRootPath, loggingOptions.ErrorLogFilePath), LogLevel.Error);
            });
            services.AddSingleton <IUserConnectionManager, UserConnectionManager>();
        }
        private static void AddAuthentication(IServiceCollection services, IConfiguration configuration)
        {
            var authOptionsSection    = configuration.GetSection("WebApp:Authentication:AzureAd");
            var b2cAuthOptionsSection = configuration.GetSection("WebApp:Authentication:AzureAd:B2C");
            var b2cPoliciesSection    = configuration.GetSection("WebApp:Authentication:AzureAd:B2C:Policies");

            services.Configure <AuthenticationOptions>(authOptionsSection);
            services.Configure <B2CAuthenticationOptions>(b2cAuthOptionsSection);
            services.Configure <B2CPolicies>(b2cPoliciesSection);

            var authOptions    = authOptionsSection.Get <AuthenticationOptions>();
            var b2cAuthOptions = b2cAuthOptionsSection.Get <B2CAuthenticationOptions>();
            var b2cPolicies    = b2cPoliciesSection.Get <B2CPolicies>();

            var serviceProvider  = services.BuildServiceProvider();
            var distributedCache = serviceProvider.GetService <IDistributedCache>();

            services.AddSingleton(distributedCache);

            services.AddAuthentication(options =>
            {
                options.DefaultScheme          = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = B2CAuthConstants.OpenIdConnectB2CAuthenticationScheme;
            })
            .AddCookie()
            .AddOpenIdConnectB2CAuthentication(b2cAuthOptions, b2cPolicies, distributedCache)
            .AddOpenIdConnectOrganizationalAuthentication(authOptions, distributedCache);
        }
Пример #3
0
 public JwtHandler(Microsoft.Extensions.Configuration.IConfiguration configuration, UserManager <User> userManager)
 {
     _userManager    = userManager;
     _configuration  = configuration;
     _jwtSettings    = _configuration.GetSection("JwtSettings");
     _goolgeSettings = _configuration.GetSection("GoogleAuthSettings");
 }
Пример #4
0
        public static ConnectionStringSettingsCollection ConnectionStrings(this Microsoft.Extensions.Configuration.IConfiguration configuration, string section = "ConnectionStrings")
        {
            return(ConnectionStringSettingsCollectionCache.GetOrAdd(section, key =>
            {
                var connectionStringCollection = configuration.GetSection(section).Get <ConnectionStringSettingsCollection>();
                if (connectionStringCollection == null || connectionStringCollection.Count == 0 || connectionStringCollection.All(c => c.Name == null))
                {
                    var connectionStrings = configuration.GetSection(section).Get <Dictionary <string, ConnectionStringSettings> >();
                    if (connectionStrings == null || connectionStrings.Count == 0)
                    {
                        var connectionStringMap = configuration.GetSection(section).Get <Dictionary <string, string> >();
                        if (connectionStringMap == null || connectionStringMap.Count == 0)
                        {
                            return new ConnectionStringSettingsCollection();
                        }
                        else
                        {
                            return new ConnectionStringSettingsCollection(connectionStringMap.Select(p => new ConnectionStringSettings {
                                Name = p.Key, ConnectionString = p.Value
                            }));
                        }
                    }
                    else
                    {
                        return new ConnectionStringSettingsCollection(connectionStrings.Do(p => p.Value.Name = p.Key).Select(p => p.Value));
                    }
                }

                return connectionStringCollection;
            }));
        }
        public static void AddAuth(this IServiceCollection services, IConfiguration config)
        {
            var appOptions    = new AppOptions();
            var googleOptions = new GoogleOptions();

            config.GetSection(AppOptions.SectionName).Bind(appOptions);
            config.GetSection(GoogleOptions.SectionName).Bind(googleOptions);

            services.ConfigureApplicationCookie(options =>
            {
                options.Cookie.Name       = appOptions.CompanyEmail + "Auth";
                options.Cookie.HttpOnly   = true;
                options.LoginPath         = "/account/login";
                options.SlidingExpiration = true;
            });

            services.AddAuthentication().AddGoogle(opt =>
            {
                opt.ClientId     = googleOptions.ClientId;
                opt.ClientSecret = googleOptions.ClientSecret;
            });

            services.AddAuthorization(x =>
            {
                x.AddPolicy("AdminArea", policy => { policy.RequireRole("admin"); });
            });
        }
Пример #6
0
        public async Task <IDocument> LoadHtml(string requestUri, Site site, CancellationToken token)
        {
            requestUri.StringNullOrEmptyValidate(nameof(requestUri));
            site.NullValidate(nameof(site));

            IWebDriver webDriver = null;

            try
            {
                await semaphoreSlim.WaitAsync(token);

                var parserSettings = _configuration.GetSection(site.Name).Get <ExtractorSettings>();

                webDriver     = webDriverQueue.Dequeue();
                webDriver.Url = requestUri;

                //Чтобы дождаться прогрузки страницы
                _ = webDriver.FindElement(By.ClassName(parserSettings.Name.Trim('.')));

                logger.LogInformation($"Successfully sent request {requestUri}");

                var context = BrowsingContext.New(Configuration.Default);
                return(await context.OpenAsync(req => req.Content(webDriver.PageSource)));
            }
            finally
            {
                webDriver.Url = site.BaseUrl;
                webDriverQueue.Enqueue(webDriver);
                semaphoreSlim.Release();
            }
        }
Пример #7
0
        /// <summary>
        /// Bootstraps selenium with options defined in source projects appsettings.json.
        /// </summary>
        /// <param name="services">The services.</param>
        /// <param name="config">The configuration.</param>
        private static void BootstrapSelenium(this IServiceCollection services, DiConfig.IConfiguration config)
        {
            var driverConfig = config.GetSection(nameof(DriverManagerOptions));

            services.Configure <DriverManagerOptions>(driverConfig);

            if (driverConfig.Get <DriverManagerOptions>().ShouldBuildProxiedDrivers)
            {
                services.AddTransient <IProxyProvider, ProxyService>();
                services.AddTransient <IDriverFactory, ProxiedChromeDriverFactory>();
            }
            else
            {
                services.AddTransient <IDriverFactory, ChromeDriverFactory>();
            }

            services.Configure <ChromeDriverFactoryOptions>(
                config.GetSection(nameof(ChromeDriverFactoryOptions)));

            services.AddTransient <IConfigureOptions <DriverManagerOptions>, ConfigureDriverManagerOptions>();

            services.AddValidatorsFromAssembly(typeof(DependencyInjection).Assembly);

            services.AddTransient <IDriverManager, DriverManager>();
            services.AddTransient <DriverExecutionRequestHandler>();
            services.AddTransient <IDriverValidator, DriverValidator>();
        }
Пример #8
0
        public static IServiceCollection AddMongoDB(this IServiceCollection services, Microsoft.Extensions.Configuration.IConfiguration Configuration)
        {
            services.Configure <MongoDbSettings>(options =>
            {
                options.ConnectionString = Configuration.GetSection("MongoConnection:ConnectionString").Value;
                options.Database         = Configuration.GetSection("MongoConnection:Database").Value;
            });

            services.AddTransient(typeof(IMongoRepository), typeof(MongoRepository));

            return(services);
        }
Пример #9
0
        protected IStringLocalizer CreateLocalizer(string baseName, string assembly, IStringLocalizerFactory factory)
        {
            IStringLocalizer realLocalizer = factory.Create(baseName, assembly);

            if (!(Environment.GetEnvironmentVariable("ResourcesDebug")?.Equals("ResourcesDebug") ?? false))
            {
                return(realLocalizer);
            }
            AutocompleteResourceConfiguration configuration = _Configuration.GetSection(nameof(AutocompleteResourceConfiguration)).Get <AutocompleteResourceConfiguration>();
            IStringLocalizer debugLocalizer = new AutoCompleterStringLocalizer(realLocalizer, CultureInfo.CurrentCulture,
                                                                               baseName, configuration, _Logger);

            return(debugLocalizer);
        }
Пример #10
0
        /// <summary>
        /// Adds service capable of returning recipe data from EatThisMuch.com.
        /// </summary>
        /// <param name="services">The services</param>
        /// <param name="config">App config object.</param>
        public static void AddEatThisMuchRecipeProvider(this IServiceCollection services, DiConfig.IConfiguration config)
        {
            services.AddTransient <RecipePage>();
            services.AddTransient <CategoryPage>();
            services.AddTransient <SiteMapPage>();

            services.Configure <RecipePageOptions>(config.GetSection(nameof(RecipePageOptions)));
            services.Configure <CategoryPageOptions>(config.GetSection(nameof(CategoryPageOptions)));
            services.Configure <SiteMapPageOptions>(config.GetSection(nameof(SiteMapPageOptions)));

            services.AddEatThisMuchCategoryProvider(config);
            services.AddRecipeRepository();

            services.AddTransient <IRecipeProvider, EatThisMuchRecipeProvider>();
        }
Пример #11
0
        private string CreateTokens(User user)
        {
            List <Claim> claims = new List <Claim>
            {
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                new Claim(ClaimTypes.Name, user.Username)
            };

            SymmetricSecurityKey key = new SymmetricSecurityKey(
                Encoding.UTF8.GetBytes(_configuration.GetSection("AppSettings:Token").Value));

            SigningCredentials creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);

            SecurityTokenDescriptor tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.Now.AddDays(1),
                SigningCredentials = creds
            };

            JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
            SecurityToken           token        = tokenHandler.CreateToken(tokenDescriptor);


            return(tokenHandler.WriteToken(token));
        }
        public async Task <ActionResult> Login([FromBody] UserForLoginDto userForLoginDto)
        {
            var user = await _authRepository.Login(userForLoginDto.UserName, userForLoginDto.Password);

            if (user == null)
            {
                return(Unauthorized());
            }

            var tokenHandler = new JwtSecurityTokenHandler();
            var key          = Encoding.ASCII.GetBytes(_configuration.GetSection("AppSettings:Token").Value);

            var securityTokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                    new Claim(ClaimTypes.Name, user.UserName)
                }),
                Expires            = DateTime.Now.AddDays(1),
                SigningCredentials =
                    new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha512)
            };
            var token       = tokenHandler.CreateToken(securityTokenDescriptor);
            var tokenString = tokenHandler.WriteToken(token);

            return(Ok(tokenString));
        }
 private static void ConfigureSecurity(IServiceCollection services, IConfiguration configuration)
 {
     services.AddTransient <IPasswordHasher, PasswordHasher>();
     services.Configure <JWTSettings>(configuration.GetSection("JWTSettings"));
     services.AddTransient <JWTTokenProvider>();
     services.TryAddSingleton <WebSession>();
 }
        public static void ConfigureHangfireContext(this IServiceCollection services,
                                                    Microsoft.Extensions.Configuration.IConfiguration config)
        {
            var connections = config.GetSection("ConnectionStrings").Get <ConnectionStringsDto>();

            services.AddHangfire(c => c.UseSqlServerStorage(connections.DefaultConnection));
        }
Пример #15
0
 public static IServiceCollection UseMetrics(
     this IServiceCollection services,
     Microsoft.Extensions.Configuration.IConfiguration configuration,
     IHostingEnvironment env)
 {
     _metricsSettings = new MetricsSettings();
     configuration.GetSection("MetricsSettings").Bind(_metricsSettings);
     if (_metricsSettings.UseMetrics)
     {
         services.AddMetrics(options =>
         {
             options.WithGlobalTags((globalTags, info) =>
             {
                 globalTags.Add("app", info.EntryAssemblyName);
                 globalTags.Add("env", env.EnvironmentName);
             });
         })
         .AddHealthChecks()
         .AddReporting(
             factory =>
         {
             factory.AddInfluxDb(
                 new InfluxDBReporterSettings
             {
                 InfluxDbSettings = new InfluxDBSettings(_metricsSettings.InfluxDatabase, new Uri(_metricsSettings.InfluxServer)),
                 ReportInterval   = TimeSpan.FromSeconds(5)
             });
         })
         .AddMetricsMiddleware(options => options.IgnoredHttpStatusCodes = new[] { 404 });
     }
     return(services);
 }
Пример #16
0
        protected string CreateJWT(User user)
        {
            var secretKey = configuration.GetSection("AppSettings:Key").Value;
            var key       = new SymmetricSecurityKey(Encoding.UTF8
                                                     .GetBytes(secretKey));

            var claims = new Claim[]
            {
                new Claim(ClaimTypes.Name, user.UserName),
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                new Claim(ClaimTypes.Name, user.Firstname != null? user.Firstname : ""),
                new Claim(ClaimTypes.Name, user.Lastname != null? user.Lastname : ""),
                new Claim(ClaimTypes.Anonymous, user.IsActive.ToString())
            };

            var signingCredentials = new SigningCredentials(
                key, SecurityAlgorithms.HmacSha256Signature);

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.UtcNow.AddDays(10),
                SigningCredentials = signingCredentials
            };

            var tokenHandler = new JwtSecurityTokenHandler();
            var token        = tokenHandler.CreateToken(tokenDescriptor);

            return(tokenHandler.WriteToken(token));
        }
Пример #17
0
        public ActionResult <string> Get(int userid)
        {
            if (AuthenticateUser() == false)
            {
                return(Unauthorized());
            }



            string conStr = configuration.GetSection("Data").GetSection("ConntectionString").Value;

            RTS.JobStation.Controller.Inlinenotification InlineNotification = new RTS.JobStation.Controller.Inlinenotification();


            DataSet ds = new DataSet("InlineNotifications");

            MySql.Data.MySqlClient.MySqlConnection  con = RTS.JobStation.DatabaseCommands.OpenConnection();
            MySql.Data.MySqlClient.MySqlTransaction MyTran;
            MyTran = RTS.JobStation.DatabaseCommands.OpenTransaction(ref con);

            ds = InlineNotification.GetInlineNotifications(ref con, ref MyTran, userid);
            ds.Tables[0].TableName = "InlineNotifications";
            ds.Tables.Add(RTS.JobStation.DatabaseCommands.GetNewTokenTable(NewToken));
            // dt = Candidate.GetCandidateList(ref con, ref MyTran,4,1,50).Tables[0];req
            string jsonResult = JsonConvert.SerializeObject(ds);

            RTS.JobStation.DatabaseCommands.CloseTransaction(ref MyTran);
            RTS.JobStation.DatabaseCommands.CloseConnection(ref con);

            return(Ok(jsonResult));
        }
        public static void AddJwt(IServiceCollection services, Microsoft.Extensions.Configuration.IConfiguration configuration)
        {
            var settingsSection = configuration.GetSection("JwtSettings");

            services.Configure <JwtSettings>(settingsSection);

            var appSettings = settingsSection.Get <JwtSettings>();
            var key         = Encoding.ASCII.GetBytes(appSettings.SecretKey);

            services.AddAuthentication(
                auth =>
            {
                auth.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                auth.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(
                bearer =>
            {
                bearer.RequireHttpsMetadata      = false;
                bearer.SaveToken                 = true;
                bearer.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(key),
                    ValidateIssuer           = false,
                    ValidateAudience         = false
                };
            }
                );

            services.AddTransient(map => new JwtToken(appSettings));
        }
        private async Task <string> GenerateJwtToken(User user)
        {
            var claims = new List <Claim>
            {
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                new Claim(ClaimTypes.Name, user.UserName),
            };

            var roles = await _userManager.GetRolesAsync(user);

            foreach (var role in roles)
            {
                claims.Add(new Claim(ClaimTypes.Role, role));
            }

            var tokenSecret = _config.GetSection("AppSettings:Token").Value;

            var key = new SymmetricSecurityKey(Encoding.UTF8
                                               .GetBytes(tokenSecret));

            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.Now.AddDays(1),
                SigningCredentials = creds
            };

            var tokenHandler = new JwtSecurityTokenHandler();

            var token = tokenHandler.CreateToken(tokenDescriptor);

            return(Task.FromResult(tokenHandler.WriteToken(token)).Result);
        }
Пример #20
0
 public PaymentsController(IPaymentService paymentService, ILogger <IPaymentService> logger, Microsoft.Extensions.Configuration.IConfiguration config)
 {
     _logger         = logger;
     _paymentService = paymentService;
     //config webhook
     _whSecret = config.GetSection("StripeSettings:WhSecret").Value;
 }
Пример #21
0
        public static void AddEatThisMuchCategoryRepository(this IServiceCollection services, DiConfig.IConfiguration config)
        {
            services.Configure <EatThisMuchCategoryRepositoryDatabaseSettings>(
                config.GetSection(nameof(EatThisMuchCategoryRepositoryDatabaseSettings)));

            services.AddRecipeRepository();
        }
        public static IServiceCollection AddCustomConfiguration(this IServiceCollection services, IConfiguration configuration)
        {
            services.Configure <FaceApiConfigHelper>(configuration.GetSection("AzureFaceApiConfig"));
            services.AddAutoMapper();

            return(services);
        }
Пример #23
0
        public async Task <object> GenerateJwtToken(string email, User user)
        {
            var now    = DateTime.UtcNow;
            var claims = new List <Claim>
            {
                new Claim(JwtRegisteredClaimNames.Sub, email),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(ClaimTypes.Role, user.Role)
            };

            var jwtOptions = new JwtOptions();

            _configuration.GetSection("jwt").Bind(jwtOptions);

            var key         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtOptions.SecretKey));
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var expires     = now.AddMinutes(_jwtOptions.ExpiryMinutes);

            var token = new JwtSecurityToken(
                issuer: _jwtOptions.Issuer,
                claims: claims,
                notBefore: now,
                expires: expires,
                signingCredentials: credentials
                );

            await Task.CompletedTask;

            return(new JwtSecurityTokenHandler().WriteToken(token));
        }
Пример #24
0
        public void RegisterServices(IServiceCollection services)
        {
            services.Configure <JwtTokenModel>(options => _config.GetSection("TokenManagement").Bind(options));

            services.AddTransient <GenericServiceBase <Rabbit, RabbitDto, RabbitListModelFilter>, RabbitsService>();
            services.AddTransient <IAuthService, TokenAuthenticationService>();
        }
        public static IServiceCollection ConfigureMongoDb(this IServiceCollection services,
                                                          IConfiguration configuration)
        {
            var mongoConfigurations =
                configuration.GetSection(MongoDbConfiguration.SectionName).Get <MongoDbConfiguration>();

            BsonSerializer.RegisterSerializer(new GuidSerializer(BsonType.String));

            BsonClassMap.RegisterClassMap <Customer>();
            BsonClassMap.RegisterClassMap <Preference>();
            BsonClassMap.RegisterClassMap <PromoCode>();

            services
            .AddSingleton <IMongoClient>(_ =>
                                         new MongoClient(configuration.GetConnectionString("MongoDb")))
            .AddSingleton(serviceProvider =>
                          serviceProvider.GetRequiredService <IMongoClient>()
                          .GetDatabase(mongoConfigurations.DatabaseName))
            .AddSingleton(serviceProvider =>
                          serviceProvider.GetRequiredService <IMongoDatabase>()
                          .GetCollection <Customer>(mongoConfigurations.CustomersCollectionName))
            .AddSingleton(serviceProvider =>
                          serviceProvider.GetRequiredService <IMongoDatabase>()
                          .GetCollection <Preference>(mongoConfigurations.PreferencesCollectionName))
            .AddSingleton(serviceProvider =>
                          serviceProvider.GetRequiredService <IMongoDatabase>()
                          .GetCollection <PromoCode>(mongoConfigurations.PromoCodesCollectionName))
            .AddScoped(serviceProvider =>
                       serviceProvider.GetRequiredService <IMongoClient>()
                       .StartSession());

            return(services);
        }
Пример #26
0
        public static void AddAuth(this IServiceCollection services, IConfiguration config)
        {
            var googleConfig = new GoogleConfig();

            config.GetSection(GoogleConfig.SectionName).Bind(googleConfig);

            services.AddAuthentication().AddGoogle(options =>
            {
                options.ClientId     = googleConfig.ClientId;
                options.ClientSecret = googleConfig.ClientSecret;
            });


            services.ConfigureApplicationCookie(options =>
            {
                options.LoginPath = "/account/login";
            });

            services.AddAuthorization(x =>
            {
                x.AddPolicy("AdminArea", policy => { policy.RequireRole("admin"); });
            });

            services.AddControllersWithViews(options =>
            {
                options.Conventions.Add(new AdminAreaAuth("Admin", "AdminArea"));
            })
            .AddSessionStateTempDataProvider();
        }
Пример #27
0
        public SelenuimLoader(Microsoft.Extensions.Configuration.IConfiguration configuration, ILogger <SelenuimLoader> logger)
        {
            this.logger         = logger;
            this._configuration = configuration;

            var loadTimeoutSeconds = configuration.GetSection("SeleniumLoadTimoutSeconds").Get <int>();

            if (loadTimeoutSeconds == 0)
            {
                loadTimeoutSeconds = 30;
                logger.LogInformation($"Section SeleniumLoadTimoutSeconds not found, set default value {loadTimeoutSeconds}");
            }

            var webDriverCounts = configuration.GetSection("SeleniumWebDriverCounts").Get <int>();

            if (webDriverCounts == 0)
            {
                webDriverCounts = Environment.ProcessorCount;
                logger.LogInformation($"Section SeleniumWebDriverCounts not foundа, set value equal to the counts of logical cores={webDriverCounts}");
            }

            semaphoreSlim = new SemaphoreSlim(webDriverCounts, webDriverCounts);

            webDriverQueue = new Queue <IWebDriver>();
            for (int i = 0; i < webDriverCounts; i++)
            {
                ChromeOptions chromeOptions = new ChromeOptions();
                //chromeOptions.AddArguments(new List<string>() {
                //    "--silent-launch",
                //    "--no-startup-window",
                //    "no-sandbox",
                //    "headless"
                //    "disable-gpu"
                //});
                //chromeOptions.AddArgument(@"user-data-dir=C:\Users\foton\AppData\Local\Temp\scoped_dir22284_1666492972");

                //var chromeDriverService = ChromeDriverService.CreateDefaultService();
                //chromeDriverService.HideCommandPromptWindow = true;
                var chromeDriver = new ChromeDriver(chromeOptions);
                chromeDriver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(loadTimeoutSeconds);
                webDriverQueue.Enqueue(chromeDriver);

                logger.LogInformation($"Create {nameof(ChromeDriver)}");
            }

            logger.LogInformation($"Created {webDriverCounts} instanse of {nameof(ChromeDriver)}");
        }
Пример #28
0
        public Dictionary <string, string> GetAllIconMarkerUrl()
        {
            var start = WebUrlService.GetSiteRootAddress().EnsureEndsWith('/') + "assets/img/icons/";

            var xx = Configuration.GetSection("IconConfig").GetChildren().Select(item => new KeyValuePair <string, string>(item.Key, start + item.Value)).ToDictionary(x => x.Key, x => x.Value);

            return(xx);
        }
Пример #29
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public IConfigurationSection GetSection(string key)
        {
            var node = Node.GetSection(key);

            return(node == null
                                ? null
                                : new CoreConfigurationSection(node));
        }
Пример #30
0
        public ElasticSearchManager(Microsoft.Extensions.Configuration.IConfiguration configuration)
        {
            Configuration = configuration;
            var settings = configuration.GetSection("ElasticSearchCong").Get <ElasticSearchCong>();
            Uri uri      = new Uri(settings.ConnectionString);

            connectionSettings = new ConnectionSettings(uri);
        }