Skip to content

Instantly share code, notes, and snippets.

@DamianReeves
Created October 26, 2016 17:23
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 DamianReeves/1abdca3cc9744b1ea578d2165e901727 to your computer and use it in GitHub Desktop.
Save DamianReeves/1abdca3cc9744b1ea578d2165e901727 to your computer and use it in GitHub Desktop.
Akka config extensions
using System;
using System.Collections.Generic;
using Akka.Configuration;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json.Linq;
namespace Akka.Configuration
{
public static class ConfigExtensions
{
public static Config ToAkkaConfig(this IConfiguration configuration)
{
var akkaProperty = new JProperty("akka", JValue.CreateUndefined());
var hocon = new JObject(akkaProperty);
var stack = new Stack<StackFrame>();
stack.Push(new StackFrame{Configuration = configuration, Property = akkaProperty});
while (stack.Count > 0)
{
var stackFrame = stack.Pop();
var config = stackFrame.Configuration;
var property = stackFrame.Property;
var configurationSection = config as IConfigurationSection;
if (configurationSection != null)
{
// We have a configuration section
if (configurationSection.Value == null)
{
int index;
if (int.TryParse(configurationSection.Key, out index))
{
if (property.Value == null || property.Value.Type == JTokenType.Undefined)
{
// Switch the property over to being an array
property.Value = new JArray();
}
}
}
else
{
switch (property.Value.Type)
{
case JTokenType.Undefined:
property.Value = configurationSection.Value;
break;
case JTokenType.Array:
((JArray)property.Value).AddFirst(configurationSection.Value);
break;
}
}
}
foreach (var child in config.GetChildren())
{
int index;
JProperty prop = null;
if (Int32.TryParse(child.Key, out index))
{
var segments = child.Path.Split(':');
if (segments.Length > 1)
{
//var propertyName = segments[segments.Length - 2];
//prop = new JProperty(propertyName, JValue.CreateUndefined());
switch (property.Value.Type)
{
case JTokenType.Undefined:
prop = property;
property.Value = new JArray();
break;
default:
prop = property;
break;
}
}
}
else
{
prop = new JProperty(child.Key, JValue.CreateUndefined());
switch (property.Value.Type)
{
case JTokenType.Undefined:
property.Value = new JObject(prop);
break;
case JTokenType.Object:
((JObject)property.Value).Add(prop);
break;
}
}
stack.Push(new StackFrame
{
Configuration = child,
Property = prop
});
}
}
var hoconText = hocon.ToString();
return ConfigurationFactory.ParseString(hoconText);
}
private class StackFrame
{
public IConfiguration Configuration { get; set; }
public JProperty Property { get; set; }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment