using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Tango.MachineService.Gateway;
namespace Tango.FSE.BL.Services
{
///
/// Represents the gateway service used to retrieve the available Tango system environments/deployment slots.
///
///
public class GatewayService : FSEServiceBase
{
private const string ENVIRONMENTS_COLLECTION = "Environments";
private const string WEB_DEBUG_ADDRESS = "http://localhost:1111";
private ReadOnlyObservableCollection _environments;
///
/// Gets the environments that were last retrieved using the method.
///
public ReadOnlyObservableCollection Environments
{
get { return _environments; }
private set { _environments = value; RaisePropertyChangedAuto(); }
}
///
/// Gets the available environments.
/// Environments are cached on disk.
///
///
public Task> GetEnvironments()
{
return DataResolver>.Builder.New()
.ConfigureCascade(DataResolverNode.Online, DataResolverNode.DiskCache)
.Online((context) =>
{
using (HttpClient http = new HttpClient())
{
http.DefaultRequestHeaders.TryAddWithoutValidation("Cookie", "x-ms-routing-name=self");
GatewayClient client = new GatewayClient(ConfigurationManager.AppSettings.Get("GatewayUrl"), http);
var list = client.GetEnvironments(new EnvironmentsRequest()).Environments.OrderBy(x => x.DisplayIndex).ToList();
LogManager.Log("Online environments retrieved successfully. Caching environments...");
try
{
using (var cache = DiskCache.CreateContext())
{
var collection = cache.Database.GetCollection(ENVIRONMENTS_COLLECTION);
foreach (var environment in list)
{
collection.Upsert(environment);
}
}
}
catch (Exception ex)
{
LogManager.Log(ex, "Error caching online environments.");
}
bool isWebDebug = Environment.GetCommandLineArgs().Contains("-webDebug");
if (isWebDebug)
{
foreach (var item in list)
{
item.MachineServiceAddress = WEB_DEBUG_ADDRESS;
}
}
return list;
}
})
.DiskCache((context) =>
{
using (var cache = DiskCache.CreateContext())
{
var collection = cache.Database.GetCollection(ENVIRONMENTS_COLLECTION);
var environments = collection.FindAll().OrderBy(x => x.DisplayIndex).ToList();
if (environments.Count == 0)
{
//Online failed and no cache found so there must be an Internet connection at least once.
throw new InternetConnectionException();
}
return environments;
}
})
.OnComplete(environments =>
{
Environments = new ReadOnlyObservableCollection(new ObservableCollection(environments));
}).BuildExecuteAsync();
}
}
}