public SlotHttpClientWrapper(IJwtTokenGenerator tokenGenerator, IDateTimeGenerator dateTimeGenerator)
 {
     _tokenGenerator    = tokenGenerator;
     _dateTimeGenerator = dateTimeGenerator;
     FlurlHttp.ConfigureClient(_uri, cli =>
                               cli.Settings.HttpClientFactory = new UntrustedCertClientFactory());
 }
Exemplo n.º 2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers()
            .AddNewtonsoftJson(WebAppDefaults.SetMvcNewtonsoftJsonOptions)
            .AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining <Startup>());

            services.AddAutoMapper(typeof(Startup));

            services.AddHttpClient();
            FlurlHttp.ConfigureClient(GetFakeNamesQueryHandler.FakeNameUrl, cli =>
                                      cli.Settings.HttpClientFactory = new UntrustedCertClientFactory());

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "My API", Version = "v1"
                });
                c.OperationFilter <CancellationTokenOperationFilter>();
            });

            services.AddDbContext <ContactDbContext>(options =>
                                                     options.UseSqlServer(Configuration.GetConnectionString("ContactContext")));
            services.AddScoped <IContactsDbContext, ContactDbContext>();

            services.AddMediatR(Assembly.GetExecutingAssembly());

            services.AddOData();
            services.AddODataSupportedMediaTypes();
        }
Exemplo n.º 3
0
        public BgmApi(IBgmCache bgmCache, IBgmOAuth bgmOAuth)
        {
            _bgmCache = bgmCache ?? throw new ArgumentNullException(nameof(bgmCache));
            _bgmOAuth = bgmOAuth ?? throw new ArgumentNullException(nameof(bgmOAuth));

            FlurlHttp.ConfigureClient(HOST, client =>
            {
                client.Settings.BeforeCall = call =>
                {
                    if (_bgmOAuth.IsLogin)
                    {
                        call.Request.Headers.Add("Authorization", $"Bearer {_bgmOAuth.MyToken.Token}");
                    }
                    call.Request.Headers.Add("Cookie", $"chii_searchDateLine={DateTime.Now.ToString()}");
                };
                client.Settings.OnErrorAsync = async call =>
                {
                    // 若请求为未认证则检查Token
                    if (call.HttpResponseMessage?.StatusCode == HttpStatusCode.Unauthorized)
                    {
                        await _bgmOAuth.CheckToken();
                        throw new BgmTokenRefreshedException("Token refreshed.");
                    }
                };
            });
        }
Exemplo n.º 4
0
        protected override Task OnInitializeAsync(IActivatedEventArgs args)
        {
            // Callback clients
            Container.RegisterType <ILobbyClient, LobbyClient>(new ContainerControlledLifetimeManager());
            Container.RegisterType <IGameClient, GameClient>(new ContainerControlledLifetimeManager());
            Container.RegisterType <IFriendClient, FriendClient>(new ContainerControlledLifetimeManager());

            // Services
            Container.RegisterType <IDialogService, DialogService>(new ContainerControlledLifetimeManager());
            Container.RegisterType <IUserManagerService, UserManagerService>(new ContainerControlledLifetimeManager());
            Container.RegisterType <IHubService, HubService>(new ContainerControlledLifetimeManager());
            Container.RegisterType <ILobbyService, LobbyService>(new ContainerControlledLifetimeManager());
            Container.RegisterType <IMatchService, MatchService>(new ContainerControlledLifetimeManager());
            Container.RegisterType <IMessageService, MessageService>(new ContainerControlledLifetimeManager());
            Container.RegisterType <IFriendService, FriendService>(new ContainerControlledLifetimeManager());


            // Caches
            Container.RegisterType <ILobbyStore, LobbyStore>(new ContainerControlledLifetimeManager());
            Container.RegisterType <IMatchStore, MatchStore>(new ContainerControlledLifetimeManager());
            Container.RegisterType <IMessageStore, MessageStore>(new ContainerControlledLifetimeManager());
            Container.RegisterType <IFriendStore, FriendStore>(new ContainerControlledLifetimeManager());

            Container.RegisterType <ILoggerFacade, NLogAdapter>(new ContainerControlledLifetimeManager());

            // Configure Flurl to ignore untrusted certificates
            var baseUrl = Current.Resources["BaseUrl"].ToString();

            FlurlHttp.ConfigureClient(baseUrl.AppendPathSegment("api"), cli => cli.Settings.HttpClientFactory = new UntrustedCertClientFactory());

            return(Task.FromResult <object>(null));
        }
