public IHalPersistResult <T> Persist <T>(T resource, HalLink link = null) where T : IHalResource { link = link ?? resource.Links.FirstOrDefault(l => l.Rel == "self"); if (link == null) { throw new HalPersisterException("No link found for persisting: " + resource); } var href = new Uri(link.Href, UriKind.Relative); if (link.IsTemplated) { href = HalClient.ResolveTemplate(link, new Dictionary <string, object>()); } var json = JsonConvert.SerializeObject(resource); var content = new StringContent(json, Encoding.UTF8, "application/json"); var result = resource.IsNew ? HttpClient.PostAsync(href, content).Result : HttpClient.PutAsync(href, content).Result; var ret = new HalPersistResult <T> { Success = result.IsSuccessStatusCode, HttpStatusCode = (int)result.StatusCode }; if (result.IsSuccessStatusCode) { var settings = new JsonSerializerSettings { Converters = new List <JsonConverter>() { new HalResourceConverter(resource.GetType()) } }; ret.Resource = JsonConvert.DeserializeObject <T>(result.Content.ReadAsStringAsync().Result, settings); } return(ret); }
public static async Task PagingExample() { var client = new HalClient(new HalKitConfiguration("http://test.dev.local/api")); var api = await client.GetRootAsync<Api>(); // These two will be the same var embeddedFirstApiVersion = api.ApiVersion.First(); var linkedApiVersion = client.GetAsync<ApiVersion>(api.ApiVersionLink).Result; }
public void AssertThatHttpClientCanBeProvided() { var baseAddress = _fixture.Create <Uri>(); var http = new HttpClient { BaseAddress = baseAddress }; var sut = new HalClient(http); sut.HttpClient.BaseAddress.Should().Be(baseAddress); }
private IHalClient GetClient() { RefreshAccessTokenIfNeeded(); var halClient = new HalClient(); halClient.HttpClient.BaseAddress = new Uri(_baseUrl); halClient.HttpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", _accessToken); halClient.HttpClient.DefaultRequestHeaders.Add("FOXY-API-VERSION", "1"); return(halClient); }
public ViagogoClient( ProductHeaderValue product, IGogoKitConfiguration configuration, IOAuth2TokenStore tokenStore, IJsonSerializer serializer, IHttpConnection oauthConnection, IHttpConnection apiConnection) { Requires.ArgumentNotNull(product, nameof(product)); Requires.ArgumentNotNull(configuration, nameof(configuration)); Requires.ArgumentNotNull(tokenStore, nameof(tokenStore)); Requires.ArgumentNotNull(serializer, nameof(serializer)); Requires.ArgumentNotNull(oauthConnection, nameof(oauthConnection)); Requires.ArgumentNotNull(apiConnection, nameof(apiConnection)); var halKitConfiguration = new HalKitConfiguration(configuration.ViagogoApiRootEndpoint) { CaptureSynchronizationContext = configuration.CaptureSynchronizationContext }; Configuration = configuration; TokenStore = tokenStore; Hypermedia = new HalClient(halKitConfiguration, apiConnection); var linkFactory = new LinkFactory(configuration); OAuth2 = new OAuth2Client(oauthConnection, configuration); User = new UserClient(Hypermedia); Search = new SearchClient(Hypermedia); Addresses = new AddressesClient(User, Hypermedia, linkFactory); Purchases = new PurchasesClient(User, Hypermedia, linkFactory); Sales = new SalesClient(Hypermedia, linkFactory); Shipments = new ShipmentsClient(Hypermedia, linkFactory); PaymentMethods = new PaymentMethodsClient(User, Hypermedia, linkFactory); Countries = new CountriesClient(Hypermedia, linkFactory); Currencies = new CurrenciesClient(Hypermedia, linkFactory); Categories = new CategoriesClient(Hypermedia, linkFactory); Events = new EventsClient(Hypermedia); Listings = new ListingsClient(Hypermedia); Venues = new VenuesClient(Hypermedia); SellerListings = new SellerListingsClient(Hypermedia, linkFactory); Webhooks = new WebhooksClient(Hypermedia, linkFactory); BatchClient = new BatchClient(apiConnection, new ApiResponseFactory(serializer, halKitConfiguration), serializer, new LinkResolver()); }
public static async Task<Workflow> RealisticExample() { var client = new HalClient(new HalKitConfiguration("http://test.dev.local/api/apiversion/1")); var api = await client.GetRootAsync<ApiVersion>(); return await client.GetAsync<Workflow>(api.WorkflowLink, new {id = 1}); }
public ReadActionHandler(HalClient halClient) { HasBody = false; Client = halClient; }
public void AssertThatDefaultHttpClientCanBeUsed() { var sut = new HalClient(); sut.HttpClient.BaseAddress.Should().BeNull("Because it hasn't been set."); }
private static void Main(string[] args) { IConfigFileClient <JObject, JToken> configFileLocal = new JSONConfigFileClient(); try { configFileLocal.Load(MagicStringEnumerator.DefaultLocalConfigPath); Log.Instance?.Info($"Configuration file {MagicStringEnumerator.DefaultLocalConfigPath} loaded."); } catch (Exception ex) { Log.Instance?.Error($"{MagicStringEnumerator.DefaultLocalConfigPath}: {ex.Message}"); CleanExit(); } var ip = configFileLocal.GetAddress(); var port = configFileLocal.GetPort(); Log.Instance?.Info($"Server ip: {ip}"); Log.Instance?.Info($"Server port: {port}"); AppDomain.CurrentDomain.ProcessExit += (o, e) => { CleanExit(); }; client = new HalClient(ip, port); new Thread(async() => { await client.StartAsync(); }).Start(); IPluginMaster pluginMaster = new PluginMasterBasePlugin(); /* * The plugin manager will manage and schedule plugins * * when a plugin need to be executed, PluginManager will launch what the plugin needs and output the result * where desired above. */ APluginManager pluginManager = new ScheduledPluginManager(pluginMaster); // We only want to configure all the plugins when the client has received all the informations and plugins client.OnReceiveDone += async(o, e) => { /* * Here we instanciate the configuration file * Its a JSON format file. * * All HAL's client configuration is here. */ IConfigFileClient <JObject, JToken> configFile = new JSONConfigFileClient(); try { configFile.Load(MagicStringEnumerator.DefaultConfigPath); Log.Instance?.Info($"Configuration file {MagicStringEnumerator.DefaultConfigPath} loaded."); } catch (Exception ex) { Log.Instance?.Error($"{MagicStringEnumerator.DefaultConfigPath}: {ex.Message}"); receiveError = true; CleanExit(); } foreach (var storageName in configFile.GetStorageNames()) { var storage = StorageFactory.CreateStorage(storageName); if (storage is StorageServerFile) { (storage as StorageServerFile).StreamWriter = client.StreamWriter; } else if (storage is StorageLocalFile) { (storage as StorageLocalFile).SavePath = configFile.GetSavePath(); } storages.Add(storage); Log.Instance?.Info($"Storage \"{storageName}\" added."); } await pluginManager.UnscheduleAllPluginsAsync(pluginMaster.Plugins); pluginMaster.RemoveAllPlugins(); /* * A connection string is needed if you want to access a database * * if none is specified, then it will do nothing and return null. */ var connectionStrings = configFile.GetDataBaseConnectionStrings(); var databases = storages.Where(s => s is IDatabaseStorage).ToArray(); for (var i = 0; i < connectionStrings?.Length; ++i) { var db = databases[i]; var connectionString = connectionStrings[i]; db.Init(connectionString); Log.Instance?.Info($"Database \"{db}\" with connection string \"{connectionString}\""); } /* * Here pluginMaster will receive some customs user specifications, * like new extensions or intepreter. */ configFile.SetScriptExtensionsConfiguration(pluginMaster); configFile.SetInterpreterNameConfiguration(pluginMaster); /* * All the plugins in the directory "plugins" will be loaded and added to the plugin master */ foreach (var file in Directory.GetFiles(MagicStringEnumerator.DefaultPluginPath)) { pluginMaster.AddPlugin(file); } /* * Then the configuration of all of the plugins is set. */ configFile.SetPluginsConfiguration(pluginMaster.Plugins); configFileLocal.SetPluginsConfiguration(pluginMaster.Plugins); configFileLocal.SetInterpreterNameConfiguration(pluginMaster); /* * An event is added when the plugin's execution is finished to save it where the user specified above. */ var savePath = configFile.GetSavePath(); foreach (var plugin in pluginMaster.Plugins) { plugin.OnExecutionFinished += async(o, e) => { foreach (var storage in storages) { try { var code = await storage.Save(e.Plugin, e.Result); if (code == StorageCode.Failed) { Log.Instance?.Error("Storage failed."); } } catch (Exception ex) { Log.Instance?.Error($"Storage failed: {ex.Message}"); } } } } ; /* * All the plugins are then schelduled to be launched when needed. */ pluginManager.SchedulePlugins(pluginMaster.Plugins); Log.Instance?.Info("Configuration reloaded."); }; while (!receiveError) { Thread.Sleep(100); } CleanExit(); } }
public UpdateActionHandler(HalClient halClient) { HasBody = true; Client = halClient; }
public void AssertThatDefaultHttpClientCanBeUsed() { var sut = new HalClient(); sut.HttpClient.BaseAddress.Should().BeNull("Because it hasn't been set."); }
public void AssertThatHttpClientCanBeProvided() { var baseAddress = _fixture.Create<Uri>(); var http = new HttpClient {BaseAddress = baseAddress}; var sut = new HalClient(http); sut.HttpClient.BaseAddress.Should().Be(baseAddress); }
public DeleteActionHandler(HalClient halClient) { HasBody = false; Client = halClient; }