Пример #1
0
        private static void ConfigureFlurlHttp()
        {
            var modernHttpClientFactory = new ModernHttpClientFactory
            {
                OnSessionTimeOut     = App.OnSessionTimeout,
                OnAccessTokenRefresh = App.OnAccessTokenRefresh
            };

            FlurlHttp.Configure(c =>
            {
                c.HttpClientFactory = modernHttpClientFactory;
            });
        }
Пример #2
0
        public IntegrationTests()
        {
            Directory.SetCurrentDirectory(Path.GetDirectoryName(typeof(IntegrationTests).Assembly.Location));

            ReadSecrets();

            var webProxy = new WebProxy("http://localhost.:8888", BypassOnLocal: false);

            FlurlHttp.Configure(settings =>
            {
                settings.HttpClientFactory = new ProxyFactory(webProxy);
            });
        }
Пример #3
0
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var call = HttpCall.Get(request);

            var stringContent = request.Content as CapturedStringContent;

            if (stringContent != null)
            {
                call.RequestBody = stringContent.Content;
            }

            await FlurlHttp.RaiseEventAsync(request, FlurlEventType.BeforeCall).ConfigureAwait(false);

            call.StartedUtc = DateTime.UtcNow;

            try {
                call.Response = await base.SendAsync(request, cancellationToken).ConfigureAwait(false);

                call.EndedUtc = DateTime.UtcNow;
            }
            catch (Exception ex) {
                call.Exception = (ex is TaskCanceledException && !cancellationToken.IsCancellationRequested) ?
                                 new FlurlHttpTimeoutException(call, ex) :
                                 new FlurlHttpException(call, ex);
            }

            if (call.Response != null && !call.Succeeded)
            {
                if (call.Response.Content != null)
                {
                    call.ErrorResponseBody = await call.Response.Content.ReadAsStringAsync().ConfigureAwait(false);
                }

                call.Exception = new FlurlHttpException(call, null);
            }

            if (call.Exception != null)
            {
                await FlurlHttp.RaiseEventAsync(request, FlurlEventType.OnError).ConfigureAwait(false);
            }

            await FlurlHttp.RaiseEventAsync(request, FlurlEventType.AfterCall).ConfigureAwait(false);

            if (call.Exception != null && !call.ExceptionHandled)
            {
                throw call.Exception;
            }

            call.Response.RequestMessage = request;
            return(call.Response);
        }
Пример #4
0
        private static void ConfigureFlurl(Action <FlurlHttpConfigurationOptions> configureFlurl = null)
        {
            FlurlHttp.Configure(c =>
            {
                // Apply the application's default settings
                if (configureFlurl != null)
                {
                    configureFlurl(c);
                }

                //
                // Apply our default settings
                //
                if (c.HttpClientFactory is DefaultHttpClientFactory)
                {
                    c.HttpClientFactory = new AuthenticatedHttpClientFactory();
                }

                // Apply our event handling without clobbering any application level handlers
                var applicationBeforeCall = c.BeforeCall;
                c.BeforeCall = call =>
                {
                    SetUserAgentHeader(call);
                    if (applicationBeforeCall != null)
                    {
                        applicationBeforeCall(call);
                    }
                };

                var applicationAfterCall = c.AfterCall;
                c.AfterCall = call =>
                {
                    Tracing.TraceHttpCall(call);
                    if (applicationAfterCall != null)
                    {
                        applicationAfterCall(call);
                    }
                };

                var applicationOnError = c.OnError;
                c.OnError = call =>
                {
                    Tracing.TraceFailedHttpCall(call);
                    if (applicationOnError != null)
                    {
                        applicationOnError(call);
                    }
                };
            });
        }
Пример #5
0
        static void GeneralConfiguration()
        {
            FlurlHttp.Configure(settings => {
                var jsonSettings = new JsonSerializerSettings
                {
                    NullValueHandling      = NullValueHandling.Ignore,
                    ObjectCreationHandling = ObjectCreationHandling.Replace
                };
                settings.JsonSerializer = new NewtonsoftJsonSerializer(jsonSettings);
            });

            Thread.CurrentThread.CurrentCulture   = new System.Globalization.CultureInfo("en-US");
            Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US");
        }
        public async Task SendXmlToModelAsync(HttpMethodTypes methodType)
        {
            FlurlHttp.Configure(c => c.HttpClientFactory = new EchoHttpClientFactory());

            var method = HttpMethodByType[methodType];
            var result = await new Url("https://some.url")
                         .AllowAnyHttpStatus()
                         .SendXmlAsync(method, new TestModel {
                Number = 3, Text = "Test"
            })
                         .ReceiveXml <TestModel>();

            AssertTestModel(result, 3, "Test");
        }