Exemplo n.º 5
0
        public override void Configure(IFunctionsHostBuilder builder)
        {
            var configurationBuilder = new ConfigurationBuilder();
            var config = configurationBuilder
                         .AddEnvironmentVariables()
                         .Build();

            var baseUrl          = config["BaseUrl"];
            var connectionString = config["ConnectionString"];

            _ = builder.Services.Configure <SqlServerConfig>(options =>
                                                             options.ConnectionString = connectionString);
            _ = builder.Services.Configure <MazeApiConfig>(options =>
                                                           options.BaseUrl = baseUrl);

            _ = builder.Services.AddSingleton(config);

            _ = builder.Services.AddDbContext <TVMazeContext>(options =>
                                                              options.UseSqlServer(connectionString));

            FlurlHttp.ConfigureClient(baseUrl, cli => cli.Settings.HttpClientFactory = new TVMazeHttpClientFactory());

            _ = builder.Services.AddScoped <ITVMazeApiHttpClient, TVMazeApiHttpClient>();
            _ = builder.Services.AddScoped <IScrapeService, ScrapeService>();
            _ = builder.Services.AddScoped <IShowService, ShowService>();

            _ = builder.Services.AddTransient <IShowRepository, ShowRepository>();
            _ = builder.Services.AddTransient <ICastMemberRepository, CastMemberRepository>();
        }
Exemplo n.º 6
0
        [Test, NonParallelizable]         // #239
        public void request_default_settings_change_when_client_changes()
        {
            FlurlHttp.ConfigureClient("http://test.com", cli => cli.Settings.CookiesEnabled = true);
            var req  = new FlurlRequest("http://test.com");
            var cli1 = req.Client;

            Assert.IsTrue(req.Settings.CookiesEnabled, "pre-configured client should provide defaults to new request");

            req.Url = "http://test.com/foo";
            Assert.AreSame(cli1, req.Client, "new URL with same host should hold onto same client");
            Assert.IsTrue(req.Settings.CookiesEnabled);

            req.Url = "http://test2.com";
            Assert.AreNotSame(cli1, req.Client, "new host should trigger new client");
            Assert.IsFalse(req.Settings.CookiesEnabled);

            FlurlHttp.ConfigureClient("http://test2.com", cli => cli.Settings.CookiesEnabled = true);
            Assert.IsTrue(req.Settings.CookiesEnabled, "changing client settings should be reflected in request");

            req.Settings = new FlurlHttpSettings();
            Assert.IsTrue(req.Settings.CookiesEnabled, "entirely new settings object should still inherit current client settings");

            req.Client = new FlurlClient();
            Assert.IsFalse(req.Settings.CookiesEnabled, "entirely new client should provide new defaults");

            req.Url = "http://test.com";
            Assert.AreNotSame(cli1, req.Client, "client was explicitly set on request, so it shouldn't change even if the URL changes");
            Assert.IsFalse(req.Settings.CookiesEnabled);
        }
Exemplo n.º 7
0
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;

            //Development HTTPS Client Certs
            FlurlHttp.ConfigureClient("https://localhost:5003", cli =>
                                      cli.Settings.HttpClientFactory = new UntrustedCertClientFactory());
        }
