Files
jdescopingtool/OLD/WorkerService/Process/FunctionConverter.cs
T
Joseph Doherty 26ff8d9b4f Initial commit: JDE Scoping Tool migration project
Set up repository with legacy .NET Framework 4.8 source (OLD/),
new .NET 10 Blazor solution (NEW/), OpenSpec specifications,
documentation, and project configuration.
2026-01-02 07:43:29 -05:00

78 lines
3.2 KiB
C#
Executable File

using System;
using System.Linq;
using System.Reflection;
using Newtonsoft.Json;
namespace WorkerService.Process
{
/// <summary>
/// Function JSON converter
/// </summary>
/// <typeparam name="TParameter">Function input type</typeparam>
/// <typeparam name="TOutput">Function output type</typeparam>
public class FunctionConverter<TParameter, TOutput> : JsonConverter
{
/// <summary>
/// Writes the JSON representation of the object
/// </summary>
/// <param name="writer">The JsonWriter to write to</param>
/// <param name="value">The value to write</param>
/// <param name="serializer">The calling serializer</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value is Func<TParameter, TOutput> function)
{
writer.WriteValue($"{function.Method.DeclaringType}.{function.Method.Name}");
}
}
/// <summary>Reads the JSON representation of the object.</summary>
/// <param name="reader">JsonReader to read from</param>
/// <param name="objectType">Type of the object</param>
/// <param name="existingValue">The existing value of object being read</param>
/// <param name="serializer">The calling serializer</param>
/// <returns>The object value</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
//Get the function's full path
string fullFunctionPath = (string)reader.Value;
if (string.IsNullOrEmpty(fullFunctionPath))
{
return null;
}
//Extract class and function names
string className = fullFunctionPath.Substring(0, fullFunctionPath.LastIndexOf(".", StringComparison.Ordinal));
string functionName = fullFunctionPath.Substring(fullFunctionPath.LastIndexOf(".", StringComparison.Ordinal) + 1);
//Get the class type
Type classType = AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes()).FirstOrDefault(t => string.Equals(t.FullName, className, StringComparison.CurrentCultureIgnoreCase));
if (classType == null)
{
return null;
}
//Get the function's method info
MethodInfo methodInfo = classType.GetMethod(functionName);
if (methodInfo == null)
{
return null;
}
return (Func<TParameter, TOutput>)methodInfo.CreateDelegate(typeof(Func<TParameter, TOutput>));
}
/// <summary>
/// Determines whether this instance can convert the specified object type
/// </summary>
/// <param name="objectType">Type of the object</param>
/// <returns>
/// Whether or not this instance can convert ot the specified object type
/// </returns>
public override bool CanConvert(Type objectType)
{
return objectType == typeof(Func<TParameter, TOutput>);
}
}
}