Пример #7
0
 public Form1()
 {
     FlurlHttp.Configure(settings => settings.AllowedHttpStatusRange = "400-404,415,421,423,500,503");
     ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
     ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); };
     ServicePointManager.DefaultConnectionLimit = 5000;
     InitializeComponent();
     InitializeSettings();
     _instance = this;
     if (!Properties.Settings.Default.HideClientToggle)
     {
         DeleteLockFile();
     }
 }
        public async Task SendXmlToXDocumentAsync(HttpMethodTypes methodType)
        {
            FlurlHttp.Configure(c => c.HttpClientFactory = new EchoHttpClientFactory());

            var method = HttpMethodByType[methodType];
            var result = await new Url("https://some.url")
                         .SendXmlAsync(method, new TestModel {
                Number = 3, Text = "Test"
            })
                         .ReceiveXDocument()
                         .ConfigureAwait(false);

            AssertXDocument(result, 3, "Test");
        }
Пример #9
0
        static async Task Main(string[] args)
        {
            var mongoHost     = Environment.GetEnvironmentVariable("MONGO_HOST") ?? "localhost";
            var interfaceHost = Environment.GetEnvironmentVariable("INTERFACE_HOST") ?? "localhost";

            //wait for mongo to be available
            await CheckMongoAvailibility(mongoHost);
            await CheckWebServerAvailibility(interfaceHost);

            FlurlHttp.Configure(settings => {
                var jsonSettings = new JsonSerializerSettings
                {
                    NullValueHandling      = NullValueHandling.Ignore,
                    ObjectCreationHandling = ObjectCreationHandling.Replace
                };
                settings.JsonSerializer = new NewtonsoftJsonSerializer(jsonSettings);
            });

            Thread.CurrentThread.CurrentCulture   = new System.Globalization.CultureInfo("en-US");
            Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US");
            Console.WriteLine("Starting daemon");
            CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
            var cancellationToken = cancellationTokenSource.Token;

            SerialThread serialThread = new SerialThread(mongoHost, interfaceHost);

            serialThread.PlayBeep();

            WebSocketThread  webSocketThread  = new WebSocketThread($"ws://{interfaceHost}:3001", serialThread);
            ProcessingThread processingThread = new ProcessingThread(serialThread, webSocketThread, mongoHost, interfaceHost);

            var serialPort = Environment.GetEnvironmentVariable("SERIAL_PORT");

            if (string.IsNullOrEmpty(serialPort))
            {
                serialThread.SetPortName();
            }
            else
            {
                serialThread.SetPortName(serialPort);
            }

            var webSocketTask  = webSocketThread.Start(cancellationToken);
            var serialTask     = serialThread.Start(cancellationToken);
            var processingTask = processingThread.Start(cancellationToken);

            Task.WaitAll(webSocketTask, serialTask, processingTask);

            Console.WriteLine("Daemon finished");
        }
        public static void AddTokenClient(this IServiceCollection services, IReadOnlyCollection <TokenSource> wellKnownTokenSources)
        {
            services.AddTransient <ITokenClient, TokenClient>();
            services.AddTransient <IAssertionService, AssertionService>();

            foreach (var source in wellKnownTokenSources)
            {
                FlurlHttp.ConfigureClient(source.BaseUri.ToString(), settings =>
                {
                    settings.Settings.HttpClientFactory = new BypassCertificateValidation(source.Thumbprint);
                    settings.AllowAnyHttpStatus();
                });
            }
        }
Пример #11
0
        public static IServiceCollection AddNugetServiceIntegrations(this IServiceCollection services, IConfiguration configuration)
        {
            services.TryAddSingleton <IFlurlClient>((s) => new FlurlClient());

            FlurlHttp.Configure(c =>
            {
                c.Timeout = TimeSpan.FromSeconds(30);
            });

            services.Configure <ConfigurationOptions>(configuration.GetSection(nameof(ConfigurationOptions)).BindWithReload);

            services.AddScoped <INugetService, NugetService>();
            return(services);
        }