Exemplo n.º 8
0
        private KeycloakClient(string url)
        {
            _url = url;

            this._clientFactory = new ConfigurableHttpClientFactory();
            FlurlHttp.ConfigureClient(this._url,
                                      cli => cli.Settings.HttpClientFactory = this._clientFactory);
        }
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            FlurlHttp.ConfigureClient(_options.DataExportUrl, cli =>
                                      cli.Settings.HttpClientFactory = new UntrustedCertClientFactory());
            while (!stoppingToken.IsCancellationRequested)
            {
                _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
                #region Stage TLHOW Pull
                TLHOWData tlhowData = null;
                while (tlhowData == null)
                {
                    try
                    {
                        tlhowData = await _options.DataExportUrl.GetJsonAsync <TLHOWData>();
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError("Error pulling data from TLHOW {error}", ex);
                        await Task.Delay(retryStageInterval, stoppingToken);
                    }
                }
                #endregion Stage TLHOW Pull

                #region Stage Find Hospital service
                string hospitalServiceHost = string.Empty;
                while (hospitalServiceHost == string.Empty)
                {
                    try
                    {
                        hospitalServiceHost = await GetServiceHostAsync(_options.HospitalServiceName);
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError("Error in finding hospital service {error}", ex);
                        await Task.Delay(retryStageInterval, stoppingToken);
                    }
                }
                #endregion Stage Find Hospital service

                foreach (var record in tlhowData.ClinicGroup)
                {
                    #region Stage push to Hospital service
                    try
                    {
                        var internalHospitalData = _mapper.Map <Contracts.V2.Company>(record.Value);
                        await $"http://{hospitalServiceHost}/api/v2/hospital/update-company"
                        .PostJsonAsync(internalHospitalData, stoppingToken);
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError("Error pushing data to hospital-service {error}", ex);
                    }
                    #endregion Stage push to Hospital service
                }

                await Task.Delay(loadInterval, stoppingToken);
            }
        }
Exemplo n.º 10
0
 private void InitHttpClient()
 {
     FlurlHttp.ConfigureClient(IoC.Get <IConfigurationService>().BaseServiceUrl, cli => cli
                               .Configure(settings =>
     {
         settings.BeforeCall = call => _logger.Info($"Calling {call.Request.RequestUri}");
         settings.OnError    = call => _logger.Error(call.Exception);
     }));
 }
Exemplo n.º 11
0
        /// <summary>
        /// Enable HTTP debugging via Fiddler. Ensure Tools > Fiddler Options... > Connections is enabled and has a port configured.
        /// Then, call this method with the following URL format: http://localhost.:PORT where PORT is the port number Fiddler proxy
        /// is listening on. (Be sure to include the period after the localhost).
        /// </summary>
        /// <param name="proxyUrl">The full proxy URL Fiddler proxy is listening on. IE: http://localhost.:8888 - The period after localhost is important to include.</param>
        public void EnableFiddlerDebugProxy(string proxyUrl)
        {
            var webProxy = new WebProxy(proxyUrl, BypassOnLocal: false);

            FlurlHttp.ConfigureClient(Endpoint, settings =>
            {
                settings.Settings.HttpClientFactory = new DebugProxyFactory(webProxy);
            });
        }
Exemplo n.º 12
0
        public void ConfigureServices(IServiceCollection services)
        {
            var connectionString = _configuration.GetConnectionString("DefaultConnection");

            services.AddDbContext <AppDbContext>(config => // Aguega una BD
            {
                //config.UseSqlServer(connectionString);
                config.UseInMemoryDatabase("Memory"); // Agrega la BD a memoria
            });

            services.AddIdentity <IdentityUser, IdentityRole>(config => { // Registra los servicios o infraestructura
                config.Password.RequiredLength         = 4;
                config.Password.RequireDigit           = false;
                config.Password.RequireNonAlphanumeric = false;
                config.Password.RequireUppercase       = false;
            })
            .AddEntityFrameworkStores <AppDbContext>()
            .AddDefaultTokenProviders();     // Provee un token por default

            services.ConfigureApplicationCookie(config =>
            {
                config.Cookie.Name = "UCAB.Cookie";  // Nombre de la Cookie
                config.LoginPath   = "/Auth/Login";  // Ruta de autenticación
                config.LogoutPath  = "/Auth/Logout"; // Ruta de cierre de sesión
            });

            var migrationAssembly = typeof(Startup).Assembly.GetName().Name;

            services.AddIdentityServer()
            .AddAspNetIdentity <IdentityUser>()
            //.AddConfigurationStore(options =>
            //{
            //    options.ConfigureDbContext = b => b.UseSqlServer(connectionString, sql => sql.MigrationsAssembly(migrationAssembly));
            //})
            //.AddOperationalStore(options =>
            //{
            //    options.ConfigureDbContext = b => b.UseSqlServer(connectionString, sql => sql.MigrationsAssembly(migrationAssembly));
            //})
            .AddInMemoryApiResources(Configuration.GetApis())
            .AddInMemoryClients(Configuration.GetClients())
            .AddInMemoryApiScopes(Configuration.GetScopes())
            .AddInMemoryIdentityResources(Configuration.GetIdentityResources())
            .AddDeveloperSigningCredential();     // Para crear una firma para el token

            FlurlHttp.ConfigureClient(_configuration["appSettings:URLBANNERRESTAPI"], cli => cli
                                      .WithHeaders(new
            {
                Accept = "application/json"
            })
                                      .WithBasicAuth(_configuration["appSettings:USERBANNERSERVICE"], _configuration["appSettings:PASSWORDBANNERSERVICE"])
                                      .Settings.HttpClientFactory = new UntrustedCertClientFactory()
                                      );


            services.AddControllersWithViews();
        }
