[Headers("Accept: application/json")] public interface IHttpbinApi { [Get("/basic-auth/{username}/{password}")] Task<AuthResult> BasicAuth(string username, string password, [Header("Authorization")] string authToken, CancellationToken ctx); [Get("/cache")] Task<HttpResponseMessage> CheckIfModified([Header("If-Modified-Since")] string lastUpdateAtString, CancellationToken ctx); [Post("/post")] Task<HttpResponseMessage> FormPost([Body(BodySerializationMethod.UrlEncoded)] FormData data, CancellationToken ctx); }
var client = new HttpClient(new NativeMessageHandler()) { BaseAddress = new Uri("http://httpbin.org") }; _httpbinApiService = RestService.For<IHttpbinApi>(client);
public class AuthResult { [JsonProperty("authenticated")] public bool IsAuthenticated { get; set; } [JsonProperty("user")] public string Login { get; set; } }
protected async Task<RequestResult> MakeRequest<T>(Func<CancellationToken, Task<T>> loadingFunction, CancellationToken cancellationToken) { Exception exception = null; var result = default(T); try { result = await Policy.Handle<WebException>().Or<HttpRequestException>() .WaitAndRetryAsync(3, i => TimeSpan.FromMilliseconds(300), (ex, span) => exception = ex) .ExecuteAsync(loadingFunction, cancellationToken); } catch (Exception e) { // - DNS exception = e; } //TODO: return result; }
var authToken = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes($"{username}:{password}")); return await MakeRequest(ct => _httpbinApiService.BasicAuth(username, password, authToken, ct), cancellationToken);
var cache = BlobCache.LocalMachine; var cachedObjects = cache.GetAndFetchLatest("objects", GetRemoteObjectAsync, offset => { TimeSpan elapsed = DateTimeOffset.Now - offset; return elapsed > new TimeSpan(hours: 0, minutes: 30, seconds: 0); });
public static class LocalCache { private class CachedObject : RealmObject { [PrimaryKey] public string Key { get; set; } public string Value { get; set; } public DateTimeOffset UpdatedAt { get; set; } } private static readonly RealmConfiguration Configuration = new RealmConfiguration("cache.realm", true); private static Realm Db => Realm.GetInstance(Configuration); public static async Task WriteToCache<T>(string key, T data, DateTimeOffset timeStamp) { if (String.IsNullOrEmpty(key) || data == null || timeStamp == DateTimeOffset.MinValue) return; var currentValue = Db.All<CachedObject>().Where(o => o.Key == key).ToList().FirstOrDefault(); if (currentValue == null) await Db.WriteAsync(db => { var newValue = db.CreateObject<CachedObject>(); newValue.Key = key; newValue.UpdatedAt = timeStamp; newValue.Value = JsonConvert.SerializeObject(data); }); else using (var transaction = Db.BeginWrite()) { currentValue.Value = JsonConvert.SerializeObject(data); currentValue.UpdatedAt = timeStamp; transaction.Commit(); } } public static DateTimeOffset CacheLastUpdated(string key) { if (String.IsNullOrEmpty(key)) return DateTimeOffset.MinValue; var currentValue = Db.All<CachedObject>().Where(o => o.Key == key).ToList().FirstOrDefault(); return currentValue?.UpdatedAt ?? DateTimeOffset.MinValue; } public static void RemoveCache(string key) { if (String.IsNullOrEmpty(key)) return; var currentValue = Db.All<CachedObject>().Where(o => o.Key == key).ToList().FirstOrDefault(); if (currentValue == null) return; using (var transaction = Db.BeginWrite()) { Db.Remove(currentValue); transaction.Commit(); } } public static T GetFromCache<T>(string key) { if (String.IsNullOrEmpty(key)) return default(T); var currentValue = Db.All<CachedObject>().Where(o => o.Key == key).ToList().FirstOrDefault(); return currentValue?.Value == null ? default(T) : JsonConvert.DeserializeObject<T>(currentValue.Value); } public static void ClearCache() { Realm.DeleteRealm(Configuration); } }
Source: https://habr.com/ru/post/310704/
All Articles