Example
This is a more comprehensive example that:
- Creates a host builder that includes the configuration file, HTTP client and the SimTransIF interface as injected services.
- Includes a post configuration service to ensure configuration limits and computed properties are respected, if they are added to the configuration.
- Uses the options monitor pattern to access configuration values.
- Builds a minimal SimTrans SN60 transaction.
- Asynchronously sends it to the server.
- Writes the result to the console.
For convenience, the SimTransIF interface and class are in the same file as they program's main
method. They would normally be in separate files.
using System;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using SimTransIF.Client;
using SimTransIF.Common;
namespace SimTransIFTestClient
{
class Program
{
static async Task Main(string[] args)
{
// Get configuration builder
string programDataPath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
string AppDataPath = Path.Join(programDataPath, @"SAWaves\SimTransIF");
IConfigurationRoot Configuration;
IConfigurationBuilder configBuilder = new ConfigurationBuilder()
.SetBasePath(AppDataPath)
.AddJsonFile("config.json", optional: true, reloadOnChange: false);
Configuration = configBuilder.Build();
// Configure and create a host builder to have the client configuration, an HttpClient and
// SimTranIF.
IHostBuilder hostBuilder = new HostBuilder()
.ConfigureServices((hostContext, services) =>
{
services.Configure(Configuration.GetSection("ClientSettings"));
services.PostConfigure(settings =>
{
settings.SetLimits();
settings.ComputeProperties();
});
services.AddHttpClient();
services.AddTransient();
}
).UseConsoleLifetime();
IHost host = hostBuilder.Build();
// Get the SimTransIF service and call its API
string result = "";
using (IServiceScope serviceScope = host.Services.CreateScope())
{
IServiceProvider services = serviceScope.ServiceProvider;
try
{
ISimTransIF service = services.GetRequiredService();
result = await service.CallApi();
}
catch(Exception ex)
{
ILogger log = services.GetRequiredService>();
log.LogError(ex, $"API call failed because of: {ex.Message}");
}
}
Console.WriteLine(result);
return 0;
}
///
/// This sample interface for SimTransIF only has one method.
///
///
/// A practical implementation is likely to have more methods.
///
private interface ISimTransIF
{
Task CallApi();
}
///
/// Local class that implements the ISimTransIF interface.
///
///
/// This implements the creation of the the SimTrans transaction to send to the server and the
/// actual sending of the data as a dependency injected service.
///
private class SimTransIF : ISimTransIF
{
private readonly IHttpClientFactory _clientFactory;
private readonly ClientSettings settings;
WebClient client;
///
/// Creates a new SimTransIF instance with a new SimTransIF.Client.WebClient
///
/// An injected HTTP client factory
/// Injected options that contains the client configuration parameters.
public SimTransIF(IHttpClientFactory clientFactory, IOptionsMonitor options)
{
_clientFactory = clientFactory;
settings = options.CurrentValue;
client = new WebClient(settings.SharedId, settings.Uri, clientFactory.CreateClient());
}
///
/// Sets up a simmple SN60 SimTrans transaction and sends it to the server.
///
/// A string version of the server submission status.
public async Task CallApi()
{
if (await client.SendAsync("SN60", GetSn60Content()))
{
Console.WriteLine(client.Result);
return "Success";
}
else
return client.Status.ToString();
}
///
/// Set up a minimal SN60 SimTrans transaction to send to the server.
///
/// An SN60 transaction in Json format.
public string GetSn60Content()
{
string jsonString;
Sn60 data = new Sn60();
data.Token = client.Token;
data.TransactionId = "trx001";
data.District = 1;
data.Material = "MS";
data.Thickness = 5;
data.Cost = 10.0;
jsonString = JsonConvert.SerializeObject(data);
return jsonString;
}
}
}
}