Exemplo n.º 13
0
 public static void ConfigureClient(IConfiguration configuration)
 {
     FlurlHttp.ConfigureClient(configuration[ConfigurationSettingName], (client) =>
     {
         client.WithHeaders(new
         {
             Accept = "application/json",
         });
     });
 }
 public DeserializationTests()
 {
     // Do this in Startup. All calls to SimpleCast will use the same HttpClient instance.
     FlurlHttp.ConfigureClient(_baseUri, cli => cli
                               .WithHeaders(new
     {
         Accept     = "application/json",
         User_Agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36"     // Flurl will convert that underscore to a hyphen
     }));
 }
Exemplo n.º 15
0
 protected internal void ConfigureClient()
 {
     FlurlHttp.ConfigureClient(Endpoint, client =>
     {
         client
         .WithHeader(HeaderNames.ApiKey, this.apiKey)
         .WithHeader(HeaderNames.Version, ApiVersionDate)
         .WithHeader("User-Agent", UserAgent);
     });
 }
Exemplo n.º 16
0
        public static void AddTokenClient(this IServiceCollection services, IReadOnlyCollection <TokenSource> wellKnownTokenSources)
        {
            AddTokenClient(services);

            foreach (var source in wellKnownTokenSources)
            {
                FlurlHttp.ConfigureClient(source.BaseUri.ToString(), settings =>
                {
                    settings.Settings.HttpClientFactory = new BypassCertificateValidation(source.Thumbprint);
                    settings.AllowAnyHttpStatus();
                });
            }
        }
Exemplo n.º 17
0
        /// <summary>
        /// Configures the application services that require configuration.
        /// </summary>
        /// <param name="jenkinsSettings">The settings required to configure Jenkins requests.</param>
        private static void ConfigureAppServices(JenkinsSettings jenkinsSettings)
        {
            var jsonSettings = new JsonSerializerSettings {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };

            FlurlHttp.Configure(s => s.JsonSerializer = new NewtonsoftJsonSerializer(jsonSettings));

            if (!string.IsNullOrWhiteSpace(jenkinsSettings.User) || !string.IsNullOrWhiteSpace(jenkinsSettings.Password))
            {
                FlurlHttp.ConfigureClient(jenkinsSettings.BaseEndpoint, cl =>
                                          cl.WithBasicAuth(jenkinsSettings.User, jenkinsSettings.Password)
                                          );
            }
            jenkinsSettings.Password = null;
        }
Exemplo n.º 18
0
        Action <dynamic> _responseCallback; // Used to notify of multi-response calls

        public ApiHelper(string account, string token, string endpointUri = "https://localhost:30063/api/1.1", Dictionary <string, string> accountProps = null, Action <dynamic> responseCallback = null)
        {
            _responseCallback = responseCallback;
            if (string.IsNullOrEmpty(token))
            {
                throw (new ArgumentNullException(nameof(token)));
            }
            this._token = token;
            if (string.IsNullOrEmpty(account))
            {
                throw (new ArgumentNullException(nameof(account)));
            }
            this._account = account;
            if (string.IsNullOrEmpty(endpointUri))
            {
                Console.WriteLine($"No api endpoint uri passed using {_endpointUri}");
            }
            else if (IsValidUri(endpointUri))
            {
                _endpointUri = endpointUri;
            }
            else
            {
                throw (new ArgumentException($"Uri {endpointUri} is not valid"));
            }
            var idx = endpointUri.IndexOf("/api/");

            if (idx < 0)
            {
                throw (new ArgumentException($"Uri {endpointUri} is not valid"));
            }
            _baseUri = _endpointUri.Substring(0, idx);

            // TODO: remove this later
            // Configure to ignore bad certificates for this endpoint
            FlurlHttp.ConfigureClient(_endpointUri, cli =>
            {
                cli.Settings.HttpClientFactory = new UntrustedCertClientFactory();
                cli.Settings.Timeout           = new TimeSpan(0, 30, 0); // 30 minutes timeout
            });

            // Configure account properties if any
            if (accountProps != null && accountProps.Count > 0)
            {
                var response = SetAccountProps(account, accountProps);
            }
        }
