Skip to content

Instantly share code, notes, and snippets.

@sixeyed
Created June 27, 2014 11:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sixeyed/60e56bc4f06b77081b04 to your computer and use it in GitHub Desktop.
Save sixeyed/60e56bc4f06b77081b04 to your computer and use it in GitHub Desktop.
using Newtonsoft.Json.Linq;
using System;
using System.Configuration;
using System.Net;
using System.Runtime.Caching;
using System.Xml;
namespace Api.Core
{
/// <summary>
/// Dynamic representation of remote JSON app config
/// </summary>
/// <remarks>
/// Add the config API url to appSettings, e.g. key="ApiConfig.Url" value="http://config.xyz.com/myapp"
/// This example uses the config to determine how long to cache config. Expects an xs:duration
/// string in the property "caching.configLifespan", e.g. "PT30S" = 30 seconds
/// </remarks>
public class Config
{
private static MemoryCache _Cache = new MemoryCache("_Config");
private static readonly string _ConfigUrl;
static Config()
{
_ConfigUrl = ConfigurationManager.AppSettings["ApiConfig.Url"];
}
public static dynamic Current
{
get
{
EnsureConfig();
return (JObject)_Cache["Current"];
}
}
private static void EnsureConfig()
{
if (_Cache["Current"] == null)
{
using (var client = new WebClient())
{
client.Headers.Add("accept", "application/json");
var json = client.DownloadString(_ConfigUrl);
dynamic config = JObject.Parse(json);
var cacheLifespan = XmlConvert.ToTimeSpan((string)config.caching.configLifespan);
_Cache.Add("Current", config, new CacheItemPolicy
{
AbsoluteExpiration = DateTimeOffset.Now.Add(cacheLifespan)
});
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment