public AdminRegisterPageViewModel(INavigationService navigationService) { FlurlClient = new FlurlClient(ServerPath.Path); Provider = AdminModule.Provider; _navigationService = navigationService; RegisterCommand = new DelegateCommand(RegisterCustomer); }
public static async Task <T> PostJsonAsync <T>(this IFlurlClient client, string route, object request, CancellationToken cancellationToken = default(CancellationToken), HttpCompletionOption completionOption = HttpCompletionOption.ResponseContentRead) { var routeUrl = route.WithParams(request, true); var response = await client.Request(routeUrl.Path).PostJsonAsync(request, cancellationToken, completionOption: completionOption); return(await response.Content.ReadAs <T>()); }
public MultiplexedRestClient(IAuthenticationProvider authenticator, string userAgent, IEnumerable <Uri> baseUris) : this(baseUris) { if (userAgent == null) { throw new ArgumentNullException(nameof(userAgent)); } _authenticator = authenticator ?? throw new ArgumentNullException(nameof(authenticator)); // Setup the underlying Flurl instance UnderlyingClient = new FlurlClient() .Configure(settings => { settings.JsonSerializer = new ProgressiveJsonSerializer(); // HTTP status codes manually handled by this multiplexer settings.AllowedHttpStatusRange = "*"; }) .WithHeader("Accept-Encoding", "gzip, deflate") .AllowAnyHttpStatus(); UnderlyingClient .HttpClient .DefaultRequestHeaders .TryAddWithoutValidation("User-Agent", userAgent); }
public HttpBenchmark() { _api = "http://localhost/SampleApi/"; _flurlClient = new FlurlClient(); _refitClient = RestService.For <IRefitSampleApiClient>(_api); }
public TechJobItemsPageViewModel(INavigationService navigationService) { FlurlClient = new FlurlClient(ServerPath.Path); _navigatiponService = navigationService; MenuCommand = new DelegateCommand <Issue>(menu); UpdateIssie(); }
public CouchQueryProvider(IFlurlClient flurlClient, CouchSettings settings, string connectionString, string db) { _flurlClient = flurlClient ?? throw new ArgumentNullException(nameof(flurlClient)); _settings = settings ?? throw new ArgumentNullException(nameof(settings)); _connectionString = connectionString ?? throw new ArgumentNullException(nameof(connectionString)); _db = db ?? throw new ArgumentNullException(nameof(db)); }
public ImageGalleryApiClient(IHttpClientFactory httpClientFactory, IHttpContextAccessor httpContextAccessor) { _flurlClient = new FlurlClient(httpClientFactory.CreateClient("api_client")); _httpClientFactory = httpClientFactory; _httpContextAccessor = httpContextAccessor; }
public TechRegisterPageViewModel(INavigationService navigationService) { FlurlClient = new FlurlClient(ServerPath.Path); RegisterCommand = new DelegateCommand(Register); _navigationService = navigationService; GetCategories(); }
/// <summary> /// Asynchronously downloads a file at the specified URL. /// </summary> /// <param name="client">The flurl client.</param> /// <param name="localFolderPath">Path of local folder where file is to be downloaded.</param> /// <param name="localFileName">Name of local file. If not specified, the source filename (last segment of the URL) is used.</param> /// <param name="bufferSize">Buffer size in bytes. Default is 4096.</param> /// <returns>A Task whose result is the local path of the downloaded file.</returns> public static async Task <string> DownloadFileAsync(this IFlurlClient client, string localFolderPath, string localFileName = null, int bufferSize = 4096) { if (localFileName == null) { localFileName = client.Url.Path.Split('/').Last(); } // need to temporarily disable autodispose if set, otherwise reading from stream will fail var autoDispose = client.Settings.AutoDispose; client.Settings.AutoDispose = false; try { var response = await client.SendAsync(HttpMethod.Get, completionOption : HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false); // http://codereview.stackexchange.com/a/18679 using (var httpStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) using (var filestream = await FileUtil.OpenWriteAsync(localFolderPath, localFileName, bufferSize).ConfigureAwait(false)) { await httpStream.CopyToAsync(filestream, bufferSize).ConfigureAwait(false); } return(FileUtil.CombinePath(localFolderPath, localFileName)); } finally { client.Settings.AutoDispose = autoDispose; if (client.Settings.AutoDispose) { client.Dispose(); } } }
public AdminIssueDetailPageViewModel(INavigationService navigationService, IEventAggregator eventAggregator) { IsCost = false; PublishCommand = new DelegateCommand(Publish); if (AdminModule.Latitude == null) { LocationAvailable = false; } else { LocationAvailable = true; } _eventAggregator = eventAggregator; FlurlClient = new FlurlClient(ServerPath.Path); _navigationService = navigationService; JobcardCommand = new DelegateCommand(Jobcard); DeleteCommand = new DelegateCommand(DeleleIssue); CompleteCommand = new DelegateCommand(Complete); AddCostCommand = new DelegateCommand(AddCost); LocationCommand = new DelegateCommand(ViewLocation); ImagesCommand = new DelegateCommand(Images); AdminModule.hubProxy.On <Issue>("updateIssue", _issue => { Issue = _issue; }); }
public TestsEndpoint(string basePath, IFlurlClient flurlClient, ChildEndpointFactory childEndpointFactory) : base(flurlClient) { this.childEndpointFactory = childEndpointFactory; BasePath = basePath; }
public TechAddCustomerViewModel(INavigationService navigationService) { FlurlClient = new FlurlClient(ServerPath.Path); Provider = TechnicianModule.Provider; _navigationService = navigationService; RegisterCommand = new DelegateCommand(Register); }
/// <summary> /// Constructor for dedicated services with Flurl client initialization already performed. /// </summary> /// <param name="client">The Flurl client.</param> /// <param name="version">The server's Api version.</param> /// <param name="logErrors">Set this flag to false to disable logging of client errors.</param> public BasicServiceProvider(IFlurlClient client, ApiVersion version, bool logErrors = true) { Client = client ?? throw new ArgumentNullException(nameof(client), "FlurlClient can not be null."); Version = version; LogClientErrors = logErrors; }
public AdminCalendarViewModel(INavigationService navigationService) { FlurlClient = new FlurlClient(ServerPath.Path); //DateCommand = new DelegateCommand<DateTime>(SelectedDate); _navigationService = navigationService; Getdates(); }
/// <summary> /// Creates a new CouchDB client. /// </summary> /// <param name="connectionString">URI to the CouchDB endpoint.</param> /// <param name="couchSettingsFunc">A function to configure the client settings.</param> /// <param name="flurlSettingsFunc">A function to configure the HTTP client.</param> public CouchClient(string connectionString, Action <CouchSettings> couchSettingsFunc = null, Action <ClientFlurlHttpSettings> flurlSettingsFunc = null) { if (string.IsNullOrEmpty(connectionString)) { throw new ArgumentNullException(nameof(connectionString)); } _settings = new CouchSettings(); couchSettingsFunc?.Invoke(_settings); ConnectionString = connectionString; _flurlClient = new FlurlClient(connectionString).Configure(s => { s.JsonSerializer = new NewtonsoftJsonSerializer(new JsonSerializerSettings { ContractResolver = new CouchContractResolver(_settings.PropertiesCase) }); s.BeforeCall = OnBeforeCall; if (_settings.ServerCertificateCustomValidationCallback != null) { s.HttpClientFactory = new CertClientFactory(_settings.ServerCertificateCustomValidationCallback); } flurlSettingsFunc?.Invoke(s); }); }
public ClientAddCustomerViewModel(INavigationService navigationService) { FlurlClient = new FlurlClient(ServerPath.Path); Customer = ClientModule.Customer; _navigationService = navigationService; RegisterCommand = new DelegateCommand(Register); }
public FreightPopService(FreightPopConfig config) { _flurl = new FlurlClient(); _username = config.Username; _password = config.Password; _freightPopBaseUrl = config.BaseUrl; }
/// <summary> /// Executes a request and returns a JToken for querying. Throws an exception when the response is invalid. /// Use this method when the expected response is a single line or simple object that doesn't warrant its own class. /// </summary> /// <remarks> /// This method will automatically dispose the <paramref name="baseClient"/> and <paramref name="baseContent" /> when finished. /// </remarks> protected async Task <JToken> ExecuteRequestAsync(IFlurlClient baseClient, HttpMethod method, JsonContent baseContent = null) { var policyResult = await _ExecutionPolicy.Run(baseClient, baseContent, async (client, content) => { var request = client.SendAsync(method, content); var response = await request; var rawResult = await request.ReceiveString(); //Check for and throw exception when necessary. CheckResponseExceptions(response, rawResult); JToken jtoken = null; // Don't parse the result when the request was Delete. if (method != HttpMethod.Delete) { jtoken = JToken.Parse(rawResult); } return(new RequestResult <JToken>(response, jtoken, rawResult)); }); baseClient.Dispose(); baseContent?.Dispose(); return(policyResult); }
public TodoApiRepository() { restClient = new FlurlClient(baseUrl: TodoAppConfig.Instance().ApiRepositoryBaseUrl); string apiKeyFilePath = Path.Combine(DIRECTORY_PATH, API_TOKEN_FILENAME); if (!File.Exists(apiKeyFilePath)) { string userCredentialFile = Path.Combine(DIRECTORY_PATH, USER_CREDENTIAL_FILENAME); if (!File.Exists(userCredentialFile)) { throw new FileNotFoundException($"File '{Path.GetFileName(userCredentialFile)}' not found in '{DIRECTORY_PATH}'."); } string[] credentials = File.ReadAllLines(userCredentialFile).Select(str => str.Trim()).ToArray(); if (credentials == null || !credentials.Any()) { throw new InvalidOperationException("Invalid credential format."); } var resp = restClient.Request("auth", "login") .PostJsonAsync(new { username = credentials[0], password = credentials[1] }).GetAwaiter().GetResult(); var tokenObj = resp.GetJsonAsync <ApiToken>().GetAwaiter().GetResult(); string tokenJson = JsonSerializer.Serialize(tokenObj); File.WriteAllText(apiKeyFilePath, tokenJson, Encoding.UTF8); } string json = File.ReadAllText(apiKeyFilePath); var token = JsonSerializer.Deserialize <ApiToken>(json); restClient.WithOAuthBearerToken(token.Token); }
/// <summary> /// Executes a request and returns the given type. Throws an exception when the response is invalid. /// Use this method when the expected response is a single line or simple object that doesn't warrant its own class. /// </summary> /// <param name="baseClient"> /// The request to be executed. Note that this request will be automatically disposed when the method returns. /// </param> /// <param name="method"> /// HTTP method to be used by the request. /// </param> /// <param name="baseContent"> /// Content that gets appended to the request body. Can be null. In most cases, you'll want to use <see cref="JsonContent"/>. /// Note that the content will be automatically disposed when the method returns. /// </param> /// <remarks> /// This method will automatically dispose the <paramref name="baseClient"/> and <paramref name="baseContent" /> when finished. /// </remarks> protected async Task <T> ExecuteRequestAsync <T>(IFlurlClient baseClient, HttpMethod method, JsonContent baseContent = null, string rootElement = null) where T : new() { var policyResult = await _ExecutionPolicy.Run <T>(baseClient, baseContent, async (client, content) => { var request = client.SendAsync(method, content); var response = await request; var rawResult = await request.ReceiveString(); //Check for and throw exception when necessary. CheckResponseExceptions(response, rawResult); // This method may fail when the method was Delete, which is intendend. // Delete methods should not be parsing the response JSON and should instead // be using the non-generic ExecuteRequestAsync. var reader = new JsonTextReader(new StringReader(rawResult)); var data = _Serializer.Deserialize <JObject>(reader).SelectToken(rootElement); var result = data.ToObject <T>(); return(new RequestResult <T>(response, result, rawResult)); }); baseClient.Dispose(); baseContent?.Dispose(); return(policyResult); }
/// <summary> /// Sends an asynchronous multipart/form-data POST request. /// </summary> /// <param name="buildContent">A delegate for building the content parts.</param> /// <param name="client">The Flurl client.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>A Task whose result is the received HttpResponseMessage.</returns> public static Task <HttpResponseMessage> PostMultipartAsync(this IFlurlClient client, Action <CapturedMultipartContent> buildContent, CancellationToken cancellationToken = default(CancellationToken)) { var cmc = new CapturedMultipartContent(client.Settings); buildContent(cmc); return(client.SendAsync(HttpMethod.Post, cmc, cancellationToken)); }
static async Task <IFlurlClient> CreateNewClientAsync() { IFlurlClient client = null; const int MaxRetryCount = 5; int retryCount; for (retryCount = 0; retryCount < MaxRetryCount; retryCount++) { client = new FlurlClient($"{CookieUrl}?{Helper.GetRandomString(8)}") // Random query param to avoid cached response .WithHeader(UserAgentKey, UserAgentValue) .EnableCookies(); await client.Request().GetAsync().ConfigureAwait(false); if (client.Cookies?.Count > 0) { break; } await Task.Delay(100).ConfigureAwait(false); } if (retryCount == MaxRetryCount) { throw new Exception("Connection has failed, please try to connect later"); } return(client); }
/// <summary> /// Sets an HTTP header to be sent with all requests made with this FlurlClient. /// </summary> /// <param name="client">The client.</param> /// <param name="name">HTTP header name.</param> /// <param name="value">HTTP header value.</param> /// <returns>The modified FlurlClient.</returns> public static IFlurlClient WithHeader(this IFlurlClient client, string name, object value) { var values = new[] { value?.ToString() }; client.HttpClient.DefaultRequestHeaders.Add(name, values); return(client); }
internal FtpClientProxy(IFtpClientProxyConfig config, IFlurlClientFactory client, TokenProvider tokenProvider, string host, NetworkCredential credentials) { this._config = config; _tokenProvider = tokenProvider; this.Host = host; this.Credentials = credentials; _client = client.Get(_config.FtpProxyWebInterfaceBaseUri) .Configure(c => { c.HttpClientFactory = new UntrustedCertClientFactory(); c.ConnectionLeaseTimeout = TimeSpan.FromMinutes(30); }) .WithHeader("Accept", "application/json, text/json") .WithHeader("Accept-Encoding", "gzip, deflate") .WithTimeout(TimeSpan.FromMinutes(20)) .AllowHttpStatus(HttpStatusCode.NotFound) ; _client.BaseUrl = _config.FtpProxyWebInterfaceBaseUri.ToString(); _connectionInfo = new ConnectionInfo { Host = this.Host, Username = this.Credentials.UserName, Password = this.Credentials.Password, }; }
public ManagementApiClientFactory( IFlurlClientFactory flurlClientFactory, IOptionsMonitor <Auth0Options> auth0OptionsMonitor) { this.flurlClient = flurlClientFactory.Get("https://dogger.eu.auth0.com/oauth/token"); this.auth0OptionsMonitor = auth0OptionsMonitor; }
public TechCalendarPageViewModel(INavigationService navigationService) { FlurlClient = new FlurlClient(ServerPath.Path); //DateCommand = new DelegateCommand<DateTime>(SelectedDate); _navigationService = navigationService; Getdates().ConfigureAwait(true); }
public static async Task <HttpResponseMessage> PostRequestAsync(this IFlurlClient client, IRequest request, CancellationToken token = default(CancellationToken), bool isMultipart = false) { // Get all form keys from request var keys = request.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly) .Where(prop => prop.GetCustomAttribute <FormIgnoreAttribute>() == null); // Get determination key for determine if the web call is a v2 call or not var v2DetKey = keys.SingleOrDefault(prop => prop.GetCustomAttribute <V2DeterminationKeyAttribute>() != null); bool isV2 = v2DetKey != null && v2DetKey.GetValue(request) != null; if (isV2 && v2DetKey.GetCustomAttribute <V2DeterminationKeyAttribute>().IsByVersionNumber) { isV2 &= v2DetKey.GetValue(request).ToString() == "2.0"; } // Get keys to process var keysToProcess = keys.Except(keys.Where(k => k.GetCustomAttribute <FormAttribute>()?.IsFor.Equals(isV2 ? VersionOption.V1 : VersionOption.V2) ?? false)); // Check null for required keys foreach (var option in new List <VersionOption> { isV2?VersionOption.V2 : VersionOption.V1, VersionOption.All }) { var keysToValidate = keysToProcess.Where(k => k.GetCustomAttribute <FormAttribute>()?.IsFor.Equals(option) ?? false); var invalidKeys = keysToValidate.Where(k => (k.GetCustomAttribute <FormAttribute>()?.IsRequiredFor.HasFlag(option) ?? false) && k.GetValue(request) == null); if (invalidKeys.Any()) { throw new KeyRequiredException(invalidKeys.Select(k => k.Name).ToArray()); } } Func <PropertyInfo, string> keyName = prop => prop.GetCustomAttribute <FormAttribute>()?.Name ?? prop.Name.ToLower(); // Process keys to form var form = new Dictionary <string, string>(); keysToProcess.Where(ok => ok.GetValue(request) != null) .ToList() .ForEach(ok => { if (ok.GetValue(request) is IEnumerable <string> list) { foreach (var item in list) { form.Add(keyName(ok), item); } } else { var objValue = ok.GetValue(request); if (!(objValue is bool && ok.GetCustomAttribute <FormAttribute>().AddKeyOnlyIfBoolTrue&& !(bool)objValue)) { form.Add(keyName(ok), ok.PropertyType.IsSimpleType() ? objValue.ToString() : JsonConvert.SerializeObject(ok.GetValue(request), SerializationHelper.SerializationSettings)); } } }); return(isMultipart ? await client.PostMultipartAsync(mp => mp.AddStringParts(form)) : await client.PostUrlEncodedAsync(form, token)); }
public WipeCloudflareCacheCommandHandler( IOptionsMonitor <CloudflareOptions> cloudflareCacheOptionsMonitor, IFlurlClientFactory flurlClientFactory) { this.cloudflareCacheOptionsMonitor = cloudflareCacheOptionsMonitor; this.flurlClient = flurlClientFactory.Get("https://api.cloudflare.com"); }
private string GetAccessToken(IFlurlClient client) { IEnumerable <string> values = new List <string>(); return(client.HttpClient.DefaultRequestHeaders.TryGetValues(REQUEST_HEADER_ACCESS_TOKEN, out values) ? values.FirstOrDefault() : null); }
public BaseRepository(IFlurlClientFactory flurlFac, IConfig configuration) { _flurlClient = flurlFac.Get(configuration.UrlBase); _timeOut = configuration.TimeOut; _headers = configuration.Headers; }