Exemplo n.º 19
0
 public Proxy()
 {
     PropertyChanged += (s, e) => e.Case <object>(a =>
     {
         try
         {
             FlurlHttp.ConfigureClient(BaseUrl, cli =>
             {
                 cli.Settings.Timeout = TimeSpan.FromMinutes(30);
                 if (cli.HttpMessageHandler is HttpClientHandler hch)
                 {
                     hch.ServerCertificateCustomValidationCallback += (_, __, ___, ____) => true;
                 }
             });
         }
         catch (Exception ex) { }
     }, nameof(Host), nameof(Port), nameof(UseHttps));
 }
Exemplo n.º 20
0
 public void can_configure_client_from_FlurlHttp_object()
 {
     FlurlHttp.ConfigureClient("http://host1.com/foo", cli => cli.Settings.CookiesEnabled = true);
     Assert.IsTrue(new FlurlRequest("https://host1.com/bar").Client.Settings.CookiesEnabled);             // different URL but same host, so should use same client
     Assert.IsFalse(new FlurlRequest("http://host2.com").Client.Settings.CookiesEnabled);
 }
Exemplo n.º 21
0
        public static async Task Main(string[] args)
        {
            FlurlHttp.ConfigureClient(Config.ElasticSearchAddress, cli =>
                                      cli.Settings.HttpClientFactory = new UntrustedCertClientFactory());

            #region Get input

            string indexName;
            int    usersToCreate;
            int    usersIdOffset;
            int    usersBatchSize;
            int    documentsToCreate;
            int    documentsIdOffset;
            int    documentsBatchSize;

            Console.Write("Use default values? [y/...]: ");
            if (Console.ReadLine() != "y")
            {
                Console.Write("Index name: ");
                indexName          = Console.ReadLine();
                usersToCreate      = ConsoleUtils.PromptValue("Users to create: ");
                usersIdOffset      = ConsoleUtils.PromptValue("Users' id offset(from which id to start - inclusive): ");
                usersBatchSize     = ConsoleUtils.PromptValue("Create users by batch size: ");
                documentsToCreate  = ConsoleUtils.PromptValue("Documents to create: ");
                documentsIdOffset  = ConsoleUtils.PromptValue("Documents' id offset(from which id to start - inclusive): ");
                documentsBatchSize = ConsoleUtils.PromptValue("Create documents by batch size: ");
            }
            else
            {
                indexName          = "cz_demo_index";
                usersToCreate      = 20;
                usersIdOffset      = 0;
                usersBatchSize     = 20;
                documentsToCreate  = 1500;
                documentsIdOffset  = 0;
                documentsBatchSize = 50;
            }

            #endregion

            Console.WriteLine("All needed variables gathered. Proceeding to creating data");

            Stopwatch watches = new Stopwatch();

            Tuple <List <DummyUser>, long> createUsersTuple = await dummyUtils.CreateUsers(
                usersToCreate,
                usersIdOffset,
                usersBatchSize,
                false,
                watches
                );

            Console.WriteLine($"Creating {usersToCreate} users took: {createUsersTuple.Item2}ms");

            await CreateIndex(indexName, watches);

            await CreateDocuments(
                documentsToCreate,
                documentsIdOffset,
                documentsBatchSize,
                indexName,
                createUsersTuple.Item1,
                watches);
        }
Exemplo n.º 22
0
 public static void ConfigureDomainWithWindowsAuthentication(string url)
 {
     FlurlHttp.ConfigureClient(url, cli =>
                               cli.Settings.HttpClientFactory = new UseDefaultCredentialsClientFactory());
 }