Пример #12
0
        internal MtgServiceProvider(
            IHeaderManager headerManager,
            IModelMapper modelMapper,
            IRateLimit rateLimit)
        {
            _headerManager = headerManager;
            _modelMapper   = modelMapper;
            _rateLimit     = rateLimit;
            _apiVersion    = ApiVersion.V1;

            FlurlHttp.Configure(settings =>
            {
                settings.JsonSerializer = new SystemTextJsonSerializer();
            });
        }
Пример #13
0
        static void SendAppLogToServer(AppLog appLog)
        {
            var serverUrl = "http://localhost:9090";

            FlurlHttp.Configure(settings => settings.OnErrorAsync = HandleFlurlErrorAsync);

            var entry = new RawLogData()
            {
                Type = StoredLogType.AppLog, Data = JsonUtils.Serialize(appLog), ReceiveDate = DateTime.UtcNow
            };

            var result = (serverUrl + ControllerConstants.AddAppLogUrl.AddFirstChar('/'))
                         .WithHeader(HeaderContants.AppId, "APPID_1")
                         .PostJsonAsync(entry).Result;
        }
        public VstsRestClient(string organization, string token)
        {
            _organization = organization ?? throw new ArgumentNullException(nameof(organization));
            _token        = token ?? throw new ArgumentNullException(nameof(token));

            FlurlHttp.Configure(settings =>
            {
                var jsonSettings = new JsonSerializerSettings
                {
                    ContractResolver = new CamelCasePropertyNamesContractResolver(),
                    Converters       = { new PolicyConverter() }
                };
                settings.JsonSerializer    = new NewtonsoftJsonSerializer(jsonSettings);
                settings.HttpClientFactory = new HttpClientFactory();
            });
        }
Пример #15
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;
        }
Пример #16
0
        private static void Main()
        {
            Application.SetHighDpiMode(HighDpiMode.SystemAware);
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            var services = new ServiceCollection();

            DependencyInjectionConfig.Register(services);
            // FlurlHttp.Configure(settings => settings.ConnectionLeaseTimeout = TimeSpan.FromMinutes(2));
            FlurlHttp.Configure(settings => settings.HttpClientFactory = new ConnectionLifetimeHttpClientFactory());
            using (var provider = services.BuildServiceProvider())
            {
                var mainForm = provider.GetService <Form1>();
                Application.Run(mainForm);
            }
        }
Пример #17
0
        /// <summary>
        ///     Initializes a new instance of the <see cref="BaseHttp" /> class.
        /// </summary>
        /// <param name="host">The host</param>
        protected BaseHttp(string host)
        {
            Guard.NotNullOrEmpty(host, nameof(host), "Host could not be null or empty");

            BasePath = host;

            FlurlHttp.Configure(settings =>
            {
                var jsonSettings = new JsonSerializerSettings
                {
                    NullValueHandling      = NullValueHandling.Ignore,
                    ObjectCreationHandling = ObjectCreationHandling.Replace
                };
                settings.JsonSerializer = new NewtonsoftJsonSerializer(jsonSettings);
            });
        }
Пример #18
0
 public AssistantClient(IOptions <HomeAssistantOptions> options, ILogger <AssistantClient> logger)
 {
     BaseUrl = (options.Value.Address.StartsWith("http") ? options.Value.Address : $"http://{options.Value.Address}").Trim('"', '\'').AppendPathSegment("api");
     // DefaultRequestHeaders.Accept
     //     .Add(new MediaTypeWithQualityHeaderValue("application/json"));
     FlurlHttp.Configure(settings => {
         var jsonSettings = new JsonSerializerSettings {
             NullValueHandling    = Newtonsoft.Json.NullValueHandling.Ignore,
             Formatting           = Formatting.None,
             StringEscapeHandling = StringEscapeHandling.Default
         };
         settings.JsonSerializer = new NewtonsoftJsonSerializer(jsonSettings);
     });
     _logger = logger;
     _logger.LogInformation($"Initialized AssistantClient for '{BaseUrl}'");
 }
        public async Task SendProtobufAsync_Put_SimpleObject()
        {
            var obj = new SimpleModel
            {
                Age       = 26,
                Id        = Guid.NewGuid(),
                BirthDate = DateTime.Now,
                Name      = "Foo da Silva"
            };

            FlurlHttp.Configure(c => c.HttpClientFactory = new VerifyObjectHttpClientFactory(obj));

            var result = await new Url("https://some.url").SendProtobufAsync(HttpMethod.Put, obj);

            Assert.AreEqual(HttpStatusCode.OK, result.StatusCode);
        }
