Created
June 27, 2014 11:15
-
-
Save sixeyed/60e56bc4f06b77081b04 to your computer and use it in GitHub Desktop.
A .NET consumer for app config hosted in a remote CMS server - see http://geekswithblogs.net/EltonStoneman/archive/2014/06/04/using-cms-for-app-configurationndashpart-1-deploy-umbraco.aspx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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