Exemplo n.º 23
0
        public RestService(string endpointUrl)
        {
            EndpointUrl = endpointUrl;

            FlurlHttp.ConfigureClient(EndpointUrl, cli => cli.Settings.HttpClientFactory = new UntrustedCertClientFactory());
        }
Exemplo n.º 24
0
 public static void ConfigureDomainForDefaultCredentials(string url)
 {
     FlurlHttp.ConfigureClient(url, cli =>
                               cli.Settings.HttpClientFactory = new UseDefaultCredentialsClientFactory());
 }
Exemplo n.º 25
0
 public static void Configure()
 {
     FlurlHttp.ConfigureClient("https://icpcarchive.ecs.baylor.edu/uhunt", cli =>
                               cli.Settings.HttpClientFactory = new UntrustedCertClientFactory());
 }
        public static async Task Main(string[] args)
        {
            FlurlHttp.ConfigureClient(Config.ElasticSearchAddress, cli =>
                                      cli.Settings.HttpClientFactory = new UntrustedCertClientFactory());

            FlurlHttp.GlobalSettings.BeforeCall = call =>
            {
                Console.WriteLine($"Before: {call.Request.RequestUri}");
            };

            FlurlHttp.GlobalSettings.BeforeCall = call =>
            {
                Console.WriteLine($"After: {call.Request.RequestUri}");
            };

            #region Get input

            string indexName;
            int    usersToCreate;

            Console.Write("Use default values? [y/...]: ");
            if (Console.ReadLine() != "y")
            {
                Console.Write("Index name: ");
                indexName     = Console.ReadLine();
                usersToCreate = ConsoleUtils.PromptValue("Users to create: ");
            }
            else
            {
                indexName     = "cz_index";
                usersToCreate = 1500;
            }

            #endregion

            Tuple <List <DummyUser>, long> users = await dummyUtils.CreateUsers(
                usersToCreate, 0, short.MaxValue, false, Stopwatch.StartNew());

            Console.WriteLine("Getting all documents");
            HttpResponseMessage documentsResponse = await $"{Config.ElasticSearchAddress}/{indexName}/_search"
                                                    .PostJsonAsync(
                new
            {
                _source = new dynamic[0],
                size    = 10000
            });

            Console.WriteLine($"Parsing all documents");
            JObject parsedDocs = JObject.Parse(await documentsResponse.Content.ReadAsStringAsync());
            Console.WriteLine($"{parsedDocs["hits"]["total"]["value"].Value<int>()} documents parsed");
            List <Task> requests = new List <Task>(
                parsedDocs["hits"]["total"]["value"].Value <int>()
                );
            Console.WriteLine("Sending update requests");
            foreach (JToken document in parsedDocs["hits"]["hits"].AsJEnumerable())
            {
                requests.Add($"{Config.ElasticSearchAddress}/{indexName}/_update/{document["_id"]}"
                             .PostJsonAsync(new
                {
                    doc = new
                    {
                        mainarea  = coverageUtils.GetRandom(CoverageConfig.MainAreaCoverage),
                        subarea   = coverageUtils.GetRandom(CoverageConfig.SubAreaCoverage),
                        product   = coverageUtils.GetRandom(CoverageConfig.ProductsCoverage),
                        placement = coverageUtils.GetRandom(CoverageConfig.PlacementCoverage),
                        users     = new[]
                        {
                            coverageUtils.GetOne(users.Item1),
                            coverageUtils.GetOne(users.Item1),
                            coverageUtils.GetOne(users.Item1)
                        }
                    }
                }));
            }

            Console.WriteLine("Waiting for unfinished requests");
            Task.WaitAll(requests.ToArray());

            Console.WriteLine("Done!");
        }