Пример #20
0
        public void BeforeAllTests()
        {
            if (!Environment.OSVersion.IsAppVeyor() && Process.GetProcessesByName("Fiddler").Any())
            {
                var webProxy = new WebProxy("http://localhost.:8888", BypassOnLocal: false);

                FlurlHttp.Configure(settings =>
                {
                    settings.HttpClientFactory = new ProxyFactory(webProxy);
                });
            }

#if NETFRAMEWORK
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
#endif
        }
Пример #21
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);
            }
        }
Пример #22
0
        public static async Task Main(string[] args)
        {
            var username = args[0];
            var password = args[1];
            var hostname = args[2];

            FlurlHttp.Configure(settings => settings.HttpClientFactory = new HttpClientRedirectFactory());

            using (var client = new FlurlClient($"https://{hostname}/api/v1"))
            {
                var accessToken = (await client.Request("login")
                                   .PostJsonAsync(new { username, password })
                                   .ReceiveJson()).accessToken;

                client.Headers.Add("Authorization", $"Bearer {accessToken}");

                // Let's exercise the API
                var networkDevices = await client.Request("networkDevices").GetJsonAsync();

                Console.WriteLine($"Total number of network devices: {networkDevices.total}");

                // Get objects from the first network device
                var firstNetworkDevice = networkDevices.items[0];
                var objects            = await client.Request($"networkDevices/{firstNetworkDevice.id}/objects").GetJsonAsync();

                Console.Write($"Item Reference of first object on first device: {objects.items[0].itemReference}");


                // Get alarms, but exclude acknowledged and discarded alarms. Also only in the priority
                // range 0-70

                var alarms = await client.Request("alarms")
                             .SetQueryParams(new
                {
                    excludePending      = true,
                    excludeAcknowledged = true,
                    priorityRange       = "0,70"
                })
                             .GetJsonAsync();

                // Do the same thing but manually construct the URL
                alarms = await client.Request("alarms?excludePending=true&excludeAcknowledged=true&priorityRange=0,70")
                         .GetJsonAsync();

                Console.WriteLine(JsonConvert.SerializeObject(alarms.items[0], Formatting.Indented));
            }
        }
Пример #23
0
        protected IntegrationTest()
        {
            DataFixture = new Fixture();
            Server      = new TestServer(new WebHostBuilder().UseStartup <InProcessStartUp>());

            FlurlHttp.Configure(c =>
            {
                c.HttpClientFactory = new HttpClientFactory(Server);
            });

            Client = new FlurlClient(Server.BaseAddress.AbsoluteUri);

            DeserializeWithPrivateSetters = new JsonSerializerSettings
            {
                ContractResolver = new JsonPrivateResolver()
            };
        }
Пример #24
0
        public IntegrationTests()
        {
            Directory.SetCurrentDirectory(Path.GetDirectoryName(typeof(IntegrationTests).Assembly.Location));

            ReadSecrets();

#if NETFRAMEWORK
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
#endif

            var webProxy = new WebProxy("http://localhost.:8888", BypassOnLocal: false);

            FlurlHttp.Configure(settings =>
            {
                settings.HttpClientFactory = new ProxyFactory(webProxy);
            });
        }
Пример #25
0
        public IntegrationTests()
        {
            Directory.SetCurrentDirectory(Path.GetDirectoryName(typeof(IntegrationTests).Assembly.Location));
            var lines  = File.ReadAllLines("../../.secrets.txt");
            var apiKey = lines[0].GetAfter(":");

            webhookSecret = lines[1].GetAfter(":");

            var webProxy = new WebProxy("http://localhost.:8888", BypassOnLocal: false);

            FlurlHttp.Configure(settings =>
            {
                settings.HttpClientFactory = new ProxyFactory(webProxy);
            });

            commerceApi = new CommerceApi(apiKey);
        }
        public static void Configure(Configuration config)
        {
            Func <FlurlCall, Task> beforeCallAsync = (FlurlCall call) =>
            {
                Log.Verbose("HTTP Request: {@HttpMethod} - {@Uri} - {@Headers} - {@Content}", call.HttpRequestMessage.Method, call.HttpRequestMessage.RequestUri, call.HttpRequestMessage.Headers.ToString(), call.HttpRequestMessage.Content);
                return(Task.CompletedTask);
            };

            Func <FlurlCall, Task> afterCallAsync = async(FlurlCall call) =>
            {
                Log.Verbose("HTTP Response: {@HttpStatusCode} - {@HttpMethod} - {@Uri} - {@Headers} - {@Content}", call.HttpResponseMessage?.StatusCode, call.HttpRequestMessage?.Method, call.HttpRequestMessage?.RequestUri, call.HttpResponseMessage.Headers.ToString(), await call.HttpResponseMessage?.Content?.ReadAsStringAsync());

                if (config.Observability.Prometheus.Enabled)
                {
                    HttpRequestHistogram
                    .WithLabels(
                        call.HttpRequestMessage.Method.ToString(),
                        call.HttpRequestMessage.RequestUri.Host,
                        call.HttpRequestMessage.RequestUri.AbsolutePath,
                        call.HttpRequestMessage.RequestUri.Query,
                        ((int)call.HttpResponseMessage.StatusCode).ToString(),
                        call.HttpResponseMessage.ReasonPhrase
                        ).Observe(call.Duration.GetValueOrDefault().TotalSeconds);
                }
            };

            Func <FlurlCall, Task> onErrorAsync = async(FlurlCall call) =>
            {
                var response = string.Empty;
                if (call.HttpResponseMessage is object)
                {
                    response = await call.HttpResponseMessage?.Content?.ReadAsStringAsync();
                }
                Log.Error("Http Call Failed. {@HttpStatusCode} {@Content}", call.HttpResponseMessage?.StatusCode, response);
            };

            FlurlHttp.Configure(settings =>
            {
                settings.Timeout                  = new TimeSpan(0, 0, 10);
                settings.BeforeCallAsync          = beforeCallAsync;
                settings.AfterCallAsync           = afterCallAsync;
                settings.OnErrorAsync             = onErrorAsync;
                settings.Redirects.ForwardHeaders = true;
            });
        }
Пример #27
0
        /// <summary>
        ///     Default constructor.
        /// </summary>
        /// <param name="apiKey"> Your OneSignal API key </param>
        /// <param name="apiUri"> API uri </param>
        protected ResourceBase(string apiKey, string apiUri = "https://onesignal.com/api/v1")
        {
            ApiKey = apiKey;

            ApiUri = apiUri;

            FlurlHttp.Configure(config =>
            {
                config.JsonSerializer = new NewtonsoftJsonSerializer(
                    new JsonSerializerSettings
                {
                    MissingMemberHandling = MissingMemberHandling.Ignore,
                    NullValueHandling     = NullValueHandling.Ignore,
                    DefaultValueHandling  = DefaultValueHandling.Include
                }
                    );
            });
        }
        private void ConfigureFlurlHttpClient()
        {
            FlurlHttp.Configure(settings =>
            {
                var contractResolver = new DefaultContractResolver
                {
                    NamingStrategy = new CamelCaseNamingStrategy()
                };

                var jsonSettings = new JsonSerializerSettings
                {
                    NullValueHandling = NullValueHandling.Ignore,
                    ContractResolver  = contractResolver
                };

                settings.JsonSerializer = new NewtonsoftJsonSerializer(jsonSettings);
            });
        }
Пример #29
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));
 }
Пример #30
0
        public static void Configure()
        {
            FlurlHttp.Configure(settings => {
                var jsonSettings = new JsonSerializerSettings
                {
                    ContractResolver  = new CamelCasePropertyNamesContractResolver(),
                    NullValueHandling = NullValueHandling.Ignore,
                    Converters        = new List <Newtonsoft.Json.JsonConverter>
                    {
                        new Newtonsoft.Json.Converters.StringEnumConverter()
                    }
                };

                var serializer = new NewtonsoftJsonSerializer(jsonSettings);

                settings.JsonSerializer = serializer;
            });
        }