elsa-core/src/scripting/Elsa.Scripting.JavaScript/Extensions/ExpandoObjectExtensions.cs
Sipke Schoorstra 21f770bc48
Refactorings and fixes (#168)
* Variables are now stored including their type name for automatic deserialization into their actual type. This is important for use in expressions.
* **SplitObject** and **ExecuteMethod** now use workflow expressions instead of variable names. This allows for more flexibility.
* Improved **Join** activity to allow proper function within looping constructs.
* Improved Variables performance. Variables are no longer serialized/deserialized upon writing/reading perspectively, only when the workflow instance is persisted.
2019-11-17 20:43:16 +01:00

30 lines
1.1 KiB
C#

using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Linq.Expressions;
namespace Elsa.Scripting.JavaScript.Extensions
{
public static class ExpandoObjectExtensions
{
public static T ToObject<T>(this ExpandoObject expandoObject)
{
var dictionary = (IDictionary<string, object>) expandoObject;
var bindings = new List<MemberBinding>();
foreach (var sourceProperty in typeof(T).GetProperties().Where(x => x.CanWrite))
{
var key = dictionary.Keys.SingleOrDefault(x => x.Equals(sourceProperty.Name, StringComparison.OrdinalIgnoreCase));
if (string.IsNullOrEmpty(key)) continue;
var propertyValue = dictionary[key];
bindings.Add(Expression.Bind(sourceProperty, Expression.Constant(propertyValue)));
}
var memberInit = Expression.MemberInit(Expression.New(typeof(T)), bindings);
return Expression.Lambda<Func<T>>(memberInit).Compile().Invoke();
}
}
}