Exemplo n.º 27
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <ApplicationSettings>(Configuration.GetSection(ApplicationSettings.SectionKey));
            services.AddSingleton(s => s.GetRequiredService <IOptions <ApplicationSettings> >().Value);
            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;
            });

            // Note: The default connection string assumes that you have 'LocalDb' installed on your machine (either through SQL Server or Visual Studio installer)
            // If you followed the instructions in 'README.MD' and installed SQL Express then change the 'DefaultConnection' value in 'appSettings.json' with
            // "Server=localhost\\SQLEXPRESS;Database=aspnet-smartadmin;Trusted_Connection=True;MultipleActiveResultSets=true"
            services.AddDbContext <ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddDefaultIdentity <IdentityUser>().AddEntityFrameworkStores <ApplicationDbContext>().AddDefaultTokenProviders();

            services.AddRouting(options =>
            {
                options.LowercaseUrls         = true;
                options.LowercaseQueryStrings = true;
            })
            .AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
            .AddRazorPagesOptions(options =>
            {
                options.AllowAreas = true;
                options.Conventions.AuthorizeAreaFolder("Identity", "/Account/Manage");
                options.Conventions.AuthorizeAreaPage("Identity", "/Account/Logout");
            });

            services.ConfigureApplicationCookie(options =>
            {
                options.LoginPath        = "/Identity/Account/Login";
                options.LogoutPath       = "/Identity/Account/Logout";
                options.AccessDeniedPath = "/Identity/Account/AccessDenied";
            });

            // Do this in Startup. All calls to SimpleCast will use the same HttpClient instance.
            FlurlHttp.ConfigureClient(Configuration["API_url"], cli => cli
                                      .Configure(settings =>
            {
                // keeps logging & error handling out of SimpleCastClient
                settings.BeforeCall = call => logger.LogWarning($"Calling {call.Request.RequestUri}");
                settings.OnError    = call => logger.LogError($"Call to SimpleCast failed: {call.Exception}");
            })
                                      // adds default headers to send with every call
                                      .WithHeaders(new
            {
                Accept     = "application/json",
                User_Agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36"     // Flurl will convert that underscore to a hyphen
            }));

            // Set API url
            Action <ConfigOptions> configOptions = (options =>
            {
                options.base_api_url = Configuration.GetSection("API_url").Value; //Configuration["API_url"];
            });

            services.Configure(configOptions);
            services.AddSingleton(resolver => resolver.GetRequiredService <IOptions <ConfigOptions> >().Value);


            services.AddResponseCaching();
        }
Exemplo n.º 28
0
 public AddAppointmentHttpClientWrapper(IJwtTokenGenerator tokenGenerator)
 {
     _tokenGenerator = tokenGenerator;
     FlurlHttp.ConfigureClient(_uri, cli =>
                               cli.Settings.HttpClientFactory = new UntrustedCertClientFactory());
 }
Exemplo n.º 29
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // AutoMapper
            services.AddAutoMapper(typeof(AutoMapperProfile).GetTypeInfo().Assembly);

            // MediatR
            services.AddMediatR(typeof(GetClientDetailQuery).GetTypeInfo().Assembly);

            // Flurl
            var jsonSettings = new JsonSerializerSettings();

            jsonSettings.Converters.Add(new FlattenNestedJSONConverter <HLClientResult>());

            FlurlHttp.ConfigureClient(Configuration["HiddenLeversServiceUri"], cli => cli
                                      .Configure(settings =>
            {
                settings.JsonSerializer = new Flurl.Http.Configuration.NewtonsoftJsonSerializer(jsonSettings);
            })
                                      .WithHeaders(new
            {
                Content_Type = "application/json"
            }));

            services.AddSingleton <IVivaldiHiddenLeversClient, HiddenLeversApiClient>();

            // DBContext
            string connection = Configuration.GetConnectionString("LocalConnection");

            services.AddDbContext <IVivaldiHiddenLeversDbContext, VivaldiHiddenLeversDbContext>
                (options => options.UseSqlServer(connection));

            // CORS
            services.AddCors();

            // WebAPI
            services.AddMvc(options => options.Filters.Add(typeof(CustomExceptionFilterAttribute)))
            .AddJsonOptions(options => {
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            // Swagger
            services.AddSwaggerDocument(config =>
            {
                config.DocumentName = "VivaldiHiddenLevers v1";
                config.PostProcess  = document =>
                {
                    document.Info.Version     = "v1";
                    document.Info.Title       = "Vivaldi - HiddenLevers API";
                    document.Info.Description = "Display Vivaldi clients with extra info powered by HiddenLevers.";
                    document.Info.Contact     = new NSwag.OpenApiContact
                    {
                        Name  = "François Blondel",
                        Email = "*****@*****.**",
                    };
                };
            });

            // In production, the Angular files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });
        }