重构了底层,方便向Android、Web、Linux进行跨平台迁移

This commit is contained in:
fengjiayi
2024-09-15 12:15:32 +08:00
parent 0271825fa9
commit 19247b5afe
51 changed files with 4987 additions and 1526 deletions

View File

@@ -9,13 +9,17 @@ namespace Serein.Library.Core.NodeFlow
/// </summary>
public class DynamicContext: IDynamicContext
{
public DynamicContext(ISereinIoc sereinIoc)
public DynamicContext(ISereinIoc sereinIoc, IFlowEnvironment flowEnvironment)
{
SereinIoc = sereinIoc;
FlowEnvironment = flowEnvironment;
}
public NodeRunCts NodeRunCts { get; set; }
public ISereinIoc SereinIoc { get; }
public IFlowEnvironment FlowEnvironment { get; }
public Task CreateTimingTask(Action action, int time = 100, int count = -1)
{
NodeRunCts ??= SereinIoc.GetOrInstantiate<NodeRunCts>();

View File

@@ -66,7 +66,7 @@ namespace Serein.Library.Core.NodeFlow
public class FlipflopContext : IFlipflopContext
{
public FlowStateType State { get; set; }
//public TResult? Data { get; set; }
public object Data { get; set; }
public FlipflopContext(FlowStateType ffState)

View File

@@ -12,13 +12,15 @@ namespace Serein.Library.Framework.NodeFlow
/// </summary>
public class DynamicContext : IDynamicContext
{
public DynamicContext(ISereinIoc sereinIoc)
public DynamicContext(ISereinIoc sereinIoc, IFlowEnvironment flowEnvironment)
{
SereinIoc = sereinIoc;
FlowEnvironment = flowEnvironment;
}
public NodeRunCts NodeRunCts { get; set; }
public ISereinIoc SereinIoc { get; }
public IFlowEnvironment FlowEnvironment { get; }
public Task CreateTimingTask(Action action, int time = 100, int count = -1)
{
if(NodeRunCts == null)

View File

@@ -6,8 +6,9 @@ namespace Serein.Library.Api
{
public interface IDynamicContext
{
NodeRunCts NodeRunCts { get; set; }
IFlowEnvironment FlowEnvironment { get; }
ISereinIoc SereinIoc { get; }
NodeRunCts NodeRunCts { get; set; }
Task CreateTimingTask(Action action, int time = 100, int count = -1);
}
}

View File

@@ -4,7 +4,7 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Serein.NodeFlow
namespace Serein.Library.Api
{
public interface IDynamicFlowNode
{

View File

@@ -0,0 +1,206 @@
using Serein.Library.Entity;
using Serein.Library.Enums;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading.Tasks;
namespace Serein.Library.Api
{
public class FlowEventArgs : EventArgs
{
public bool IsSucceed { get; protected set; } = true;
public string ErrorTips { get; protected set; } = string.Empty;
}
public delegate void FlowRunCompleteHandler(FlowEventArgs eventArgs);
/// <summary>
/// 加载节点
/// </summary>
public delegate void LoadNodeHandler(LoadNodeEventArgs eventArgs);
public class LoadNodeEventArgs : FlowEventArgs
{
public LoadNodeEventArgs(NodeInfo NodeInfo, MethodDetails MethodDetailss)
{
this.NodeInfo = NodeInfo;
this.MethodDetailss = MethodDetailss;
}
public NodeInfo NodeInfo { get; protected set; }
public MethodDetails MethodDetailss { get; protected set; }
}
/// <summary>
/// 加载DLL
/// </summary>
/// <param name="assembly"></param>
public delegate void LoadDLLHandler(LoadDLLEventArgs eventArgs);
public class LoadDLLEventArgs : FlowEventArgs
{
public LoadDLLEventArgs(Assembly Assembly, List<MethodDetails> MethodDetailss)
{
this.Assembly = Assembly;
this.MethodDetailss = MethodDetailss;
}
public Assembly Assembly { get; protected set; }
public List<MethodDetails> MethodDetailss { get; protected set; }
}
/// <summary>
/// 运行环境节点连接发生了改变
/// </summary>
/// <param name="fromNodeGuid"></param>
/// <param name="toNodeGuid"></param>
/// <param name="connectionType"></param>
public delegate void NodeConnectChangeHandler(NodeConnectChangeEventArgs eventArgs);
public class NodeConnectChangeEventArgs : FlowEventArgs
{
public enum ChangeTypeEnum
{
Create,
Remote,
}
public NodeConnectChangeEventArgs(string fromNodeGuid, string toNodeGuid, ConnectionType connectionType, ChangeTypeEnum changeType)
{
this.FromNodeGuid = fromNodeGuid;
this.ToNodeGuid = toNodeGuid;
this.ConnectionType = connectionType;
this.ChangeType = changeType;
}
public string FromNodeGuid { get; protected set; }
public string ToNodeGuid { get; protected set; }
public ConnectionType ConnectionType { get; protected set; }
public ChangeTypeEnum ChangeType { get; protected set; }
}
/// <summary>
/// 添加了节点
/// </summary>
/// <param name="fromNodeGuid"></param>
/// <param name="toNodeGuid"></param>
/// <param name="connectionType"></param>
public delegate void NodeCreateHandler(NodeCreateEventArgs eventArgs);
public class NodeCreateEventArgs : FlowEventArgs
{
public NodeCreateEventArgs(object nodeModel)
{
this.NodeModel = nodeModel;
}
public object NodeModel { get; private set; }
}
public delegate void NodeRemoteHandler(NodeRemoteEventArgs eventArgs);
public class NodeRemoteEventArgs : FlowEventArgs
{
public NodeRemoteEventArgs(string nodeGuid)
{
this.NodeGuid = nodeGuid;
}
public string NodeGuid { get; private set; }
}
public delegate void StartNodeChangeHandler(StartNodeChangeEventArgs eventArgs);
public class StartNodeChangeEventArgs: FlowEventArgs
{
public StartNodeChangeEventArgs(string oldNodeGuid, string newNodeGuid)
{
this.OldNodeGuid = oldNodeGuid;
this.NewNodeGuid = newNodeGuid; ;
}
public string OldNodeGuid { get; private set; }
public string NewNodeGuid { get; private set; }
}
public interface IFlowEnvironment
{
event FlowRunCompleteHandler OnFlowRunComplete;
event LoadNodeHandler OnLoadNode;
event LoadDLLHandler OnDllLoad;
event NodeConnectChangeHandler OnNodeConnectChange;
event NodeCreateHandler OnNodeCreate;
event NodeRemoteHandler OnNodeRemote;
event StartNodeChangeHandler OnStartNodeChange;
/// <summary>
/// 保存当前项目
/// </summary>
/// <returns></returns>
SereinOutputFileData SaveProject();
/// <summary>
/// 加载项目文件
/// </summary>
/// <param name="projectFile"></param>
/// <param name="filePath"></param>
void LoadProject(SereinOutputFileData projectFile, string filePath);
/// <summary>
/// 从文件中加载Dll
/// </summary>
/// <param name="dllPath"></param>
void LoadDll(string dllPath);
/// <summary>
/// 清理加载的DLL待更改
/// </summary>
void ClearAll();
/// <summary>
/// 获取方法描述
/// </summary>
/// <param name="name"></param>
/// <param name="md"></param>
/// <returns></returns>
bool TryGetMethodDetails(string methodName,out MethodDetails md);
/// <summary>
/// 开始运行
/// </summary>
Task StartAsync();
/// <summary>
/// 结束运行
/// </summary>
void Exit();
/// <summary>
/// 设置流程起点节点
/// </summary>
/// <param name="nodeGuid"></param>
void SetStartNode(string nodeGuid);
/// <summary>
/// 在两个节点之间创建连接关系
/// </summary>
/// <param name="fromNodeGuid">起始节点Guid</param>
/// <param name="toNodeGuid">目标节点Guid</param>
/// <param name="connectionType">连接类型</param>
void ConnectNode(string fromNodeGuid, string toNodeGuid, ConnectionType connectionType);
/// <summary>
/// 创建节点/区域/基础控件
/// </summary>
/// <param name="nodeBase">节点/区域/基础控件</param>
/// <param name="methodDetails">节点绑定的方法说明(</param>
void CreateNode(NodeControlType nodeBase, MethodDetails methodDetails = null);
/// <summary>
/// 移除两个节点之间的连接关系
/// </summary>
/// <param name="fromNodeGuid">起始节点</param>
/// <param name="toNodeGuid">目标节点</param>
/// <param name="connectionType">连接类型</param>
void RemoteConnect(string fromNodeGuid, string toNodeGuid, ConnectionType connectionType);
/// <summary>
/// 移除节点/区域/基础控件
/// </summary>
/// <param name="nodeGuid">待移除的节点Guid</param>
void RemoteNode(string nodeGuid);
}
}

83
Library/Base/NodeBase.cs Normal file
View File

@@ -0,0 +1,83 @@
using Serein.Library.Entity;
using Serein.Library.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Serein.Library.Base
{
public abstract class NodeBase
{
/// <summary>
/// 节点类型
/// </summary>
public abstract NodeControlType ControlType { get; set; }
/// <summary>
/// 方法描述对应DLL的方法
/// </summary>
public abstract MethodDetails MethodDetails { get; set; }
/// <summary>
/// 节点guid
/// </summary>
public abstract string Guid { get; set; }
/// <summary>
/// 显示名称
/// </summary>
public abstract string DisplayName { get; set; }
/// <summary>
/// 是否为起点控件
/// </summary>
public abstract bool IsStart { get; set; }
/// <summary>
/// 运行时的上一节点
/// </summary>
public abstract NodeBase PreviousNode { get; set; }
/// <summary>
/// 上一节点集合
/// </summary>
public abstract List<NodeBase> PreviousNodes { get; set; }
/// <summary>
/// 下一节点集合(真分支)
/// </summary>
public abstract List<NodeBase> SucceedBranch { get; set; }
/// <summary>
/// 下一节点集合(假分支)
/// </summary>
public abstract List<NodeBase> FailBranch { get; set; }
/// <summary>
/// 异常分支
/// </summary>
public abstract List<NodeBase> ErrorBranch { get; set; }
/// <summary>
/// 上游分支
/// </summary>
public abstract List<NodeBase> UpstreamBranch { get; set; }
/// <summary>
/// 当前执行状态(进入真分支还是假分支,异常分支在异常中确定)
/// </summary>
public abstract FlowStateType FlowState { get; set; }
/// <summary>
/// 运行时的异常信息(仅在 FlowState 为 Error 时存在对应值)
/// </summary>
public abstract Exception RuningException { get; set; }
/// <summary>
/// 当前传递数据(执行了节点对应的方法,才会存在值)
/// </summary>
public abstract object FlowData { get; set; }
}
}

View File

@@ -0,0 +1,110 @@
using Serein.Library.Api;
using Serein.Library.Entity;
using Serein.Library.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Serein.Library.Base
{
/// <summary>
/// 节点基类(数据):条件控件,动作控件,条件区域,动作区域
/// </summary>
public abstract partial class NodeModelBase : IDynamicFlowNode
{
public NodeControlType ControlType { get; set; }
/// <summary>
/// 方法描述对应DLL的方法
/// </summary>
public MethodDetails MethodDetails { get; set; }
/// <summary>
/// 节点guid
/// </summary>
public string Guid { get; set; }
/// <summary>
/// 显示名称
/// </summary>
public string DisplayName { get; set; }
/// <summary>
/// 是否为起点控件
/// </summary>
public bool IsStart { get; set; }
/// <summary>
/// 运行时的上一节点
/// </summary>
public NodeModelBase PreviousNode { get; set; }
/// <summary>
/// 上一节点集合
/// </summary>
public List<NodeModelBase> PreviousNodes { get; set; } = new List<NodeModelBase>();
/// <summary>
/// 下一节点集合(真分支)
/// </summary>
public List<NodeModelBase> SucceedBranch { get; set; } = new List<NodeModelBase>();
/// <summary>
/// 下一节点集合(假分支)
/// </summary>
public List<NodeModelBase> FailBranch { get; set; } = new List<NodeModelBase>();
/// <summary>
/// 异常分支
/// </summary>
public List<NodeModelBase> ErrorBranch { get; set; } = new List<NodeModelBase>();
/// <summary>
/// 上游分支
/// </summary>
public List<NodeModelBase> UpstreamBranch { get; set; } = new List<NodeModelBase>();
/// <summary>
/// 当前执行状态(进入真分支还是假分支,异常分支在异常中确定)
/// </summary>
public FlowStateType FlowState { get; set; } = FlowStateType.None;
/// <summary>
/// 运行时的异常信息(仅在 FlowState 为 Error 时存在对应值)
/// </summary>
public Exception RuningException { get; set; } = null;
/// <summary>
/// 当前传递数据(执行了节点对应的方法,才会存在值)
/// </summary>
public object FlowData { get; set; } = null;
public abstract Parameterdata[] GetParameterdatas();
public virtual NodeInfo ToInfo()
{
if (MethodDetails == null) return null;
var trueNodes = SucceedBranch.Select(item => item.Guid); // 真分支
var falseNodes = FailBranch.Select(item => item.Guid);// 假分支
var upstreamNodes = UpstreamBranch.Select(item => item.Guid);// 上游分支
var errorNodes = ErrorBranch.Select(item => item.Guid);// 异常分支
// 生成参数列表
Parameterdata[] parameterData = GetParameterdatas();
return new NodeInfo
{
Guid = Guid,
MethodName = MethodDetails?.MethodName,
Label = DisplayName ?? "",
Type = this.GetType().ToString(),
TrueNodes = trueNodes.ToArray(),
FalseNodes = falseNodes.ToArray(),
UpstreamNodes = upstreamNodes.ToArray(),
ParameterData = parameterData.ToArray(),
ErrorNodes = errorNodes.ToArray(),
};
}
}
}

View File

@@ -0,0 +1,480 @@
using Newtonsoft.Json;
using Serein.Library.Api;
using Serein.Library.Entity;
using Serein.Library.Enums;
using Serein.Library.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Serein.Library.Base
{
/// <summary>
/// 节点基类(数据):条件控件,动作控件,条件区域,动作区域
/// </summary>
public abstract partial class NodeModelBase : IDynamicFlowNode
{
/// <summary>
/// 执行节点对应的方法
/// </summary>
/// <param name="context">流程上下文</param>
/// <returns>节点传回数据对象</returns>
public virtual object Execute(IDynamicContext context)
{
MethodDetails md = MethodDetails;
object result = null;
var del = md.MethodDelegate;
try
{
if (md.ExplicitDatas.Length == 0)
{
if (md.ReturnType == typeof(void))
{
((Action<object>)del).Invoke(md.ActingInstance);
}
else
{
result = ((Func<object, object>)del).Invoke(md.ActingInstance);
}
}
else
{
object[] parameters = GetParameters(context, MethodDetails);
if (md.ReturnType == typeof(void))
{
((Action<object, object[]>)del).Invoke(md.ActingInstance, parameters);
}
else
{
result = ((Func<object, object[], object>)del).Invoke(md.ActingInstance, parameters);
}
}
return result;
}
catch (Exception ex)
{
FlowState = FlowStateType.Error;
RuningException = ex;
}
return result;
}
/// <summary>
/// 执行等待触发器的方法
/// </summary>
/// <param name="context"></param>
/// <returns>节点传回数据对象</returns>
/// <exception cref="RuningException"></exception>
public virtual async Task<object> ExecuteAsync(IDynamicContext context)
{
MethodDetails md = MethodDetails;
object result = null;
IFlipflopContext flipflopContext = null;
try
{
// 调用委托并获取结果
if (md.ExplicitDatas.Length == 0)
{
flipflopContext = await ((Func<object, Task<IFlipflopContext>>)md.MethodDelegate).Invoke(MethodDetails.ActingInstance);
}
else
{
object[] parameters = GetParameters(context, MethodDetails);
flipflopContext = await ((Func<object, object[], Task<IFlipflopContext>>)md.MethodDelegate).Invoke(MethodDetails.ActingInstance, parameters);
}
if (flipflopContext != null)
{
FlowState = flipflopContext.State;
if (flipflopContext.State == FlowStateType.Succeed)
{
result = flipflopContext.Data;
}
else
{
result = null;
}
}
}
catch (Exception ex)
{
FlowState = FlowStateType.Error;
RuningException = ex;
}
return result;
}
/// <summary>
/// 开始执行
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public async Task StartExecution(IDynamicContext context)
{
var cts = context.SereinIoc.GetOrInstantiate<CancellationTokenSource>();
Stack<NodeModelBase> stack = new Stack<NodeModelBase>();
stack.Push(this);
while (stack.Count > 0 && !cts.IsCancellationRequested) // 循环中直到栈为空才会退出循环
{
// 从栈中弹出一个节点作为当前节点进行处理
var currentNode = stack.Pop();
// 设置方法执行的对象
if (currentNode.MethodDetails != null)
{
if(currentNode.MethodDetails.ActingInstance == null)
{
currentNode.MethodDetails.ActingInstance = context.SereinIoc.GetOrInstantiate(MethodDetails.ActingInstanceType);
}
}
// 获取上游分支,首先执行一次
var upstreamNodes = currentNode.UpstreamBranch;
for (int i = upstreamNodes.Count - 1; i >= 0; i--)
{
upstreamNodes[i].PreviousNode = currentNode;
await upstreamNodes[i].StartExecution(context);
}
if (currentNode.MethodDetails != null && currentNode.MethodDetails.MethodDynamicType == NodeType.Flipflop)
{
// 触发器节点
currentNode.FlowData = await currentNode.ExecuteAsync(context);
}
else
{
// 动作节点
currentNode.FlowData = currentNode.Execute(context);
}
List<NodeModelBase> nextNodes = null ;
switch (currentNode.FlowState)
{
case FlowStateType.Succeed:
nextNodes = currentNode.SucceedBranch;
break;
case FlowStateType.Fail :
nextNodes = currentNode.FailBranch;
break;
case FlowStateType.Error :
nextNodes = currentNode.ErrorBranch;
break;
}
if(nextNodes != null)
{
for (int i = nextNodes.Count - 1; i >= 0; i--)
{
nextNodes[i].PreviousNode = currentNode;
stack.Push(nextNodes[i]);
}
}
/*var nextNodes = currentNode.FlowState switch
{
FlowStateType.Succeed => currentNode.SucceedBranch,
FlowStateType.Fail => currentNode.FailBranch,
FlowStateType.Error => currentNode.ErrorBranch,
_ => throw new Exception("非预期的枚举值")
};*/
// 将下一个节点集合中的所有节点逆序推入栈中
}
}
/// <summary>
/// 获取对应的参数数组
/// </summary>
public object[] GetParameters(IDynamicContext context, MethodDetails md)
{
// 用正确的大小初始化参数数组
var types = md.ExplicitDatas.Select(it => it.DataType).ToArray();
if (types.Length == 0)
{
return new object[] { md.ActingInstance };
}
object[] parameters = new object[types.Length];
for (int i = 0; i < types.Length; i++)
{
var mdEd = md.ExplicitDatas[i];
Type type = mdEd.DataType;
var f1 = PreviousNode?.FlowData?.GetType();
var f2 = mdEd.DataType;
if (type == typeof(IDynamicContext))
{
parameters[i] = context;
}
else if (type == typeof(MethodDetails))
{
parameters[i] = md;
}
else if (type == typeof(NodeModelBase))
{
parameters[i] = this;
}
else if (mdEd.IsExplicitData) // 显式参数
{
// 判断是否使用表达式解析
if (mdEd.DataValue[0] == '@')
{
var expResult = SerinExpressionEvaluator.Evaluate(mdEd.DataValue, PreviousNode?.FlowData, out bool isChange);
if (mdEd.DataType.IsEnum)
{
var enumValue = Enum.Parse(mdEd.DataType, mdEd.DataValue);
parameters[i] = enumValue;
}
else if (mdEd.ExplicitType == typeof(string))
{
parameters[i] = Convert.ChangeType(expResult, typeof(string));
}
else if (mdEd.ExplicitType == typeof(bool))
{
parameters[i] = Convert.ChangeType(expResult, typeof(bool));
}
else if (mdEd.ExplicitType == typeof(int))
{
parameters[i] = Convert.ChangeType(expResult, typeof(int));
}
else if (mdEd.ExplicitType == typeof(double))
{
parameters[i] = Convert.ChangeType(expResult, typeof(double));
}
else
{
parameters[i] = expResult;
//parameters[i] = ConvertValue(mdEd.DataValue, mdEd.ExplicitType);
}
}
else
{
if (mdEd.DataType.IsEnum)
{
var enumValue = Enum.Parse(mdEd.DataType, mdEd.DataValue);
parameters[i] = enumValue;
}
else if (mdEd.ExplicitType == typeof(string))
{
parameters[i] = mdEd.DataValue;
}
else if (mdEd.ExplicitType == typeof(bool))
{
parameters[i] = bool.Parse(mdEd.DataValue);
}
else if (mdEd.ExplicitType == typeof(int))
{
parameters[i] = int.Parse(mdEd.DataValue);
}
else if (mdEd.ExplicitType == typeof(double))
{
parameters[i] = double.Parse(mdEd.DataValue);
}
else
{
parameters[i] = "";
//parameters[i] = ConvertValue(mdEd.DataValue, mdEd.ExplicitType);
}
}
}
else if (f1 != null && f2 != null)
{
if (f2.IsAssignableFrom(f1) || f2.FullName.Equals(f1.FullName))
{
parameters[i] = PreviousNode?.FlowData;
}
}
else
{
var tmpParameter = PreviousNode?.FlowData?.ToString();
if (mdEd.DataType.IsEnum)
{
var enumValue = Enum.Parse(mdEd.DataType, tmpParameter);
parameters[i] = enumValue;
}
else if (mdEd.DataType == typeof(string))
{
parameters[i] = tmpParameter;
}
else if (mdEd.DataType == typeof(bool))
{
parameters[i] = bool.Parse(tmpParameter);
}
else if (mdEd.DataType == typeof(int))
{
parameters[i] = int.Parse(tmpParameter);
}
else if (mdEd.DataType == typeof(double))
{
parameters[i] = double.Parse(tmpParameter);
}
else
{
if (tmpParameter != null && mdEd.DataType != null)
{
parameters[i] = ConvertValue(tmpParameter, mdEd.DataType);
}
}
}
}
return parameters;
}
/// <summary>
/// json文本反序列化为对象
/// </summary>
/// <param name="value"></param>
/// <param name="targetType"></param>
/// <returns></returns>
private dynamic ConvertValue(string value, Type targetType)
{
try
{
if (!string.IsNullOrEmpty(value))
{
return JsonConvert.DeserializeObject(value, targetType);
}
else
{
return null;
}
}
catch (JsonReaderException ex)
{
Console.WriteLine(ex);
return value;
}
catch (JsonSerializationException ex)
{
// 如果无法转为对应的JSON对象
int startIndex = ex.Message.IndexOf("to type '") + "to type '".Length; // 查找类型信息开始的索引
int endIndex = ex.Message.IndexOf('\''); // 查找类型信息结束的索引
var typeInfo = ex.Message.Substring(startIndex,endIndex); // 提取出错类型信息,该怎么传出去?
Console.WriteLine("无法转为对应的JSON对象:" + typeInfo);
return null;
}
catch // (Exception ex)
{
return value;
}
}
#region ExecuteAsync调用方法
//public virtual async Task<object?> ExecuteAsync(DynamicContext context)
//{
// MethodDetails md = MethodDetails;
// object? result = null;
// if (DelegateCache.GlobalDicDelegates.TryGetValue(md.MethodName, out Delegate del))
// {
// if (md.ExplicitDatas.Length == 0)
// {
// if (md.ReturnType == typeof(void))
// {
// ((Action<object>)del).Invoke(md.ActingInstance);
// }
// else if (md.ReturnType == typeof(Task<FlipflopContext>))
// {
// // 调用委托并获取结果
// FlipflopContext flipflopContext = await ((Func<object, Task<FlipflopContext>>)del).Invoke(MethodDetails.ActingInstance);
// if (flipflopContext != null)
// {
// if (flipflopContext.State == FfState.Cancel)
// {
// throw new Exception("this async task is cancel.");
// }
// else
// {
// if (flipflopContext.State == FfState.Succeed)
// {
// CurrentState = true;
// result = flipflopContext.Data;
// }
// else
// {
// CurrentState = false;
// }
// }
// }
// }
// else
// {
// result = ((Func<object, object>)del).Invoke(md.ActingInstance);
// }
// }
// else
// {
// object?[]? parameters = GetParameters(context, MethodDetails);
// if (md.ReturnType == typeof(void))
// {
// ((Action<object, object[]>)del).Invoke(md.ActingInstance, parameters);
// }
// else if (md.ReturnType == typeof(Task<FlipflopContext>))
// {
// // 调用委托并获取结果
// FlipflopContext flipflopContext = await ((Func<object, object[], Task<FlipflopContext>>)del).Invoke(MethodDetails.ActingInstance, parameters);
// if (flipflopContext != null)
// {
// if (flipflopContext.State == FfState.Cancel)
// {
// throw new Exception("取消此异步");
// }
// else
// {
// CurrentState = flipflopContext.State == FfState.Succeed;
// result = flipflopContext.Data;
// }
// }
// }
// else
// {
// result = ((Func<object, object[], object>)del).Invoke(md.ActingInstance, parameters);
// }
// }
// context.SetFlowData(result);
// }
// return result;
//}
#endregion
}
}

View File

@@ -0,0 +1,69 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Serein.Library.Entity
{
/// <summary>
/// 参数
/// </summary>
public class ExplicitData
{
/// <summary>
/// 索引
/// </summary>
public int Index { get; set; }
/// <summary>
/// 是否为显式参数
/// </summary>
public bool IsExplicitData { get; set; }
/// <summary>
/// 显式类型
/// </summary>
public Type ExplicitType { get; set; }
/// <summary>
/// 显示类型编号>
/// </summary>
public string ExplicitTypeName { get; set; }
/// <summary>
/// 方法需要的类型
/// </summary>
public Type DataType { get; set; }
/// <summary>
/// 方法入参参数名称
/// </summary>
public string ParameterName { get; set; }
/// <summary>
/// 入参值在UI上输入的文本内容
/// </summary>
public string DataValue { get; set; }
public string[] Items { get; set; }
public ExplicitData Clone() => new ExplicitData()
{
Index = Index,
IsExplicitData = IsExplicitData,
ExplicitType = ExplicitType,
DataType = DataType,
ParameterName = ParameterName,
ExplicitTypeName = ExplicitTypeName,
DataValue = string.IsNullOrEmpty(DataValue) ? string.Empty : DataValue,
Items = Items.Select(it => it).ToArray(),
};
}
}

View File

@@ -0,0 +1,183 @@
using Serein.Library.Api;
using Serein.Library.Enums;
using System;
using System.Linq;
namespace Serein.Library.Entity
{
public class MethodDetails
{
/// <summary>
/// 拷贝
/// </summary>
/// <returns></returns>
public MethodDetails Clone()
{
return new MethodDetails
{
ActingInstance = ActingInstance,
ActingInstanceType = ActingInstanceType,
MethodDelegate = MethodDelegate,
MethodDynamicType = MethodDynamicType,
MethodGuid = Guid.NewGuid().ToString(),
MethodTips = MethodTips,
ReturnType = ReturnType,
MethodName = MethodName,
MethodLockName = MethodLockName,
IsNetFramework = IsNetFramework,
ExplicitDatas = ExplicitDatas.Select(it => it.Clone()).ToArray(),
};
}
/// <summary>
/// 作用实例
/// </summary>
public Type ActingInstanceType { get; set; }
/// <summary>
/// 作用实例
/// </summary>
public object ActingInstance { get; set; }
/// <summary>
/// 方法GUID
/// </summary>
public string MethodGuid { get; set; }
/// <summary>
/// 方法名称
/// </summary>
public string MethodName { get; set; }
/// <summary>
/// 方法委托
/// </summary>
public Delegate MethodDelegate { get; set; }
/// <summary>
/// 节点类型
/// </summary>
public NodeType MethodDynamicType { get; set; }
/// <summary>
/// 锁名称
/// </summary>
public string MethodLockName { get; set; }
/// <summary>
/// 方法说明
/// </summary>
public string MethodTips { get; set; }
/// <summary>
/// 参数内容
/// </summary>
public ExplicitData[] ExplicitDatas { get; set; }
/// <summary>
/// 出参类型
/// </summary>
public Type ReturnType { get; set; }
public bool IsNetFramework { get; set; }
//public bool IsCanConnect(Type returnType)
//{
// if (ExplicitDatas.Length == 0)
// {
// // 目标不需要传参,可以舍弃结果?
// return true;
// }
// var types = ExplicitDatas.Select(it => it.DataType).ToArray();
// // 检查返回类型是否是元组类型
// if (returnType.IsGenericType && IsValueTuple(returnType))
// {
// return CompareGenericArguments(returnType, types);
// }
// else
// {
// int index = 0;
// if (types[index] == typeof(DynamicContext))
// {
// index++;
// if (types.Length == 1)
// {
// return true;
// }
// }
// // 被连接节点检查自己需要的参数类型,与发起连接的节点比较返回值类型
// if (returnType == types[index])
// {
// return true;
// }
// }
// return false;
//}
///// <summary>
///// 检查元组类型
///// </summary>
///// <param name="type"></param>
///// <returns></returns>
//private bool IsValueTuple(Type type)
//{
// if (!type.IsGenericType) return false;
// var genericTypeDef = type.GetGenericTypeDefinition();
// return genericTypeDef == typeof(ValueTuple<>) ||
// genericTypeDef == typeof(ValueTuple<,>) ||
// genericTypeDef == typeof(ValueTuple<,,>) ||
// genericTypeDef == typeof(ValueTuple<,,,>) ||
// genericTypeDef == typeof(ValueTuple<,,,,>) ||
// genericTypeDef == typeof(ValueTuple<,,,,,>) ||
// genericTypeDef == typeof(ValueTuple<,,,,,,>) ||
// genericTypeDef == typeof(ValueTuple<,,,,,,,>);
//}
//private bool CompareGenericArguments(Type returnType, Type[] parameterTypes)
//{
// var genericArguments = returnType.GetGenericArguments();
// var length = parameterTypes.Length;
// for (int i = 0; i < genericArguments.Length; i++)
// {
// if (i >= length) return false;
// if (IsValueTuple(genericArguments[i]))
// {
// // 如果当前参数也是 ValueTuple递归检查嵌套的泛型参数
// if (!CompareGenericArguments(genericArguments[i], parameterTypes.Skip(i).ToArray()))
// {
// return false;
// }
// }
// else if (genericArguments[i] != parameterTypes[i])
// {
// return false;
// }
// }
// return true;
//}
}
}

View File

@@ -0,0 +1,202 @@
using Serein.Library.Api;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Serein.Library.Entity
{
/// <summary>
/// 输出文件
/// </summary>
public class SereinOutputFileData
{
/// <summary>
/// 基础
/// </summary>
public Basic Basic { get; set; }
/// <summary>
/// 依赖的DLL
/// </summary>
public Library[] Librarys { get; set; }
/// <summary>
/// 起始节点GUID
/// </summary>
public string StartNode { get; set; }
/// <summary>
/// 节点集合
/// </summary>
public NodeInfo[] Nodes { get; set; }
///// <summary>
///// 区域集合
///// </summary>
//public Region[] Regions { get; set; }
}
/// <summary>
/// 基础
/// </summary>
public class Basic
{
/// <summary>
/// 画布
/// </summary>
public FlowCanvas canvas { get; set; }
/// <summary>
/// 版本
/// </summary>
public string versions { get; set; }
// 预览位置
// 缩放比例
}
/// <summary>
/// 画布
/// </summary>
public class FlowCanvas
{
/// <summary>
/// 宽度
/// </summary>
public float width { get; set; }
/// <summary>
/// 高度
/// </summary>
public float lenght { get; set; }
}
/// <summary>
/// DLL
/// </summary>
public class Library
{
/// <summary>
/// DLL名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 路径
/// </summary>
public string Path { get; set; }
}
/// <summary>
/// 节点
/// </summary>
public class NodeInfo
{
/// <summary>
/// GUID
/// </summary>
public string Guid { get; set; }
/// <summary>
/// 名称
/// </summary>
public string MethodName { get; set; }
/// <summary>
/// 显示标签
/// </summary>
public string Label { get; set; }
/// <summary>
/// 类型
/// </summary>
public string Type { get; set; }
/// <summary>
/// 真分支节点GUID
/// </summary>
public string[] TrueNodes { get; set; }
/// <summary>
/// 假分支节点
/// </summary>
public string[] FalseNodes { get; set; }
/// <summary>
/// 上游分支
/// </summary>
public string[] UpstreamNodes { get; set; }
/// <summary>
/// 异常分支
/// </summary>
public string[] ErrorNodes { get; set; }
/// <summary>
/// 参数
/// </summary>
public Parameterdata[] ParameterData { get; set; }
/// <summary>
/// 如果是区域控件,则会存在子项。
/// </summary>
public NodeInfo[] ChildNodes { get; set; }
/// <summary>
/// 于画布中的位置
/// </summary>
public Position Position { get; set; }
/// <summary>
/// 是否选中
/// </summary>
public bool IsSelect { get; set; }
}
public class Parameterdata
{
public bool state { get; set; }
public string value { get; set; }
public string expression { get; set; }
}
/// <summary>
/// 节点于画布中的位置
/// </summary>
public class Position
{
public float X { get; set; }
public float Y { get; set; }
}
/// <summary>
/// 区域
/// </summary>
public class Region
{
public string guid { get; set; }
public NodeInfo[] ChildNodes { get; set; }
}
}

View File

@@ -0,0 +1,28 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace Serein.Library.Enums
{
public enum ConnectionType
{
/// <summary>
/// 真分支
/// </summary>
IsSucceed,
/// <summary>
/// 假分支
/// </summary>
IsFail,
/// <summary>
/// 异常发生分支
/// </summary>
IsError,
/// <summary>
/// 上游分支(执行当前节点前会执行一次上游分支)
/// </summary>
Upstream,
}
}

View File

@@ -9,6 +9,10 @@ namespace Serein.Library.Enums
public enum FlowStateType
{
/// <summary>
/// 待执行
/// </summary>
None,
/// <summary>
/// 成功(方法成功执行)
/// </summary>

View File

@@ -9,15 +9,15 @@ namespace Serein.Library.Enums
public enum NodeType
{
/// <summary>
/// 初始化
/// 初始化(事件,不生成节点)
/// </summary>
Init,
/// <summary>
/// 开始载入
/// 开始载入(事件,不生成节点)
/// </summary>
Loading,
/// <summary>
/// 结束
/// 结束(事件,不生成节点)
/// </summary>
Exit,
@@ -26,13 +26,39 @@ namespace Serein.Library.Enums
/// </summary>
Flipflop,
/// <summary>
/// 条件节点
/// 条件
/// </summary>
Condition,
/// <summary>
/// 动作节点
/// 动作
/// </summary>
Action,
}
public enum NodeControlType
{
None,
/// <summary>
/// 动作节点
/// </summary>
Action,
/// <summary>
/// 触发器节点
/// </summary>
Flipflop,
/// <summary>
/// 表达式操作节点
/// </summary>
ExpOp,
/// <summary>
/// 表达式操作节点
/// </summary>
ExpCondition,
/// <summary>
/// 条件节点区域
/// </summary>
ConditionRegion,
}
}

View File

@@ -24,6 +24,8 @@ namespace Serein.Library.Attributes
public bool Scan { get; set; } = true;
}
/// <summary>
/// 标记一个方法是什么类型加载dll后用来拖拽到画布中
/// </summary>
@@ -40,10 +42,14 @@ namespace Serein.Library.Attributes
MethodTips = methodTips;
LockName = lockName;
}
public bool Scan { get; set; }
public string MethodTips { get; }
public NodeType MethodDynamicType { get; }
public string LockName { get; }
public bool Scan;
public string MethodTips;
public NodeType MethodDynamicType;
/// <summary>
/// 推荐触发器手动设置返回类型
/// </summary>
public Type ReturnType;
public string LockName;
}
}

View File

@@ -4,4 +4,24 @@
<TargetFrameworks>netstandard2.0;net461</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<Compile Remove="Utils\SerinExpression\**" />
<EmbeddedResource Remove="Utils\SerinExpression\**" />
<None Remove="Utils\SerinExpression\**" />
</ItemGroup>
<ItemGroup>
<Compile Remove="Base\NodeBase.cs" />
<Compile Remove="Base\NodeModelBaseData.cs" />
<Compile Remove="Base\NodeModelBaseFunc.cs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>
<ItemGroup>
<Folder Include="Base\" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,338 @@
using System;
using System.Reflection;
namespace Serein.NodeFlow.Tool.SerinExpression
{
/// <summary>
/// 条件解析抽象类
/// </summary>
public abstract class ConditionResolver
{
public abstract bool Evaluate(object obj);
}
public class PassConditionResolver : ConditionResolver
{
public Operator Op { get; set; }
public override bool Evaluate(object obj)
{
return Op switch
{
Operator.Pass => true,
Operator.NotPass => false,
_ => throw new NotSupportedException("不支持的条件类型")
};
}
public enum Operator
{
Pass,
NotPass,
}
}
public class ValueTypeConditionResolver<T> : ConditionResolver where T : struct, IComparable<T>
{
public enum Operator
{
/// <summary>
/// 不进行任何操作
/// </summary>
Node,
/// <summary>
/// 大于
/// </summary>
GreaterThan,
/// <summary>
/// 小于
/// </summary>
LessThan,
/// <summary>
/// 等于
/// </summary>
Equal,
/// <summary>
/// 大于或等于
/// </summary>
GreaterThanOrEqual,
/// <summary>
/// 小于或等于
/// </summary>
LessThanOrEqual,
/// <summary>
/// 在两者之间
/// </summary>
InRange,
/// <summary>
/// 不在两者之间
/// </summary>
OutOfRange
}
public Operator Op { get; set; }
public T Value { get; set; }
public T RangeStart { get; set; }
public T RangeEnd { get; set; }
public string ArithmeticExpression { get; set; }
public override bool Evaluate(object obj)
{
if (obj is T typedObj)
{
double numericValue = Convert.ToDouble(typedObj);
if (!string.IsNullOrEmpty(ArithmeticExpression))
{
numericValue = SerinArithmeticExpressionEvaluator.Evaluate(ArithmeticExpression, numericValue);
}
T evaluatedValue = (T)Convert.ChangeType(numericValue, typeof(T));
return Op switch
{
Operator.GreaterThan => evaluatedValue.CompareTo(Value) > 0,
Operator.LessThan => evaluatedValue.CompareTo(Value) < 0,
Operator.Equal => evaluatedValue.CompareTo(Value) == 0,
Operator.GreaterThanOrEqual => evaluatedValue.CompareTo(Value) >= 0,
Operator.LessThanOrEqual => evaluatedValue.CompareTo(Value) <= 0,
Operator.InRange => evaluatedValue.CompareTo(RangeStart) >= 0 && evaluatedValue.CompareTo(RangeEnd) <= 0,
Operator.OutOfRange => evaluatedValue.CompareTo(RangeStart) < 0 || evaluatedValue.CompareTo(RangeEnd) > 0,
_ => throw new NotSupportedException("不支持的条件类型")
};
/* switch (Op)
{
case Operator.GreaterThan:
return evaluatedValue.CompareTo(Value) > 0;
case Operator.LessThan:
return evaluatedValue.CompareTo(Value) < 0;
case Operator.Equal:
return evaluatedValue.CompareTo(Value) == 0;
case Operator.GreaterThanOrEqual:
return evaluatedValue.CompareTo(Value) >= 0;
case Operator.LessThanOrEqual:
return evaluatedValue.CompareTo(Value) <= 0;
case Operator.InRange:
return evaluatedValue.CompareTo(RangeStart) >= 0 && evaluatedValue.CompareTo(RangeEnd) <= 0;
case Operator.OutOfRange:
return evaluatedValue.CompareTo(RangeStart) < 0 || evaluatedValue.CompareTo(RangeEnd) > 0;
}*/
}
return false;
}
}
public class BoolConditionResolver : ConditionResolver
{
public enum Operator
{
/// <summary>
/// 是
/// </summary>
Is
}
public Operator Op { get; set; }
public bool Value { get; set; }
public override bool Evaluate(object obj)
{
if (obj is bool boolObj)
{
return boolObj == Value;
/*switch (Op)
{
case Operator.Is:
return boolObj == Value;
}*/
}
return false;
}
}
public class StringConditionResolver : ConditionResolver
{
public enum Operator
{
/// <summary>
/// 出现过
/// </summary>
Contains,
/// <summary>
/// 没有出现过
/// </summary>
DoesNotContain,
/// <summary>
/// 相等
/// </summary>
Equal,
/// <summary>
/// 不相等
/// </summary>
NotEqual,
/// <summary>
/// 起始字符串等于
/// </summary>
StartsWith,
/// <summary>
/// 结束字符串等于
/// </summary>
EndsWith
}
public Operator Op { get; set; }
public string Value { get; set; }
public override bool Evaluate(object obj)
{
if (obj is string strObj)
{
return Op switch
{
Operator.Contains => strObj.Contains(Value),
Operator.DoesNotContain => !strObj.Contains(Value),
Operator.Equal => strObj == Value,
Operator.NotEqual => strObj != Value,
Operator.StartsWith => strObj.StartsWith(Value),
Operator.EndsWith => strObj.EndsWith(Value),
_ => throw new NotSupportedException("不支持的条件类型"),
};
/* switch (Op)
{
case Operator.Contains:
return strObj.Contains(Value);
case Operator.DoesNotContain:
return !strObj.Contains(Value);
case Operator.Equal:
return strObj == Value;
case Operator.NotEqual:
return strObj != Value;
case Operator.StartsWith:
return strObj.StartsWith(Value);
case Operator.EndsWith:
return strObj.EndsWith(Value);
}*/
}
return false;
}
}
public class MemberConditionResolver<T> : ConditionResolver where T : struct, IComparable<T>
{
//public string MemberPath { get; set; }
public ValueTypeConditionResolver<T>.Operator Op { get; set; }
public object? TargetObj { get; set; }
public T Value { get; set; }
public string ArithmeticExpression { get; set; }
public override bool Evaluate(object? obj)
{
//object? memberValue = GetMemberValue(obj, MemberPath);
if (TargetObj is T typedObj)
{
return new ValueTypeConditionResolver<T>
{
Op = Op,
Value = Value,
ArithmeticExpression = ArithmeticExpression,
}.Evaluate(typedObj);
}
return false;
}
//private object? GetMemberValue(object? obj, string memberPath)
//{
// string[] members = memberPath[1..].Split('.');
// foreach (var member in members)
// {
// if (obj == null) return null;
// Type type = obj.GetType();
// PropertyInfo? propertyInfo = type.GetProperty(member);
// FieldInfo? fieldInfo = type.GetField(member);
// if (propertyInfo != null)
// obj = propertyInfo.GetValue(obj);
// else if (fieldInfo != null)
// obj = fieldInfo.GetValue(obj);
// else
// throw new ArgumentException($"Member {member} not found in type {type.FullName}");
// }
// return obj;
//}
}
public class MemberStringConditionResolver : ConditionResolver
{
public string MemberPath { get; set; }
public StringConditionResolver.Operator Op { get; set; }
public string Value { get; set; }
public override bool Evaluate(object obj)
{
object memberValue = GetMemberValue(obj, MemberPath);
if (memberValue is string strObj)
{
return new StringConditionResolver
{
Op = Op,
Value = Value
}.Evaluate(strObj);
}
return false;
}
private object GetMemberValue(object? obj, string memberPath)
{
string[] members = memberPath[1..].Split('.');
foreach (var member in members)
{
if (obj == null) return null;
Type type = obj.GetType();
PropertyInfo? propertyInfo = type.GetProperty(member);
FieldInfo? fieldInfo = type.GetField(member);
if (propertyInfo != null)
obj = propertyInfo.GetValue(obj);
else if (fieldInfo != null)
obj = fieldInfo.GetValue(obj);
else
throw new ArgumentException($"Member {member} not found in type {type.FullName}");
}
return obj;
}
private static string GetArithmeticExpression(string part)
{
int startIndex = part.IndexOf('[');
int endIndex = part.IndexOf(']');
if (startIndex >= 0 && endIndex > startIndex)
{
return part.Substring(startIndex + 1, endIndex - startIndex - 1);
}
return null;
}
}
}

View File

@@ -0,0 +1,342 @@
using System;
using System.Globalization;
using System.Reflection;
namespace Serein.NodeFlow.Tool.SerinExpression
{
public class SerinConditionParser
{
public static bool To<T>(T data, string expression)
{
try
{
return ConditionParse(data, expression).Evaluate(data);
}
catch (Exception ex)
{
Console.WriteLine(ex);
throw;
}
}
public static ConditionResolver ConditionParse(object data, string expression)
{
if (expression.StartsWith('.')) // 表达式前缀属于从上一个节点数据对象获取成员值
{
return ParseObjectExpression(data, expression);
}
else
{
return ParseSimpleExpression(data, expression);
}
//bool ContainsArithmeticOperators(string expression)
//{
// return expression.Contains('+') || expression.Contains('-') || expression.Contains('*') || expression.Contains('/');
//}
}
/// <summary>
/// 获取计算表达式的部分
/// </summary>
/// <param name="part"></param>
/// <returns></returns>
private static string GetArithmeticExpression(string part)
{
int startIndex = part.IndexOf('[');
int endIndex = part.IndexOf(']');
if (startIndex >= 0 && endIndex > startIndex)
{
return part.Substring(startIndex + 1, endIndex - startIndex - 1);
}
return null;
}
/// <summary>
/// 获取对象指定名称的成员
/// </summary>
private static object? GetMemberValue(object? obj, string memberPath)
{
string[] members = memberPath[1..].Split('.');
foreach (var member in members)
{
if (obj == null) return null;
Type type = obj.GetType();
PropertyInfo? propertyInfo = type.GetProperty(member);
FieldInfo? fieldInfo = type.GetField(member);
if (propertyInfo != null)
obj = propertyInfo.GetValue(obj);
else if (fieldInfo != null)
obj = fieldInfo.GetValue(obj);
else
throw new ArgumentException($"Member {member} not found in type {type.FullName}");
}
return obj;
}
/// <summary>
/// 解析对象表达式
/// </summary>
private static ConditionResolver ParseObjectExpression(object data, string expression)
{
var parts = expression.Split(' ');
string operatorStr = parts[0];
string valueStr = string.Join(' ', parts, 1, parts.Length - 1);
int typeStartIndex = expression.IndexOf('<');
int typeEndIndex = expression.IndexOf('>');
string memberPath;
Type type;
object? targetObj;
if (typeStartIndex + typeStartIndex == -2)
{
memberPath = operatorStr;
targetObj = GetMemberValue(data, operatorStr);
type = targetObj.GetType();
operatorStr = parts[1].ToLower();
valueStr = string.Join(' ', parts.Skip(2));
}
else
{
if (typeStartIndex >= typeEndIndex)
{
throw new ArgumentException("无效的表达式格式");
}
memberPath = expression.Substring(0, typeStartIndex).Trim();
string typeStr = expression.Substring(typeStartIndex + 1, typeEndIndex - typeStartIndex - 1).Trim().ToLower();
parts = expression.Substring(typeEndIndex + 1).Trim().Split(' ');
if (parts.Length == 3)
{
operatorStr = parts[1].ToLower();
valueStr = string.Join(' ', parts.Skip(2));
}
else
{
operatorStr = parts[0].ToLower();
valueStr = string.Join(' ', parts.Skip(1));
}
targetObj = GetMemberValue(data, memberPath);
Type? tempType = typeStr switch
{
"int" => typeof(int),
"double" => typeof(double),
"bool" => typeof(bool),
"string" => typeof(string),
_ => Type.GetType(typeStr)
};
type = tempType ?? throw new ArgumentException("对象表达式无效的类型声明");
}
if (type == typeof(int))
{
int value = int.Parse(valueStr, CultureInfo.InvariantCulture);
return new MemberConditionResolver<int>
{
TargetObj = targetObj,
//MemberPath = memberPath,
Op = ParseValueTypeOperator<int>(operatorStr),
Value = value,
ArithmeticExpression = GetArithmeticExpression(parts[0])
};
}
else if (type == typeof(double))
{
double value = double.Parse(valueStr, CultureInfo.InvariantCulture);
return new MemberConditionResolver<double>
{
//MemberPath = memberPath,
TargetObj = targetObj,
Op = ParseValueTypeOperator<double>(operatorStr),
Value = value,
ArithmeticExpression = GetArithmeticExpression(parts[0])
};
}
else if (type == typeof(bool))
{
return new MemberConditionResolver<bool>
{
//MemberPath = memberPath,
TargetObj = targetObj,
Op = (ValueTypeConditionResolver<bool>.Operator)ParseBoolOperator(operatorStr)
};
}
else if (type == typeof(string))
{
return new MemberStringConditionResolver
{
MemberPath = memberPath,
Op = ParseStringOperator(operatorStr),
Value = valueStr
};
}
throw new NotSupportedException($"Type {type} is not supported.");
}
private static ConditionResolver ParseSimpleExpression(object data, string expression)
{
if ("pass".Equals(expression.ToLower()))
{
return new PassConditionResolver
{
Op = PassConditionResolver.Operator.Pass,
};
}
else
{
if ("not pass".Equals(expression.ToLower()))
{
return new PassConditionResolver
{
Op = PassConditionResolver.Operator.NotPass,
};
}
if ("!pass".Equals(expression.ToLower()))
{
return new PassConditionResolver
{
Op = PassConditionResolver.Operator.NotPass,
};
}
}
var parts = expression.Split(' ');
if (parts.Length < 2)
throw new ArgumentException("无效的表达式格式。");
//string typeStr = parts[0];
string operatorStr = parts[0];
string valueStr = string.Join(' ', parts, 1, parts.Length - 1);
Type type = data.GetType();//Type.GetType(typeStr);
if (type == typeof(int))
{
var op = ParseValueTypeOperator<int>(operatorStr);
if (op == ValueTypeConditionResolver<int>.Operator.InRange || op == ValueTypeConditionResolver<int>.Operator.OutOfRange)
{
var temp = valueStr.Split('-');
if (temp.Length < 2)
throw new ArgumentException($"范围无效:{valueStr}。");
int rangeStart = int.Parse(temp[0], CultureInfo.InvariantCulture);
int rangeEnd = int.Parse(temp[1], CultureInfo.InvariantCulture);
return new ValueTypeConditionResolver<int>
{
Op = op,
RangeStart = rangeStart,
RangeEnd = rangeEnd,
ArithmeticExpression = GetArithmeticExpression(parts[0]),
};
}
else
{
int value = int.Parse(valueStr, CultureInfo.InvariantCulture);
return new ValueTypeConditionResolver<int>
{
Op = op,
Value = value,
ArithmeticExpression = GetArithmeticExpression(parts[0])
};
}
}
else if (type == typeof(double))
{
double value = double.Parse(valueStr, CultureInfo.InvariantCulture);
return new ValueTypeConditionResolver<double>
{
Op = ParseValueTypeOperator<double>(operatorStr),
Value = value,
ArithmeticExpression = GetArithmeticExpression(parts[0])
};
}
else if (type == typeof(bool))
{
bool value = bool.Parse(valueStr);
return new BoolConditionResolver
{
Op = ParseBoolOperator(operatorStr),
Value = value,
};
}
else if (type == typeof(string))
{
return new StringConditionResolver
{
Op = ParseStringOperator(operatorStr),
Value = valueStr
};
}
throw new NotSupportedException($"Type {type} is not supported.");
}
private static ValueTypeConditionResolver<T>.Operator ParseValueTypeOperator<T>(string operatorStr) where T : struct, IComparable<T>
{
return operatorStr switch
{
">" => ValueTypeConditionResolver<T>.Operator.GreaterThan,
"<" => ValueTypeConditionResolver<T>.Operator.LessThan,
"=" => ValueTypeConditionResolver<T>.Operator.Equal,
"==" => ValueTypeConditionResolver<T>.Operator.Equal,
">=" => ValueTypeConditionResolver<T>.Operator.GreaterThanOrEqual,
"≥" => ValueTypeConditionResolver<T>.Operator.GreaterThanOrEqual,
"<=" => ValueTypeConditionResolver<T>.Operator.LessThanOrEqual,
"≤" => ValueTypeConditionResolver<T>.Operator.LessThanOrEqual,
"equals" => ValueTypeConditionResolver<T>.Operator.Equal,
"in" => ValueTypeConditionResolver<T>.Operator.InRange,
"!in" => ValueTypeConditionResolver<T>.Operator.OutOfRange,
_ => throw new ArgumentException($"Invalid operator {operatorStr} for value type.")
};
}
private static BoolConditionResolver.Operator ParseBoolOperator(string operatorStr)
{
return operatorStr switch
{
"is" => BoolConditionResolver.Operator.Is,
"==" => BoolConditionResolver.Operator.Is,
"equals" => BoolConditionResolver.Operator.Is,
//"isFalse" => BoolConditionNode.Operator.IsFalse,
_ => throw new ArgumentException($"Invalid operator {operatorStr} for bool type.")
};
}
private static StringConditionResolver.Operator ParseStringOperator(string operatorStr)
{
return operatorStr switch
{
"c" => StringConditionResolver.Operator.Contains,
"nc" => StringConditionResolver.Operator.DoesNotContain,
"sw" => StringConditionResolver.Operator.StartsWith,
"ew" => StringConditionResolver.Operator.EndsWith,
"contains" => StringConditionResolver.Operator.Contains,
"doesNotContain" => StringConditionResolver.Operator.DoesNotContain,
"equals" => StringConditionResolver.Operator.Equal,
"==" => StringConditionResolver.Operator.Equal,
"notEquals" => StringConditionResolver.Operator.NotEqual,
"!=" => StringConditionResolver.Operator.NotEqual,
"startsWith" => StringConditionResolver.Operator.StartsWith,
"endsWith" => StringConditionResolver.Operator.EndsWith,
_ => throw new ArgumentException($"Invalid operator {operatorStr} for string type.")
};
}
}
}

View File

@@ -0,0 +1,216 @@
using System.Data;
namespace Serein.NodeFlow.Tool.SerinExpression
{
public class SerinArithmeticExpressionEvaluator
{
private static readonly DataTable table = new DataTable();
public static double Evaluate(string expression, double inputValue)
{
// 替换占位符@为输入值
expression = expression.Replace("@", inputValue.ToString());
try
{
// 使用 DataTable.Compute 方法计算表达式
var result = table.Compute(expression, string.Empty);
return Convert.ToDouble(result);
}
catch
{
throw new ArgumentException("Invalid arithmetic expression.");
}
}
}
public class SerinExpressionEvaluator
{
/// <summary>
///
/// </summary>
/// <param name="expression">表达式</param>
/// <param name="targetObJ">操作对象</param>
/// <param name="isChange">是否改变了对象get语法</param>
/// <returns></returns>
/// <exception cref="ArgumentException"></exception>
/// <exception cref="NotSupportedException"></exception>
public static object Evaluate(string expression, object targetObJ, out bool isChange)
{
var parts = expression.Split([' '], 2);
if (parts.Length != 2)
{
throw new ArgumentException("Invalid expression format.");
}
var operation = parts[0].ToLower();
var operand = parts[1][0] == '.' ? parts[1][1..] : parts[1];
var result = operation switch
{
"@num" => ComputedNumber(targetObJ, operand),
"@call" => InvokeMethod(targetObJ, operand),
"@get" => GetMember(targetObJ, operand),
"@set" => SetMember(targetObJ, operand),
_ => throw new NotSupportedException($"Operation {operation} is not supported.")
};
isChange = operation switch
{
"@num" => true,
"@call" => true,
"@get" => true,
"@set" => false,
_ => throw new NotSupportedException($"Operation {operation} is not supported.")
};
return result;
}
private static readonly char[] separator = ['(', ')'];
private static readonly char[] separatorArray = [','];
private static object InvokeMethod(object target, string methodCall)
{
var methodParts = methodCall.Split(separator, StringSplitOptions.RemoveEmptyEntries);
if (methodParts.Length != 2)
{
throw new ArgumentException("Invalid method call format.");
}
var methodName = methodParts[0];
var parameterList = methodParts[1];
var parameters = parameterList.Split(separatorArray, StringSplitOptions.RemoveEmptyEntries)
.Select(p => p.Trim())
.ToArray();
var method = target.GetType().GetMethod(methodName);
if (method == null)
{
throw new ArgumentException($"Method {methodName} not found on target.");
}
var parameterValues = method.GetParameters()
.Select((p, index) => Convert.ChangeType(parameters[index], p.ParameterType))
.ToArray();
return method.Invoke(target, parameterValues);
}
private static object GetMember(object target, string memberPath)
{
var members = memberPath.Split('.');
foreach (var member in members)
{
if (target == null) return null;
var property = target.GetType().GetProperty(member);
if (property != null)
{
target = property.GetValue(target);
}
else
{
var field = target.GetType().GetField(member);
if (field != null)
{
target = field.GetValue(target);
}
else
{
throw new ArgumentException($"Member {member} not found on target.");
}
}
}
return target;
}
private static object SetMember(object target, string assignment)
{
var parts = assignment.Split(new[] { '=' }, 2);
if (parts.Length != 2)
{
throw new ArgumentException("Invalid assignment format.");
}
var memberPath = parts[0].Trim();
var value = parts[1].Trim();
var members = memberPath.Split('.');
for (int i = 0; i < members.Length - 1; i++)
{
var member = members[i];
var property = target.GetType().GetProperty(member);
if (property != null)
{
target = property.GetValue(target);
}
else
{
var field = target.GetType().GetField(member);
if (field != null)
{
target = field.GetValue(target);
}
else
{
throw new ArgumentException($"Member {member} not found on target.");
}
}
}
var lastMember = members.Last();
var lastProperty = target.GetType().GetProperty(lastMember);
if (lastProperty != null)
{
var convertedValue = Convert.ChangeType(value, lastProperty.PropertyType);
lastProperty.SetValue(target, convertedValue);
}
else
{
var lastField = target.GetType().GetField(lastMember);
if (lastField != null)
{
var convertedValue = Convert.ChangeType(value, lastField.FieldType);
lastField.SetValue(target, convertedValue);
}
else
{
throw new ArgumentException($"Member {lastMember} not found on target.");
}
}
return target;
}
private static double ComputedNumber(object value, string expression)
{
double numericValue = Convert.ToDouble(value);
if (!string.IsNullOrEmpty(expression))
{
numericValue = SerinArithmeticExpressionEvaluator.Evaluate(expression, numericValue);
}
return numericValue;
}
}
}

View File

@@ -0,0 +1,9 @@
using System;
namespace Serein.Library.Utils
{
//public abstract class SerinExpressionEvaluator
//{
// public abstract string Evaluate(string expression ,object obj , out bool isChange);
//}
}

View File

@@ -136,7 +136,7 @@ namespace MyDll
#region
[NodeAction(NodeType.Flipflop, "等待信号触发")]
[NodeAction(NodeType.Flipflop, "等待信号触发",ReturnType = typeof(int))]
public async Task<IFlipflopContext> WaitTask(SignalType triggerType = SignalType.1)
{
/*if (!Enum.TryParse(triggerValue, out SignalType triggerType) && Enum.IsDefined(typeof(SignalType), triggerType))

View File

@@ -0,0 +1,188 @@
using Newtonsoft.Json;
using Serein.Library.Api;
using Serein.Library.Entity;
using Serein.Library.Enums;
using Serein.NodeFlow.Model;
using Serein.NodeFlow.Tool.SerinExpression;
using System.Xml.Linq;
namespace Serein.NodeFlow.Base
{
/// <summary>
/// 节点基类(数据):条件控件,动作控件,条件区域,动作区域
/// </summary>
public abstract partial class NodeModelBase :IDynamicFlowNode
{
public NodeModelBase()
{
ConnectionType[] ct = [ConnectionType.IsSucceed,
ConnectionType.IsFail,
ConnectionType.IsError,
ConnectionType.Upstream];
PreviousNodes = [];
SuccessorNodes = [];
foreach (ConnectionType ctType in ct)
{
PreviousNodes[ctType] = [];
SuccessorNodes[ctType] = [];
}
}
/// <summary>
/// 节点对应的控件类型
/// </summary>
public NodeControlType ControlType { get; set; }
/// <summary>
/// 方法描述对应DLL的方法
/// </summary>
public MethodDetails MethodDetails { get; set; }
/// <summary>
/// 节点guid
/// </summary>
public string Guid { get; set; }
/// <summary>
/// 显示名称
/// </summary>
public string DisplayName { get; set; }
/// <summary>
/// 是否为起点控件
/// </summary>
public bool IsStart { get; set; }
/// <summary>
/// 运行时的上一节点
/// </summary>
public NodeModelBase? PreviousNode { get; set; }
/// <summary>
/// 不同分支的父节点
/// </summary>
public Dictionary<ConnectionType,List<NodeModelBase>> PreviousNodes { get; }
/// <summary>
/// 不同分支的子节点
/// </summary>
public Dictionary<ConnectionType,List<NodeModelBase>> SuccessorNodes { get; }
/// <summary>
/// 当前执行状态(进入真分支还是假分支,异常分支在异常中确定)
/// </summary>
public FlowStateType FlowState { get; set; } = FlowStateType.None;
/// <summary>
/// 运行时的异常信息(仅在 FlowState 为 Error 时存在对应值)
/// </summary>
public Exception RuningException { get; set; } = null;
/// <summary>
/// 当前传递数据(执行了节点对应的方法,才会存在值)
/// </summary>
public object? FlowData { get; set; } = null;
// public NodeModelBaseBuilder Build() => new NodeModelBaseBuilder(this);
}
/// <summary>
/// 节点基类(数据):条件控件,动作控件,条件区域,动作区域
/// </summary>
//public class NodeModelBaseBuilder
//{
// public NodeModelBaseBuilder(NodeModelBase builder)
// {
// this.ControlType = builder.ControlType;
// this.MethodDetails = builder.MethodDetails;
// this.Guid = builder.Guid;
// this.DisplayName = builder.DisplayName;
// this.IsStart = builder.IsStart;
// this.PreviousNode = builder.PreviousNode;
// this.PreviousNodes = builder.PreviousNodes;
// this.SucceedBranch = builder.SucceedBranch;
// this.FailBranch = builder.FailBranch;
// this.ErrorBranch = builder.ErrorBranch;
// this.UpstreamBranch = builder.UpstreamBranch;
// this.FlowState = builder.FlowState;
// this.RuningException = builder.RuningException;
// this.FlowData = builder.FlowData;
// }
// /// <summary>
// /// 节点对应的控件类型
// /// </summary>
// public NodeControlType ControlType { get; }
// /// <summary>
// /// 方法描述对应DLL的方法
// /// </summary>
// public MethodDetails MethodDetails { get; }
// /// <summary>
// /// 节点guid
// /// </summary>
// public string Guid { get; }
// /// <summary>
// /// 显示名称
// /// </summary>
// public string DisplayName { get;}
// /// <summary>
// /// 是否为起点控件
// /// </summary>
// public bool IsStart { get; }
// /// <summary>
// /// 运行时的上一节点
// /// </summary>
// public NodeModelBase? PreviousNode { get; }
// /// <summary>
// /// 上一节点集合
// /// </summary>
// public List<NodeModelBase> PreviousNodes { get; } = [];
// /// <summary>
// /// 下一节点集合(真分支)
// /// </summary>
// public List<NodeModelBase> SucceedBranch { get; } = [];
// /// <summary>
// /// 下一节点集合(假分支)
// /// </summary>
// public List<NodeModelBase> FailBranch { get; } = [];
// /// <summary>
// /// 异常分支
// /// </summary>
// public List<NodeModelBase> ErrorBranch { get; } = [];
// /// <summary>
// /// 上游分支
// /// </summary>
// public List<NodeModelBase> UpstreamBranch { get; } = [];
// /// <summary>
// /// 当前执行状态(进入真分支还是假分支,异常分支在异常中确定)
// /// </summary>
// public FlowStateType FlowState { get; set; } = FlowStateType.None;
// /// <summary>
// /// 运行时的异常信息(仅在 FlowState 为 Error 时存在对应值)
// /// </summary>
// public Exception RuningException { get; set; } = null;
// /// <summary>
// /// 当前传递数据(执行了节点对应的方法,才会存在值)
// /// </summary>
// public object? FlowData { get; set; } = null;
//}
}

View File

@@ -1,90 +1,48 @@
using Newtonsoft.Json;
using Serein.Library.Api;
using Serein.Library.Entity;
using Serein.Library.Enums;
using Serein.Library.Core.NodeFlow;
using Serein.NodeFlow.Tool;
using Serein.NodeFlow.Tool.SerinExpression;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Serein.NodeFlow.Model
namespace Serein.NodeFlow.Base
{
public enum ConnectionType
{
/// <summary>
/// 真分支
/// </summary>
IsSucceed,
/// <summary>
/// 假分支
/// </summary>
IsFail,
/// <summary>
/// 异常发生分支
/// </summary>
IsError,
/// <summary>
/// 上游分支(执行当前节点前会执行一次上游分支)
/// </summary>
Upstream,
}
/// <summary>
/// 节点基类(数据):条件控件,动作控件,条件区域,动作区域
/// </summary>
public abstract class NodeBase : IDynamicFlowNode
public abstract partial class NodeModelBase : IDynamicFlowNode
{
public abstract Parameterdata[] GetParameterdatas();
public virtual NodeInfo ToInfo()
{
if (MethodDetails == null) return null;
public MethodDetails MethodDetails { get; set; }
var trueNodes = SuccessorNodes[ConnectionType.IsSucceed].Select(item => item.Guid); // 真分支
var falseNodes = SuccessorNodes[ConnectionType.IsFail].Select(item => item.Guid);// 假分支
var upstreamNodes = SuccessorNodes[ConnectionType.IsError].Select(item => item.Guid);// 上游分支
var errorNodes = SuccessorNodes[ConnectionType.Upstream].Select(item => item.Guid);// 异常分支
// 生成参数列表
Parameterdata[] parameterData = GetParameterdatas();
public string Guid { get; set; }
public string DisplayName { get; set; }
public bool IsStart { get; set; }
public string DelegateName { get; set; }
/// <summary>
/// 运行时的上一节点
/// </summary>
public NodeBase? PreviousNode { get; set; }
/// <summary>
/// 上一节点集合
/// </summary>
public List<NodeBase> PreviousNodes { get; set; } = [];
/// <summary>
/// 下一节点集合(真分支)
/// </summary>
public List<NodeBase> SucceedBranch { get; set; } = [];
/// <summary>
/// 下一节点集合(假分支)
/// </summary>
public List<NodeBase> FailBranch { get; set; } = [];
/// <summary>
/// 异常分支
/// </summary>
public List<NodeBase> ErrorBranch { get; set; } = [];
/// <summary>
/// 上游分支
/// </summary>
public List<NodeBase> UpstreamBranch { get; set; } = [];
/// <summary>
/// 当前状态(进入真分支还是假分支,异常分支在异常中确定)
/// </summary>
public FlowStateType FlowState { get; set; } = FlowStateType.Succeed;
public Exception Exception { get; set; } = null;
/// <summary>
/// 当前传递数据
/// </summary>
public object? FlowData { get; set; } = null;
return new NodeInfo
{
Guid = Guid,
MethodName = MethodDetails?.MethodName,
Label = DisplayName ?? "",
Type = this.GetType().ToString(),
TrueNodes = trueNodes.ToArray(),
FalseNodes = falseNodes.ToArray(),
UpstreamNodes = upstreamNodes.ToArray(),
ParameterData = parameterData.ToArray(),
ErrorNodes = errorNodes.ToArray(),
};
}
/// <summary>
/// 执行节点对应的方法
@@ -95,11 +53,7 @@ namespace Serein.NodeFlow.Model
{
MethodDetails md = MethodDetails;
object? result = null;
if (!DelegateCache.GlobalDicDelegates.TryGetValue(md.MethodName, out Delegate del))
{
return result;
}
var del = md.MethodDelegate;
try
{
if (md.ExplicitDatas.Length == 0)
@@ -131,7 +85,7 @@ namespace Serein.NodeFlow.Model
catch (Exception ex)
{
FlowState = FlowStateType.Error;
Exception = ex;
RuningException = ex;
}
return result;
@@ -142,29 +96,24 @@ namespace Serein.NodeFlow.Model
/// </summary>
/// <param name="context"></param>
/// <returns>节点传回数据对象</returns>
/// <exception cref="Exception"></exception>
/// <exception cref="RuningException"></exception>
public virtual async Task<object?> ExecuteAsync(IDynamicContext context)
{
MethodDetails md = MethodDetails;
object? result = null;
if (!DelegateCache.GlobalDicDelegates.TryGetValue(md.MethodName, out Delegate del))
{
return result;
}
IFlipflopContext flipflopContext = null;
try
{
// 调用委托并获取结果
if (md.ExplicitDatas.Length == 0)
{
flipflopContext = await ((Func<object, Task<IFlipflopContext>>)del).Invoke(MethodDetails.ActingInstance);
flipflopContext = await ((Func<object, Task<IFlipflopContext>>)md.MethodDelegate).Invoke(MethodDetails.ActingInstance);
}
else
{
object?[]? parameters = GetParameters(context, MethodDetails);
flipflopContext = await ((Func<object, object[], Task<IFlipflopContext>>)del).Invoke(MethodDetails.ActingInstance, parameters);
flipflopContext = await ((Func<object, object[], Task<IFlipflopContext>>)md.MethodDelegate).Invoke(MethodDetails.ActingInstance, parameters);
}
if (flipflopContext != null)
@@ -183,7 +132,7 @@ namespace Serein.NodeFlow.Model
catch (Exception ex)
{
FlowState = FlowStateType.Error;
Exception = ex;
RuningException = ex;
}
return result;
@@ -198,7 +147,7 @@ namespace Serein.NodeFlow.Model
{
var cts = context.SereinIoc.GetOrInstantiate<CancellationTokenSource>();
Stack<NodeBase> stack = [];
Stack<NodeModelBase> stack = [];
stack.Push(this);
while (stack.Count > 0 && !cts.IsCancellationRequested) // 循环中直到栈为空才会退出循环
@@ -213,7 +162,7 @@ namespace Serein.NodeFlow.Model
}
// 获取上游分支,首先执行一次
var upstreamNodes = currentNode.UpstreamBranch;
var upstreamNodes = currentNode.SuccessorNodes[ConnectionType.Upstream];
for (int i = upstreamNodes.Count - 1; i >= 0; i--)
{
upstreamNodes[i].PreviousNode = currentNode;
@@ -231,13 +180,14 @@ namespace Serein.NodeFlow.Model
currentNode.FlowData = currentNode.Execute(context);
}
var nextNodes = currentNode.FlowState switch
ConnectionType connection = currentNode.FlowState switch
{
FlowStateType.Succeed => currentNode.SucceedBranch,
FlowStateType.Fail => currentNode.FailBranch,
FlowStateType.Error => currentNode.ErrorBranch,
FlowStateType.Succeed => ConnectionType.IsSucceed,
FlowStateType.Fail => ConnectionType.IsFail,
FlowStateType.Error => ConnectionType.IsError,
_ => throw new Exception("非预期的枚举值")
};
var nextNodes = currentNode.SuccessorNodes[connection];
// 将下一个节点集合中的所有节点逆序推入栈中
for (int i = nextNodes.Count - 1; i >= 0; i--)
@@ -278,7 +228,7 @@ namespace Serein.NodeFlow.Model
{
parameters[i] = md;
}
else if (type == typeof(NodeBase))
else if (type == typeof(NodeModelBase))
{
parameters[i] = this;
}
@@ -288,7 +238,7 @@ namespace Serein.NodeFlow.Model
if (mdEd.DataValue[0] == '@')
{
var expResult = SerinExpressionEvaluator.Evaluate(mdEd.DataValue, PreviousNode?.FlowData, out bool isChange);
if (mdEd.DataType.IsEnum)
{
@@ -348,11 +298,11 @@ namespace Serein.NodeFlow.Model
}
}
}
else if (f1 != null && f2 != null)
{
if(f2.IsAssignableFrom(f1) || f2.FullName.Equals(f1.FullName))
if (f2.IsAssignableFrom(f1) || f2.FullName.Equals(f1.FullName))
{
parameters[i] = PreviousNode?.FlowData;
@@ -534,37 +484,5 @@ namespace Serein.NodeFlow.Model
}
}
/* while (stack.Count > 0) // 循环中直到栈为空才会退出
{
// 从栈中弹出一个节点作为当前节点进行处理
var currentNode = stack.Pop();
if(currentNode is CompositeActionNode || currentNode is CompositeConditionNode)
{
currentNode.currentState = true;
}
else if (currentNode is CompositeConditionNode)
{
}
currentNode.Execute(context);
// 根据当前节点的执行结果选择下一节点集合
// 如果 currentState 为真,选择 TrueBranchNextNodes否则选择 FalseBranchNextNodes
var nextNodes = currentNode.currentState ? currentNode.TrueBranchNextNodes
: currentNode.FalseBranchNextNodes;
// 将下一个节点集合中的所有节点逆序推入栈中
for (int i = nextNodes.Count - 1; i >= 0; i--)
{
stack.Push(nextNodes[i]);
}
}*/

View File

@@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Serein.NodeFlow
{
public enum ConnectionType
{
/// <summary>
/// 真分支
/// </summary>
IsSucceed,
/// <summary>
/// 假分支
/// </summary>
IsFail,
/// <summary>
/// 异常发生分支
/// </summary>
IsError,
/// <summary>
/// 上游分支(执行当前节点前会执行一次上游分支)
/// </summary>
Upstream,
}
}

View File

@@ -1,38 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Serein.NodeFlow
{
//public enum DynamicNodeType
//{
// /// <summary>
// /// 初始化
// /// </summary>
// Init,
// /// <summary>
// /// 开始载入
// /// </summary>
// Loading,
// /// <summary>
// /// 结束
// /// </summary>
// Exit,
// /// <summary>
// /// 触发器
// /// </summary>
// Flipflop,
// /// <summary>
// /// 条件节点
// /// </summary>
// Condition,
// /// <summary>
// /// 动作节点
// /// </summary>
// Action,
//}
}

613
NodeFlow/FlowEnvironment.cs Normal file
View File

@@ -0,0 +1,613 @@
using Serein.Library.Api;
using Serein.Library.Attributes;
using Serein.Library.Entity;
using Serein.Library.Enums;
using Serein.Library.Utils;
using Serein.NodeFlow.Base;
using Serein.NodeFlow.Model;
using Serein.NodeFlow.Tool;
using System.Diagnostics;
using System.Reflection;
using System.Reflection.Emit;
using System.Xml.Linq;
namespace Serein.NodeFlow
{
/*
脱离wpf平台独立运行。
加载文件。
创建节点对象,设置节点属性,确定连接关系,设置起点。
↓抽象↓
wpf依赖于运行环境而不是运行环境依赖于wpf。
运行环境实现以下功能:
①从项目文件加载数据,生成项目文件对象。
②运行项目,调试项目,中止项目,终止项目。
③自动包装数据类型,在上下文中传递数据。
*/
/// <summary>
/// 运行环境
/// </summary>
/// <summary>
/// 运行环境
/// </summary>
public class FlowEnvironment : IFlowEnvironment
{
/// <summary>
/// 加载Dll
/// </summary>
public event LoadDLLHandler OnDllLoad;
/// <summary>
/// 加载节点
/// </summary>
public event LoadNodeHandler OnLoadNode;
/// <summary>
/// 连接节点
/// </summary>
public event NodeConnectChangeHandler OnNodeConnectChange;
/// <summary>
/// 创建节点
/// </summary>
public event NodeCreateHandler OnNodeCreate;
public event NodeRemoteHandler OnNodeRemote;
public event StartNodeChangeHandler OnStartNodeChange;
public event FlowRunCompleteHandler OnFlowRunComplete;
private FlowStarter? nodeFlowStarter = null;
/// <summary>
/// 节点的命名空间
/// </summary>
public const string NodeSpaceName = $"{nameof(Serein)}.{nameof(Serein.NodeFlow)}.{nameof(Serein.NodeFlow.Model)}";
/// <summary>
/// 一种轻量的IOC容器
/// </summary>
public SereinIoc SereinIoc { get; } = new SereinIoc();
/// <summary>
/// 存储加载的程序集路径
/// </summary>
public List<string> LoadedAssemblyPaths { get; } = [];
/// <summary>
/// 存储加载的程序集
/// </summary>
public List<Assembly> LoadedAssemblies { get; } = [];
/// <summary>
/// 存储所有方法信息
/// </summary>
public List<MethodDetails> MethodDetailss { get; } = [];
public Dictionary<string,NodeModelBase> Nodes { get; } = [];
public List<NodeModelBase> Regions { get; } = [];
/// <summary>
/// 存放触发器节点(运行时全部调用)
/// </summary>
public List<SingleFlipflopNode> FlipflopNodes { get; } = [];
private NodeModelBase? _startNode = null;
public NodeModelBase StartNode {
get
{
return _startNode;
}
set {
if(_startNode is null)
{
value.IsStart = true;
_startNode = value;
}
else
{
_startNode.IsStart = false;
value.IsStart = true;
_startNode = value;
}
} }
public async Task StartAsync()
{
nodeFlowStarter = new FlowStarter(SereinIoc, MethodDetailss);
var nodes = Nodes.Values.ToList();
var flipflopNodes = nodes.Where(it => it.MethodDetails?.MethodDynamicType == NodeType.Flipflop
&& it.PreviousNodes.Count == 0
&& it.IsStart != true)
.Select(it => it as SingleFlipflopNode)
.ToList();
await nodeFlowStarter.RunAsync(StartNode, this, flipflopNodes);
OnFlowRunComplete?.Invoke(new FlowEventArgs());
}
public void Exit()
{
nodeFlowStarter?.Exit();
nodeFlowStarter = null;
OnFlowRunComplete?.Invoke(new FlowEventArgs());
}
/// <summary>
/// 清除所有
/// </summary>
public void ClearAll()
{
LoadedAssemblyPaths.Clear();
LoadedAssemblies.Clear();
MethodDetailss.Clear();
}
#region
/// <summary>
/// 获取方法描述
/// </summary>
public bool TryGetMethodDetails(string name, out MethodDetails? md)
{
md = MethodDetailss.FirstOrDefault(it => it.MethodName == name);
if(md == null)
{
return false;
}
return true;
}
/// <summary>
/// 加载项目文件
/// </summary>
/// <param name="projectFile"></param>
/// <param name="filePath"></param>
public void LoadProject(SereinOutputFileData projectFile, string filePath)
{
// 加载项目配置文件
var dllPaths = projectFile.Librarys.Select(it => it.Path).ToList();
List<MethodDetails> methodDetailss = [];
// 遍历依赖项中的特性注解,生成方法详情
foreach (var dll in dllPaths)
{
var dllFilePath = System.IO.Path.GetFullPath(System.IO.Path.Combine(filePath, dll));
(var assembly, var list) = LoadAssembly(dllFilePath);
if (assembly is not null && list.Count > 0)
{
methodDetailss.AddRange(methodDetailss); // 暂存方法描述
OnDllLoad?.Invoke(new LoadDLLEventArgs(assembly, methodDetailss)); // 通知UI创建dll面板显示
}
}
// 方法加载完成,缓存到运行环境中。
MethodDetailss.AddRange(methodDetailss);
methodDetailss.Clear();
// 加载节点
foreach (var nodeInfo in projectFile.Nodes)
{
if (TryGetMethodDetails(nodeInfo.MethodName, out MethodDetails? methodDetails))
{
OnLoadNode?.Invoke(new LoadNodeEventArgs(nodeInfo, methodDetails));
}
}
// 确定节点之间的连接关系
foreach (var nodeInfo in projectFile.Nodes)
{
if (!Nodes.TryGetValue(nodeInfo.Guid, out NodeModelBase fromNode))
{
// 不存在对应的起始节点
continue;
}
List<(ConnectionType, string[])> nodeGuids = [(ConnectionType.IsSucceed,nodeInfo.TrueNodes),
(ConnectionType.IsFail, nodeInfo.FalseNodes),
(ConnectionType.IsError, nodeInfo.ErrorNodes),
(ConnectionType.Upstream, nodeInfo.UpstreamNodes)];
List<(ConnectionType, NodeModelBase[])> nodes = nodeGuids.Where(info => info.Item2.Length > 0)
.Select(info => (info.Item1,
info.Item2.Select(guid => Nodes[guid])
.ToArray()))
.ToList();
// 遍历每种类型的节点分支(四种)
foreach ((ConnectionType connectionType, NodeModelBase[] nodeBases) item in nodes)
{
// 遍历当前类型分支的节点(确认连接关系)
foreach (var node in item.nodeBases)
{
ConnectNode(fromNode, node, item.connectionType); // 加载时确定节点间的连接关系
}
}
}
}
/// <summary>
/// 连接节点
/// </summary>
/// <param name="fromNode">起始节点</param>
/// <param name="toNode">目标节点</param>
/// <param name="connectionType">连接关系</param>
public void ConnectNode(string fromNodeGuid, string toNodeGuid, ConnectionType connectionType)
{
// 获取起始节点与目标节点
if (!Nodes.TryGetValue(fromNodeGuid, out NodeModelBase? fromNode) || !Nodes.TryGetValue(toNodeGuid, out NodeModelBase? toNode))
{
return;
}
if(fromNode is null || toNode is null)
{
return ;
}
// 开始连接
ConnectNode(fromNode, toNode, connectionType); // 外部调用连接方法
}
/// <summary>
/// 创建节点
/// </summary>
/// <param name="nodeBase"></param>
public void CreateNode(NodeControlType nodeControlType, MethodDetails? methodDetails = null)
{
// 确定创建的节点类型
Type? nodeType = nodeControlType switch
{
NodeControlType.Action => typeof(SingleActionNode),
NodeControlType.Flipflop => typeof(SingleFlipflopNode),
NodeControlType.ExpOp => typeof(SingleExpOpNode),
NodeControlType.ExpCondition => typeof(SingleConditionNode),
NodeControlType.ConditionRegion => typeof(CompositeConditionNode),
_ => null
};
if(nodeType == null)
{
return;
}
// 生成实例
var nodeObj = Activator.CreateInstance(nodeType);
if (nodeObj is not NodeModelBase nodeBase)
{
return;
}
// 配置基础的属性
nodeBase.ControlType = nodeControlType;
nodeBase.Guid = Guid.NewGuid().ToString();
if (methodDetails != null)
{
var md = methodDetails.Clone();
nodeBase.DisplayName = md.MethodTips;
nodeBase.MethodDetails = md;
}
Nodes[nodeBase.Guid] = nodeBase;
// 如果是触发器,则需要添加到专属集合中
if (nodeControlType == NodeControlType.Flipflop && nodeBase is SingleFlipflopNode flipflopNode )
{
var guid = flipflopNode.Guid;
if (!FlipflopNodes.Exists(it => it.Guid.Equals(guid)))
{
FlipflopNodes.Add(flipflopNode);
}
}
// 通知UI更改
OnNodeCreate?.Invoke(new NodeCreateEventArgs(nodeBase));
// 因为需要UI先布置了元素才能通知UI变更特效
// 如果不存在流程起始控件,默认设置为流程起始控件
if (StartNode is null)
{
SetStartNode(nodeBase);
}
}
/// <summary>
/// 从文件路径中加载DLL
/// </summary>
/// <param name="dllPath"></param>
/// <returns></returns>
public void LoadDll(string dllPath)
{
(var assembly, var list) = LoadAssembly(dllPath);
if (assembly is not null && list.Count > 0)
{
OnDllLoad?.Invoke(new LoadDLLEventArgs(assembly, list));
}
}
/// <summary>
/// 保存项目为项目文件
/// </summary>
/// <returns></returns>
public SereinOutputFileData SaveProject()
{
var projectData = new SereinOutputFileData()
{
Librarys = LoadedAssemblies.Select(assemblies => assemblies.ToLibrary()).ToArray(),
Nodes = Nodes.Values.Select(node => node.ToInfo()).Where(info => info is not null).ToArray(),
StartNode = Nodes.Values.FirstOrDefault(it => it.IsStart)?.Guid,
};
return projectData;
}
/// <summary>
/// 移除连接关系
/// </summary>
/// <param name="fromNodeGuid"></param>
/// <param name="toNodeGuid"></param>
/// <param name="connectionType"></param>
/// <exception cref="NotImplementedException"></exception>
public void RemoteConnect(string fromNodeGuid, string toNodeGuid, ConnectionType connectionType)
{
// 获取起始节点与目标节点
if (!Nodes.TryGetValue(fromNodeGuid, out NodeModelBase? fromNode) || !Nodes.TryGetValue(toNodeGuid, out NodeModelBase? toNode))
{
return;
}
if (fromNode is null || toNode is null)
{
return;
}
fromNode.SuccessorNodes[connectionType].Remove(toNode);
toNode.PreviousNodes[connectionType].Remove(fromNode);
OnNodeConnectChange?.Invoke(new NodeConnectChangeEventArgs(fromNodeGuid,
toNodeGuid,
connectionType,
NodeConnectChangeEventArgs.ChangeTypeEnum.Remote));
}
/// <summary>
/// 移除节点
/// </summary>
/// <param name="nodeGuid"></param>
/// <exception cref="NotImplementedException"></exception>
public void RemoteNode(string nodeGuid)
{
if (!Nodes.TryGetValue(nodeGuid, out NodeModelBase? remoteNode))
{
return;
}
if (remoteNode is null)
{
return;
}
if (remoteNode.IsStart)
{
return;
}
// 遍历所有父节点,从那些父节点中的子节点集合移除该节点
foreach(var pnc in remoteNode.PreviousNodes)
{
var pCType = pnc.Key; // 连接类型
for (int i = 0; i < pnc.Value.Count; i++)
{
NodeModelBase? pNode = pnc.Value[i];
pNode.SuccessorNodes[pCType].RemoveAt(i);
OnNodeConnectChange?.Invoke(new NodeConnectChangeEventArgs(pNode.Guid,
remoteNode.Guid,
pCType,
NodeConnectChangeEventArgs.ChangeTypeEnum.Remote)); // 通知UI
}
}
// 遍历所有子节点,从那些子节点中的父节点集合移除该节点
foreach (var snc in remoteNode.SuccessorNodes)
{
var sCType = snc.Key; // 连接类型
for (int i = 0; i < snc.Value.Count; i++)
{
NodeModelBase? sNode = snc.Value[i];
remoteNode.SuccessorNodes[sCType].RemoveAt(i);
OnNodeConnectChange?.Invoke(new NodeConnectChangeEventArgs(remoteNode.Guid,
sNode.Guid,
sCType,
NodeConnectChangeEventArgs.ChangeTypeEnum.Remote)); // 通知UI
}
}
// 从集合中移除节点
Nodes.Remove(nodeGuid);
OnNodeRemote?.Invoke(new NodeRemoteEventArgs(nodeGuid));
}
/// <summary>
/// 设置起点控件
/// </summary>
/// <param name="newNodeGuid"></param>
public void SetStartNode(string newNodeGuid)
{
if(Nodes.TryGetValue(newNodeGuid, out NodeModelBase? newStartNodeModel))
{
if(newStartNodeModel != null)
{
SetStartNode(newStartNodeModel);
//var oldNodeGuid = "";
//if(StartNode != null)
//{
// oldNodeGuid = StartNode.Guid;
// StartNode.IsStart = false;
//}
//newStartNodeModel.IsStart = true;
//StartNode = newStartNodeModel;
//OnStartNodeChange?.Invoke(new StartNodeChangeEventArgs(oldNodeGuid, newNodeGuid));
}
}
}
#endregion
#region
/// <summary>
/// 加载指定路径的DLL文件
/// </summary>
/// <param name="dllPath"></param>
private (Assembly?, List<MethodDetails>) LoadAssembly(string dllPath)
{
try
{
Assembly assembly = Assembly.LoadFrom(dllPath); // 加载DLL文件
Type[] types = assembly.GetTypes(); // 获取程序集中的所有类型
List<Type> scanTypes = assembly.GetTypes().Where(t => t.GetCustomAttribute<DynamicFlowAttribute>()?.Scan == true).ToList();
if (scanTypes.Count == 0)
{
return (null, []);
}
List<MethodDetails> methodDetails = new List<MethodDetails>();
// 遍历扫描的类型
foreach (var item in scanTypes)
{
//加载DLL创建 MethodDetails、实例作用对象、委托方法
var itemMethodDetails = MethodDetailsHelperTmp.GetList(item, false);
methodDetails.AddRange(itemMethodDetails);
}
LoadedAssemblies.Add(assembly); // 将加载的程序集添加到列表中
LoadedAssemblyPaths.Add(dllPath); // 记录加载的DLL路径
return (assembly, methodDetails);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return (null, []);
}
}
/// <summary>
/// 连接节点
/// </summary>
/// <param name="fromNode">起始节点</param>
/// <param name="toNode">目标节点</param>
/// <param name="connectionType">连接关系</param>
private void ConnectNode(NodeModelBase fromNode, NodeModelBase toNode, ConnectionType connectionType)
{
if (fromNode == null || toNode == null || fromNode == toNode)
{
return;
}
var ToExistOnFrom = true;
var FromExistInTo = true;
ConnectionType[] ct = [ConnectionType.IsSucceed,
ConnectionType.IsFail,
ConnectionType.IsError,
ConnectionType.Upstream];
foreach (ConnectionType ctType in ct)
{
var FToTo = fromNode.SuccessorNodes[ctType].Where(it => it.Guid.Equals(toNode.Guid)).ToArray();
var ToOnF = toNode.PreviousNodes[ctType].Where(it => it.Guid.Equals(fromNode.Guid)).ToArray();
ToExistOnFrom = FToTo.Length > 0;
FromExistInTo = ToOnF.Length > 0;
if (ToExistOnFrom && FromExistInTo)
{
Console.WriteLine("起始节点已与目标节点存在连接");
return;
}
else
{
// 检查是否可能存在异常
if (!ToExistOnFrom && FromExistInTo)
{
Console.WriteLine("目标节点不是起始节点的子节点,起始节点却是目标节点的父节点");
return;
}
else if (ToExistOnFrom && !FromExistInTo)
{
//
Console.WriteLine(" 起始节点不是目标节点的父节点,目标节点却是起始节点的子节点");
return;
}
else // if (!ToExistOnFrom && !FromExistInTo)
{
// 可以正常连接
}
}
}
fromNode.SuccessorNodes[connectionType].Add(toNode); // 添加到起始节点的子分支
toNode.PreviousNodes[connectionType].Add(fromNode); // 添加到目标节点的父分支
OnNodeConnectChange?.Invoke(new NodeConnectChangeEventArgs(fromNode.Guid,
toNode.Guid,
connectionType,
NodeConnectChangeEventArgs.ChangeTypeEnum.Create)); // 通知UI
}
/// <summary>
/// 更改起点节点
/// </summary>
/// <param name="newStartNode"></param>
/// <param name="oldStartNode"></param>
private void SetStartNode(NodeModelBase newStartNode)
{
var oldNodeGuid = StartNode?.Guid;
StartNode = newStartNode;
OnStartNodeChange?.Invoke(new StartNodeChangeEventArgs(oldNodeGuid, StartNode.Guid));
}
#endregion
#region
#region WPF
#endregion
#region Socket的方式进行操作
#endregion
#endregion
}
public static class FlowFunc
{
public static Library.Entity.Library ToLibrary(this Assembly assembly)
{
return new Library.Entity.Library
{
Name = assembly.GetName().Name,
Path = assembly.Location,
};
}
}
}

View File

@@ -1,56 +1,51 @@
using Serein.Library.Api;
using Serein.Library.Enums;
using Serein.Library.Core.NodeFlow;
using Serein.Library.Entity;
using Serein.Library.Enums;
using Serein.Library.Utils;
using Serein.NodeFlow.Base;
using Serein.NodeFlow.Model;
using Serein.NodeFlow.Tool;
namespace Serein.NodeFlow
{
public class NodeRunTcs : CancellationTokenSource
{
}
public class NodeFlowStarter(ISereinIoc serviceContainer, List<MethodDetails> methodDetails)
/// <summary>
/// 流程启动器
/// </summary>
/// <param name="serviceContainer"></param>
/// <param name="methodDetails"></param>
public class FlowStarter(ISereinIoc serviceContainer, List<MethodDetails> methodDetails)
{
private readonly ISereinIoc ServiceContainer = serviceContainer;
private readonly List<MethodDetails> methodDetails = methodDetails;
private Action ExitAction = null;
private IDynamicContext context = null;
public NodeRunTcs MainCts;
private Action ExitAction = null; //退出方法
private IDynamicContext context = null; //上下文
public NodeRunCts MainCts;
/// <summary>
/// 运行测试
/// 开始运行
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
//public async Task RunAsync1(List<NodeBase> nodes)
//{
// await Task.Run(async ()=> await StartRunAsync(nodes));
//}
public async Task RunAsync(List<NodeBase> nodes)
/// <param name="nodes"></param>
/// <returns></returns>
// public async Task RunAsync(List<NodeModelBase> nodes, IFlowEnvironment flowEnvironment)
public async Task RunAsync(NodeModelBase startNode, IFlowEnvironment flowEnvironment, List<SingleFlipflopNode> flipflopNodes)
{
var startNode = nodes.FirstOrDefault(p => p.IsStart);
// var startNode = nodes.FirstOrDefault(p => p.IsStart);
if (startNode == null) { return; }
if (false)
var isNetFramework = true;
if (isNetFramework)
{
context = new Serein.Library.Core.NodeFlow.DynamicContext(ServiceContainer);
context = new Serein.Library.Framework.NodeFlow.DynamicContext(ServiceContainer, flowEnvironment);
}
else
{
context = new Serein.Library.Framework.NodeFlow.DynamicContext(ServiceContainer);
context = new Serein.Library.Core.NodeFlow.DynamicContext(ServiceContainer, flowEnvironment);
}
MainCts = ServiceContainer.CreateServiceInstance<NodeRunTcs>();
MainCts = ServiceContainer.CreateServiceInstance<NodeRunCts>();
var initMethods = methodDetails.Where(it => it.MethodDynamicType == NodeType.Init).ToList();
var loadingMethods = methodDetails.Where(it => it.MethodDynamicType == NodeType.Loading).ToList();
@@ -75,10 +70,8 @@ namespace Serein.NodeFlow
ServiceContainer.Reset();
};
foreach (var md in initMethods) // 初始化 - 调用方法
{
//md.ActingInstance = context.ServiceContainer.Get(md.ActingInstanceType);
object?[]? args = [context];
object?[]? data = [md.ActingInstance, args];
md.MethodDelegate.DynamicInvoke(data);
@@ -87,25 +80,20 @@ namespace Serein.NodeFlow
foreach (var md in loadingMethods) // 加载
{
//md.ActingInstance = context.ServiceContainer.Get(md.ActingInstanceType);
object?[]? args = [context];
object?[]? data = [md.ActingInstance, args];
md.MethodDelegate.DynamicInvoke(data);
}
var flipflopNodes = nodes.Where(it => it.MethodDetails?.MethodDynamicType == NodeType.Flipflop
&& it.PreviousNodes.Count == 0
&& it.IsStart != true).ToArray();
// 运行触发器节点
var singleFlipflopNodes = flipflopNodes.Select(it => (SingleFlipflopNode)it).ToArray();
// 使用 TaskCompletionSource 创建未启动的任务
var tasks = singleFlipflopNodes.Select(async node =>
{
await FlipflopExecute(node);
await FlipflopExecute(node, flowEnvironment);
}).ToArray();
try
{
await Task.Run(async () =>
@@ -120,19 +108,17 @@ namespace Serein.NodeFlow
}
private async Task FlipflopExecute(SingleFlipflopNode singleFlipFlopNode)
/// <summary>
/// 启动触发器
/// </summary>
private async Task FlipflopExecute(SingleFlipflopNode singleFlipFlopNode, IFlowEnvironment flowEnvironment)
{
DynamicContext context = new DynamicContext(ServiceContainer);
DynamicContext context = new DynamicContext(ServiceContainer, flowEnvironment);
MethodDetails md = singleFlipFlopNode.MethodDetails;
var del = md.MethodDelegate;
try
{
if (!DelegateCache.GlobalDicDelegates.TryGetValue(md.MethodName, out Delegate del))
{
return;
}
//var func = md.ExplicitDatas.Length == 0 ? (Func<object, object, Task<FlipflopContext<dynamic>>>)del : (Func<object, object[], Task<FlipflopContext<dynamic>>>)del;
var func = md.ExplicitDatas.Length == 0 ? (Func<object, object, Task<IFlipflopContext>>)del : (Func<object, object[], Task<IFlipflopContext>>)del;
@@ -144,30 +130,22 @@ namespace Serein.NodeFlow
IFlipflopContext flipflopContext = await func.Invoke(md.ActingInstance, parameters);
if (flipflopContext == null)
{
break;
}
else if (flipflopContext.State == FlowStateType.Error)
{
break;
}
else if (flipflopContext.State == FlowStateType.Fail)
{
break;
}
else if (flipflopContext.State == FlowStateType.Succeed)
if (flipflopContext.State == FlowStateType.Succeed)
{
singleFlipFlopNode.FlowState = FlowStateType.Succeed;
singleFlipFlopNode.FlowData = flipflopContext.Data;
var tasks = singleFlipFlopNode.SucceedBranch.Select(nextNode =>
var tasks = singleFlipFlopNode.PreviousNodes[ConnectionType.IsSucceed].Select(nextNode =>
{
var context = new DynamicContext(ServiceContainer);
var context = new DynamicContext(ServiceContainer,flowEnvironment);
nextNode.PreviousNode = singleFlipFlopNode;
return nextNode.StartExecution(context);
}).ToArray();
Task.WaitAll(tasks);
}
else
{
break;
}
}
}
catch (Exception ex)

View File

@@ -1,24 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Serein.NodeFlow
{
//public enum FlowStateType
//{
// /// <summary>
// /// 成功(方法成功执行)
// /// </summary>
// Succeed,
// /// <summary>
// /// 失败(方法没有成功执行,不过执行时没有发生非预期的错误)
// /// </summary>
// Fail,
// /// <summary>
// /// 异常(节点没有成功执行,执行时发生非预期的错误)
// /// </summary>
// Error,
//}
}

View File

@@ -1,4 +1,5 @@
using Serein.Library.Enums;
using Serein.Library.Api;
using Serein.Library.Enums;
namespace Serein.NodeFlow
{
@@ -65,7 +66,7 @@ namespace Serein.NodeFlow
public class MethodDetails
public class MethodDetails : IMethodDetails
{
/// <summary>
/// 拷贝

View File

@@ -1,10 +1,14 @@
namespace Serein.NodeFlow.Model
using Serein.Library.Entity;
using Serein.Library.Enums;
using Serein.NodeFlow.Base;
namespace Serein.NodeFlow.Model
{
/// <summary>
/// 组合动作节点(用于动作区域)
/// </summary>
public class CompositeActionNode : NodeBase
public class CompositeActionNode : NodeModelBase
{
public List<SingleActionNode> ActionNodes;
/// <summary>
@@ -14,12 +18,42 @@
{
ActionNodes = actionNodes;
}
public void AddNode(SingleActionNode node)
{
ActionNodes.Add(node);
MethodDetails ??= node.MethodDetails;
}
public override Parameterdata[] GetParameterdatas()
{
return [];
}
public override NodeInfo ToInfo()
{
if (MethodDetails == null) return null;
//var trueNodes = SucceedBranch.Select(item => item.Guid); // 真分支
//var falseNodes = FailBranch.Select(item => item.Guid);// 假分支
//var upstreamNodes = UpstreamBranch.Select(item => item.Guid);// 上游分支
//var errorNodes = ErrorBranch.Select(item => item.Guid);// 异常分支
var trueNodes = SuccessorNodes[ConnectionType.IsSucceed].Select(item => item.Guid); // 真分支
var falseNodes = SuccessorNodes[ConnectionType.IsFail].Select(item => item.Guid);// 假分支
var upstreamNodes = SuccessorNodes[ConnectionType.IsError].Select(item => item.Guid);// 上游分支
var errorNodes = SuccessorNodes[ConnectionType.Upstream].Select(item => item.Guid);// 异常分支
// 生成参数列表
Parameterdata[] parameterData = GetParameterdatas();
return new NodeInfo
{
Guid = Guid,
MethodName = MethodDetails?.MethodName,
Label = DisplayName ?? "",
Type = this.GetType().ToString(),
TrueNodes = trueNodes.ToArray(),
FalseNodes = falseNodes.ToArray(),
UpstreamNodes = upstreamNodes.ToArray(),
ParameterData = parameterData.ToArray(),
ErrorNodes = errorNodes.ToArray(),
ChildNodes = ActionNodes.Select(node => node.ToInfo()).ToArray(),
};
}
}
}

View File

@@ -1,13 +1,14 @@
using Serein.Library.Api;
using Serein.Library.Entity;
using Serein.Library.Enums;
using Serein.Library.Core.NodeFlow;
using Serein.NodeFlow.Base;
namespace Serein.NodeFlow.Model
{
/// <summary>
/// 组合条件节点(用于条件区域)
/// </summary>
public class CompositeConditionNode : NodeBase
public class CompositeConditionNode : NodeModelBase
{
public List<SingleConditionNode> ConditionNodes { get; } = [];
@@ -54,6 +55,10 @@ namespace Serein.NodeFlow.Model
// }
//}
}
private FlowStateType Judge(IDynamicContext context, SingleConditionNode node)
{
try
@@ -68,7 +73,41 @@ namespace Serein.NodeFlow.Model
}
}
public override Parameterdata[] GetParameterdatas()
{
return [];
}
public override NodeInfo ToInfo()
{
if (MethodDetails == null) return null;
//var trueNodes = SucceedBranch.Select(item => item.Guid); // 真分支
//var falseNodes = FailBranch.Select(item => item.Guid);// 假分支
//var upstreamNodes = UpstreamBranch.Select(item => item.Guid);// 上游分支
//var errorNodes = ErrorBranch.Select(item => item.Guid);// 异常分支
var trueNodes = SuccessorNodes[ConnectionType.IsSucceed].Select(item => item.Guid); // 真分支
var falseNodes = SuccessorNodes[ConnectionType.IsFail].Select(item => item.Guid);// 假分支
var upstreamNodes = SuccessorNodes[ConnectionType.IsError].Select(item => item.Guid);// 上游分支
var errorNodes = SuccessorNodes[ConnectionType.Upstream].Select(item => item.Guid);// 异常分支
// 生成参数列表
Parameterdata[] parameterData = GetParameterdatas();
return new NodeInfo
{
Guid = Guid,
MethodName = MethodDetails?.MethodName,
Label = DisplayName ?? "",
Type = this.GetType().ToString(),
TrueNodes = trueNodes.ToArray(),
FalseNodes = falseNodes.ToArray(),
UpstreamNodes = upstreamNodes.ToArray(),
ParameterData = parameterData.ToArray(),
ErrorNodes = errorNodes.ToArray(),
ChildNodes = ConditionNodes.Select(node => node.ToInfo()).ToArray(),
};
}
}

View File

@@ -1,6 +1,6 @@
namespace Serein.NodeFlow.Model
{
public class CompositeLoopNode : NodeBase
{
}
//public class CompositeLoopNode : NodeBase
//{
//}
}

View File

@@ -1,9 +1,12 @@
namespace Serein.NodeFlow.Model
using Serein.Library.Entity;
using Serein.NodeFlow.Base;
namespace Serein.NodeFlow.Model
{
/// <summary>
/// 单动作节点(用于动作控件)
/// </summary>
public class SingleActionNode : NodeBase
public class SingleActionNode : NodeModelBase
{
//public override void Execute(DynamicContext context)
//{
@@ -61,7 +64,23 @@
// context.SetFlowData(result);
// }
//}
public override Parameterdata[] GetParameterdatas()
{
if (base.MethodDetails.ExplicitDatas.Length > 0)
{
return MethodDetails.ExplicitDatas
.Select(it => new Parameterdata
{
state = it.IsExplicitData,
value = it.DataValue,
})
.ToArray();
}
else
{
return [];
}
}
}

View File

@@ -1,7 +1,8 @@
using Serein.Library.Api;
using Serein.Library.Entity;
using Serein.Library.Enums;
using Serein.Library.Core.NodeFlow;
using Serein.NodeFlow.Base;
using Serein.NodeFlow.Tool.SerinExpression;
namespace Serein.NodeFlow.Model
@@ -9,7 +10,7 @@ namespace Serein.NodeFlow.Model
/// <summary>
/// 条件节点(用于条件控件)
/// </summary>
public class SingleConditionNode : NodeBase
public class SingleConditionNode : NodeModelBase
{
/// <summary>
@@ -47,13 +48,40 @@ namespace Serein.NodeFlow.Model
catch (Exception ex)
{
FlowState = FlowStateType.Error;
Exception = ex;
RuningException = ex;
}
Console.WriteLine($"{result} {Expression} -> " + FlowState);
return result;
}
public override Parameterdata[] GetParameterdatas()
{
if (base.MethodDetails.ExplicitDatas.Length > 0)
{
return MethodDetails.ExplicitDatas
.Select(it => new Parameterdata
{
state = IsCustomData,
expression = Expression,
value = CustomData switch
{
Type when CustomData.GetType() == typeof(int)
&& CustomData.GetType() == typeof(double)
&& CustomData.GetType() == typeof(float)
=> ((double)CustomData).ToString(),
Type when CustomData.GetType() == typeof(bool) => ((bool)CustomData).ToString(),
_ => CustomData?.ToString()!,
}
})
.ToArray();
}
else
{
return [];
}
}
//public override void Execute(DynamicContext context)
//{
// CurrentState = Judge(context, base.MethodDetails);

View File

@@ -1,6 +1,7 @@
using Serein.Library.Api;
using Serein.Library.Entity;
using Serein.Library.Enums;
using Serein.Library.Core.NodeFlow;
using Serein.NodeFlow.Base;
using Serein.NodeFlow.Tool.SerinExpression;
namespace Serein.NodeFlow.Model
@@ -8,7 +9,7 @@ namespace Serein.NodeFlow.Model
/// <summary>
/// Expression Operation - 表达式操作
/// </summary>
public class SingleExpOpNode : NodeBase
public class SingleExpOpNode : NodeModelBase
{
/// <summary>
/// 表达式
@@ -34,5 +35,24 @@ namespace Serein.NodeFlow.Model
}
}
public override Parameterdata[] GetParameterdatas()
{
if (base.MethodDetails.ExplicitDatas.Length > 0)
{
return MethodDetails.ExplicitDatas
.Select(it => new Parameterdata
{
state = it.IsExplicitData,
// value = it.DataValue,
expression = Expression,
})
.ToArray();
}
else
{
return [];
}
}
}
}

View File

@@ -1,15 +1,33 @@
using Serein.Library.Api;
using Serein.Library.Core.NodeFlow;
using Serein.Library.Entity;
using Serein.NodeFlow.Base;
namespace Serein.NodeFlow.Model
{
public class SingleFlipflopNode : NodeBase
public class SingleFlipflopNode : NodeModelBase
{
public override object Execute(IDynamicContext context)
{
throw new NotImplementedException("无法以非await/async的形式调用触发器");
}
public override Parameterdata[] GetParameterdatas()
{
if (base.MethodDetails.ExplicitDatas.Length > 0)
{
return MethodDetails.ExplicitDatas
.Select(it => new Parameterdata
{
state = it.IsExplicitData,
value = it.DataValue
})
.ToArray();
}
else
{
return [];
}
}
}
}

16
NodeFlow/MoveNodeData.cs Normal file
View File

@@ -0,0 +1,16 @@
using Serein.Library.Entity;
using Serein.Library.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Serein.NodeFlow
{
public class MoveNodeData
{
public NodeControlType NodeControlType { get; set; }
public MethodDetails MethodDetails { get; set; }
}
}

View File

@@ -17,9 +17,12 @@
</ItemGroup>
<ItemGroup>
<Compile Remove="ConnectionType.cs" />
<Compile Remove="DynamicContext.cs" />
<Compile Remove="MethodDetails.cs" />
<Compile Remove="Tool\Attribute.cs" />
<Compile Remove="Tool\DynamicTool.cs" />
<Compile Remove="Tool\NodeModelBaseFunc.cs" />
<Compile Remove="Tool\TcsSignal.cs" />
</ItemGroup>

View File

@@ -1,13 +1,16 @@
using System;
using Serein.Library.Api;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Serein.WorkBench
namespace Serein.NodeFlow
{
public class SereinOutputFileData
/* /// <summary>
/// 输出文件
/// </summary>
public class SereinOutputFileData
{
/// <summary>
/// 基础
@@ -58,6 +61,9 @@ namespace Serein.WorkBench
public string versions { get; set; }
// 预览位置
// 缩放比例
}
/// <summary>
/// 画布
@@ -179,5 +185,5 @@ namespace Serein.WorkBench
public string guid { get; set; }
public NodeInfo[] childNodes { get; set; }
}
}*/
}

View File

@@ -1,34 +1,218 @@
using Serein.Library.Api;
using Serein.Library.Attributes;
using Serein.Library.Core.NodeFlow;
using Serein.Library.Entity;
using System.Collections.Concurrent;
using System.Reflection;
namespace Serein.NodeFlow.Tool;
public static class DelegateCache
//public static class DelegateCache
//{
// /// <summary>
// /// 委托缓存全局字典
// /// </summary>
// //public static ConcurrentDictionary<string, Delegate> GlobalDicDelegates { get; } = new ConcurrentDictionary<string, Delegate>();
//}
public static class MethodDetailsHelperTmp
{
/// <summary>
/// 委托缓存全局字典
/// 生成方法信息
/// </summary>
public static ConcurrentDictionary<string, Delegate> GlobalDicDelegates { get; } = new ConcurrentDictionary<string, Delegate>();
/// <param name="serviceContainer"></param>
/// <param name="type"></param>
/// <returns></returns>
public static List<MethodDetails> GetList(Type type, bool isNetFramework)
{
var methodDetailsDictionary = new List<MethodDetails>();
var assemblyName = type.Assembly.GetName().Name;
var methods = GetMethodsToProcess(type, isNetFramework);
foreach (var method in methods)
{
var methodDetails = CreateMethodDetails(type, method, assemblyName, isNetFramework);
methodDetailsDictionary.Add(methodDetails);
}
return methodDetailsDictionary.OrderBy(it => it.MethodName).ToList();
}
/// <summary>
/// 获取处理方法
/// </summary>
private static IEnumerable<MethodInfo> GetMethodsToProcess(Type type, bool isNetFramework)
{
if (isNetFramework)
{
return type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
.Where(m => m.GetCustomAttribute<NodeActionAttribute>()?.Scan == true);
}
else
{
return type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
.Where(m => m.GetCustomAttribute<NodeActionAttribute>()?.Scan == true);
}
}
/// <summary>
/// 创建方法信息
/// </summary>
/// <returns></returns>
private static MethodDetails CreateMethodDetails(Type type, MethodInfo method, string assemblyName, bool isNetFramework)
{
var methodName = method.Name;
var attribute = method.GetCustomAttribute<NodeActionAttribute>();
var explicitDataOfParameters = GetExplicitDataOfParameters(method.GetParameters());
// 生成委托
var methodDelegate = GenerateMethodDelegate(type, // 方法所在的对象类型
method, // 方法信息
method.GetParameters(),// 方法参数
method.ReturnType);// 返回值
var dllTypeName = $"{assemblyName}.{type.Name}";
object instance = Activator.CreateInstance(type);
var dllTypeMethodName = $"{assemblyName}.{type.Name}.{method.Name}";
return new MethodDetails
{
ActingInstanceType = type,
ActingInstance = instance,
MethodName = dllTypeMethodName,
MethodDelegate = methodDelegate,
MethodDynamicType = attribute.MethodDynamicType,
MethodLockName = attribute.LockName,
MethodTips = attribute.MethodTips,
ExplicitDatas = explicitDataOfParameters,
ReturnType = method.ReturnType,
};
}
private static ExplicitData[] GetExplicitDataOfParameters(ParameterInfo[] parameters)
{
return parameters.Select((it, index) =>
{
//Console.WriteLine($"{it.Name}-{it.HasDefaultValue}-{it.DefaultValue}");
string explicitTypeName = GetExplicitTypeName(it.ParameterType);
var items = GetExplicitItems(it.ParameterType, explicitTypeName);
if ("Bool".Equals(explicitTypeName)) explicitTypeName = "Select"; // 布尔值 转为 可选类型
return new ExplicitData
{
IsExplicitData = it.HasDefaultValue,
Index = index,
ExplicitType = it.ParameterType,
ExplicitTypeName = explicitTypeName,
DataType = it.ParameterType,
ParameterName = it.Name,
DataValue = it.HasDefaultValue ? it.DefaultValue.ToString() : "",
Items = items.ToArray(),
};
}).ToArray();
}
private static string GetExplicitTypeName(Type type)
{
return type switch
{
Type t when t.IsEnum => "Select",
Type t when t == typeof(bool) => "Bool",
Type t when t == typeof(string) => "Value",
Type t when t == typeof(int) => "Value",
Type t when t == typeof(double) => "Value",
_ => "Value"
};
}
private static IEnumerable<string> GetExplicitItems(Type type, string explicitTypeName)
{
return explicitTypeName switch
{
"Select" => Enum.GetNames(type),
"Bool" => ["True", "False"],
_ => []
};
}
private static Delegate GenerateMethodDelegate(Type type, MethodInfo methodInfo, ParameterInfo[] parameters, Type returnType)
{
var parameterTypes = parameters.Select(p => p.ParameterType).ToArray();
var parameterCount = parameters.Length;
if (returnType == typeof(void))
{
if (parameterCount == 0)
{
// 无返回值,无参数
return ExpressionHelper.MethodCaller(type, methodInfo);
}
else
{
// 无返回值,有参数
return ExpressionHelper.MethodCaller(type, methodInfo, parameterTypes);
}
}
// else if (returnType == typeof(Task<FlipflopContext)) // 触发器
else if (FlipflopFunc.IsTaskOfFlipflop(returnType)) // 触发器
{
if (parameterCount == 0)
{
// 有返回值,无参数
return ExpressionHelper.MethodCallerAsync(type, methodInfo);
}
else
{
// 有返回值,有参数
return ExpressionHelper.MethodCallerAsync(type, methodInfo, parameterTypes);
}
}
else
{
if (parameterCount == 0)
{
// 有返回值,无参数
return ExpressionHelper.MethodCallerHaveResult(type, methodInfo);
}
else
{
// 有返回值,有参数
return ExpressionHelper.MethodCallerHaveResult(type, methodInfo, parameterTypes);
}
}
}
}
public static class DelegateGenerator
public static class MethodDetailsHelper
{
// 缓存的实例对象(键:类型名称)
public static ConcurrentDictionary<string, object> DynamicInstanceToType { get; } = new ConcurrentDictionary<string, object>();
// public static ConcurrentDictionary<string, object> DynamicInstanceToType { get; } = new ConcurrentDictionary<string, object>();
// 缓存的实例对象 (键:生成的方法名称)
// public static ConcurrentDictionary<string, object> DynamicInstance { get; } = new ConcurrentDictionary<string, object>();
/// <summary>
/// 生成方法信息
/// </summary>
/// <param name="serviceContainer"></param>
/// <param name="type"></param>
/// <returns></returns>
public static ConcurrentDictionary<string, MethodDetails> GenerateMethodDetails(ISereinIoc serviceContainer, Type type, bool isNetFramework)
public static ConcurrentDictionary<string, MethodDetails> GetDict(ISereinIoc serviceContainer, Type type, bool isNetFramework)
{
var methodDetailsDictionary = new ConcurrentDictionary<string, MethodDetails>();
var assemblyName = type.Assembly.GetName().Name;
@@ -44,7 +228,6 @@ public static class DelegateGenerator
return methodDetailsDictionary;
}
/// <summary>
/// 获取处理方法
/// </summary>

View File

@@ -0,0 +1,460 @@
using Newtonsoft.Json;
using Serein.Library.Api;
using Serein.Library.Entity;
using Serein.Library.Enums;
using Serein.NodeFlow.Tool.SerinExpression;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Serein.Library.Base
{
/// <summary>
/// 节点基类(数据):条件控件,动作控件,条件区域,动作区域
/// </summary>
// public abstract partial class NodeModelBase : IDynamicFlowNode
public static class NodeFunc
{
/// <summary>
/// 执行节点对应的方法
/// </summary>
/// <param name="context">流程上下文</param>
/// <returns>节点传回数据对象</returns>
public static object? Execute(this NodeModelBase nodeModelBase, IDynamicContext context)
{
MethodDetails md = nodeModelBase.MethodDetails;
object? result = null;
var del = md.MethodDelegate;
try
{
if (md.ExplicitDatas.Length == 0)
{
if (md.ReturnType == typeof(void))
{
((Action<object>)del).Invoke(md.ActingInstance);
}
else
{
result = ((Func<object, object>)del).Invoke(md.ActingInstance);
}
}
else
{
object?[]? parameters = nodeModelBase.GetParameters(context, md);
if (md.ReturnType == typeof(void))
{
((Action<object, object[]>)del).Invoke(md.ActingInstance, parameters);
}
else
{
result = ((Func<object, object[], object>)del).Invoke(md.ActingInstance, parameters);
}
}
return result;
}
catch (Exception ex)
{
nodeModelBase.FlowState = FlowStateType.Error;
nodeModelBase.RuningException = ex;
}
return result;
}
/// <summary>
/// 执行等待触发器的方法
/// </summary>
/// <param name="context"></param>
/// <returns>节点传回数据对象</returns>
/// <exception cref="RuningException"></exception>
public static async Task<object?> ExecuteAsync(this NodeModelBase nodeModel, IDynamicContext context)
{
MethodDetails md = nodeModel.MethodDetails;
object? result = null;
IFlipflopContext flipflopContext = null;
try
{
// 调用委托并获取结果
if (md.ExplicitDatas.Length == 0)
{
flipflopContext = await ((Func<object, Task<IFlipflopContext>>)md.MethodDelegate).Invoke(md.ActingInstance);
}
else
{
object?[]? parameters = nodeModel.GetParameters(context, md);
flipflopContext = await ((Func<object, object[], Task<IFlipflopContext>>)md.MethodDelegate).Invoke(md.ActingInstance, parameters);
}
if (flipflopContext != null)
{
nodeModel.FlowState = flipflopContext.State;
if (flipflopContext.State == FlowStateType.Succeed)
{
result = flipflopContext.Data;
}
else
{
result = null;
}
}
}
catch (Exception ex)
{
nodeModel.FlowState = FlowStateType.Error;
nodeModel.RuningException = ex;
}
return result;
}
/// <summary>
/// 开始执行
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public static async Task StartExecution(this NodeModelBase nodeModel, IDynamicContext context)
{
var cts = context.SereinIoc.GetOrInstantiate<CancellationTokenSource>();
Stack<NodeModelBase> stack = [];
stack.Push(nodeModel);
var md = nodeModel.MethodDetails;
while (stack.Count > 0 && !cts.IsCancellationRequested) // 循环中直到栈为空才会退出循环
{
// 从栈中弹出一个节点作为当前节点进行处理
var currentNode = stack.Pop();
// 设置方法执行的对象
if (currentNode.MethodDetails != null)
{
currentNode.MethodDetails.ActingInstance ??= context.SereinIoc.GetOrInstantiate(md.ActingInstanceType);
}
// 获取上游分支,首先执行一次
var upstreamNodes = currentNode.UpstreamBranch;
for (int i = upstreamNodes.Count - 1; i >= 0; i--)
{
upstreamNodes[i].PreviousNode = currentNode;
await upstreamNodes[i].StartExecution(context);
}
if (currentNode.MethodDetails != null && currentNode.MethodDetails.MethodDynamicType == NodeType.Flipflop)
{
// 触发器节点
currentNode.FlowData = await currentNode.ExecuteAsync(context);
}
else
{
// 动作节点
currentNode.FlowData = currentNode.Execute(context);
}
var nextNodes = currentNode.FlowState switch
{
FlowStateType.Succeed => currentNode.SucceedBranch,
FlowStateType.Fail => currentNode.FailBranch,
FlowStateType.Error => currentNode.ErrorBranch,
_ => throw new Exception("非预期的枚举值")
};
// 将下一个节点集合中的所有节点逆序推入栈中
for (int i = nextNodes.Count - 1; i >= 0; i--)
{
nextNodes[i].PreviousNode = currentNode;
stack.Push(nextNodes[i]);
}
}
}
/// <summary>
/// 获取对应的参数数组
/// </summary>
public static object[]? GetParameters(this NodeModelBase nodeModel, IDynamicContext context, MethodDetails md)
{
// 用正确的大小初始化参数数组
var types = md.ExplicitDatas.Select(it => it.DataType).ToArray();
if (types.Length == 0)
{
return [md.ActingInstance];
}
object[]? parameters = new object[types.Length];
for (int i = 0; i < types.Length; i++)
{
var mdEd = md.ExplicitDatas[i];
Type type = mdEd.DataType;
var f1 = nodeModel.PreviousNode?.FlowData?.GetType();
var f2 = mdEd.DataType;
if (type == typeof(IDynamicContext))
{
parameters[i] = context;
}
else if (type == typeof(MethodDetails))
{
parameters[i] = md;
}
else if (type == typeof(NodeModelBase))
{
parameters[i] = nodeModel;
}
else if (mdEd.IsExplicitData) // 显式参数
{
// 判断是否使用表达式解析
if (mdEd.DataValue[0] == '@')
{
var expResult = SerinExpressionEvaluator.Evaluate(mdEd.DataValue, nodeModel.PreviousNode?.FlowData, out bool isChange);
if (mdEd.DataType.IsEnum)
{
var enumValue = Enum.Parse(mdEd.DataType, mdEd.DataValue);
parameters[i] = enumValue;
}
else if (mdEd.ExplicitType == typeof(string))
{
parameters[i] = Convert.ChangeType(expResult, typeof(string));
}
else if (mdEd.ExplicitType == typeof(bool))
{
parameters[i] = Convert.ChangeType(expResult, typeof(bool));
}
else if (mdEd.ExplicitType == typeof(int))
{
parameters[i] = Convert.ChangeType(expResult, typeof(int));
}
else if (mdEd.ExplicitType == typeof(double))
{
parameters[i] = Convert.ChangeType(expResult, typeof(double));
}
else
{
parameters[i] = expResult;
//parameters[i] = ConvertValue(mdEd.DataValue, mdEd.ExplicitType);
}
}
else
{
if (mdEd.DataType.IsEnum)
{
var enumValue = Enum.Parse(mdEd.DataType, mdEd.DataValue);
parameters[i] = enumValue;
}
else if (mdEd.ExplicitType == typeof(string))
{
parameters[i] = mdEd.DataValue;
}
else if (mdEd.ExplicitType == typeof(bool))
{
parameters[i] = bool.Parse(mdEd.DataValue);
}
else if (mdEd.ExplicitType == typeof(int))
{
parameters[i] = int.Parse(mdEd.DataValue);
}
else if (mdEd.ExplicitType == typeof(double))
{
parameters[i] = double.Parse(mdEd.DataValue);
}
else
{
parameters[i] = "";
//parameters[i] = ConvertValue(mdEd.DataValue, mdEd.ExplicitType);
}
}
}
else if (f1 != null && f2 != null)
{
if (f2.IsAssignableFrom(f1) || f2.FullName.Equals(f1.FullName))
{
parameters[i] = nodeModel.PreviousNode?.FlowData;
}
}
else
{
var tmpParameter = nodeModel.PreviousNode?.FlowData?.ToString();
if (mdEd.DataType.IsEnum)
{
var enumValue = Enum.Parse(mdEd.DataType, tmpParameter);
parameters[i] = enumValue;
}
else if (mdEd.DataType == typeof(string))
{
parameters[i] = tmpParameter;
}
else if (mdEd.DataType == typeof(bool))
{
parameters[i] = bool.Parse(tmpParameter);
}
else if (mdEd.DataType == typeof(int))
{
parameters[i] = int.Parse(tmpParameter);
}
else if (mdEd.DataType == typeof(double))
{
parameters[i] = double.Parse(tmpParameter);
}
else
{
if (tmpParameter != null && mdEd.DataType != null)
{
parameters[i] = ConvertValue(tmpParameter, mdEd.DataType);
}
}
}
}
return parameters;
}
/// <summary>
/// json文本反序列化为对象
/// </summary>
/// <param name="value"></param>
/// <param name="targetType"></param>
/// <returns></returns>
private static dynamic? ConvertValue(string value, Type targetType)
{
try
{
if (!string.IsNullOrEmpty(value))
{
return JsonConvert.DeserializeObject(value, targetType);
}
else
{
return null;
}
}
catch (JsonReaderException ex)
{
Console.WriteLine(ex);
return value;
}
catch (JsonSerializationException ex)
{
// 如果无法转为对应的JSON对象
int startIndex = ex.Message.IndexOf("to type '") + "to type '".Length; // 查找类型信息开始的索引
int endIndex = ex.Message.IndexOf('\''); // 查找类型信息结束的索引
var typeInfo = ex.Message[startIndex..endIndex]; // 提取出错类型信息,该怎么传出去?
Console.WriteLine("无法转为对应的JSON对象:" + typeInfo);
return null;
}
catch // (Exception ex)
{
return value;
}
}
#region ExecuteAsync调用方法
//public virtual async Task<object?> ExecuteAsync(DynamicContext context)
//{
// MethodDetails md = MethodDetails;
// object? result = null;
// if (DelegateCache.GlobalDicDelegates.TryGetValue(md.MethodName, out Delegate del))
// {
// if (md.ExplicitDatas.Length == 0)
// {
// if (md.ReturnType == typeof(void))
// {
// ((Action<object>)del).Invoke(md.ActingInstance);
// }
// else if (md.ReturnType == typeof(Task<FlipflopContext>))
// {
// // 调用委托并获取结果
// FlipflopContext flipflopContext = await ((Func<object, Task<FlipflopContext>>)del).Invoke(MethodDetails.ActingInstance);
// if (flipflopContext != null)
// {
// if (flipflopContext.State == FfState.Cancel)
// {
// throw new Exception("this async task is cancel.");
// }
// else
// {
// if (flipflopContext.State == FfState.Succeed)
// {
// CurrentState = true;
// result = flipflopContext.Data;
// }
// else
// {
// CurrentState = false;
// }
// }
// }
// }
// else
// {
// result = ((Func<object, object>)del).Invoke(md.ActingInstance);
// }
// }
// else
// {
// object?[]? parameters = GetParameters(context, MethodDetails);
// if (md.ReturnType == typeof(void))
// {
// ((Action<object, object[]>)del).Invoke(md.ActingInstance, parameters);
// }
// else if (md.ReturnType == typeof(Task<FlipflopContext>))
// {
// // 调用委托并获取结果
// FlipflopContext flipflopContext = await ((Func<object, object[], Task<FlipflopContext>>)del).Invoke(MethodDetails.ActingInstance, parameters);
// if (flipflopContext != null)
// {
// if (flipflopContext.State == FfState.Cancel)
// {
// throw new Exception("取消此异步");
// }
// else
// {
// CurrentState = flipflopContext.State == FfState.Succeed;
// result = flipflopContext.Data;
// }
// }
// }
// else
// {
// result = ((Func<object, object[], object>)del).Invoke(md.ActingInstance, parameters);
// }
// }
// context.SetFlowData(result);
// }
// return result;
//}
#endregion
}
}

View File

@@ -3,6 +3,11 @@
不定期在Bilibili个人空间上更新相关的视频。
https://space.bilibili.com/33526379
# 当前任务 2024年9月12日22:32:10
1. 将运行环境从UIWPF中独立出来方便控制台程序直接运行项目文件。
2. 包装数据类型, 优化传递效率(尽可能避免拆箱、装箱)
3. 优化触发器节点(显示传出类型)
# 如何加载我的DLL
使用 **DynamicFlow** 特性标记你的类,可以参照 **MyDll****SereinWAT** 的实现。编译为 Dll文件 后,拖入到软件中即可。

View File

@@ -1,4 +1,6 @@
using Newtonsoft.Json;
using Serein.Library.Entity;
using Serein.NodeFlow;
using System.Diagnostics;
using System.Windows;
@@ -115,8 +117,10 @@ namespace Serein.WorkBench
window.Close();
}
}
public static SereinOutputFileData? FData;
/// <summary>
/// 成功加载的工程文件
/// </summary>
public static SereinOutputFileData? FData { get; set; }
public static string FileDataPath = "";
private void Application_Startup(object sender, StartupEventArgs e)
{

View File

@@ -5,7 +5,6 @@
xmlns:custom="clr-namespace:Serein.WorkBench.Node.View"
Title="Dynamic Node Flow" Height="700" Width="1200"
AllowDrop="True" Drop="Window_Drop" DragOver="Window_DragOver"
SizeChanged ="Window_SizeChanged"
Loaded="Window_Loaded"
Closing="Window_Closing">
@@ -55,9 +54,9 @@
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>-->
<custom:ExpOpNodeControl x:Name="ExpOpNodeControl" Margin="10" AllowDrop="True" Drop="ConditionRegionControl_Drop" PreviewMouseMove="BaseNodeControl_PreviewMouseMove"/>
<custom:ConditionNodeControl x:Name="ConditionNodeControl" Margin="10" AllowDrop="True" Drop="ConditionNodeControl_Drop" PreviewMouseMove="BaseNodeControl_PreviewMouseMove"/>
<custom:ConditionRegionControl x:Name="ConditionRegionControl" Margin="10" AllowDrop="True" Drop="ConditionRegionControl_Drop" PreviewMouseMove="RegionControl_PreviewMouseMove"/>
<custom:ExpOpNodeControl x:Name="ExpOpNodeControl" Margin="10" AllowDrop="True" PreviewMouseMove="BaseNodeControl_PreviewMouseMove"/>
<custom:ConditionNodeControl x:Name="ConditionNodeControl" Margin="10" AllowDrop="True" PreviewMouseMove="BaseNodeControl_PreviewMouseMove"/>
<custom:ConditionRegionControl x:Name="ConditionRegionControl" Margin="10" AllowDrop="True" PreviewMouseMove="BaseNodeControl_PreviewMouseMove"/>
<!--<custom:ActionRegionControl x:Name="ActionRegionControl" Grid.Column="1" Margin="10" AllowDrop="True" Drop="ActionRegionControl_Drop" PreviewMouseMove="RegionControl_PreviewMouseMove"/>-->
<!--<TextBlock Text="触发器" Grid.Column="2"/>-->
<!--<custom:StateRegionControl x:Name="StateRegionControl" Grid.Column="2" Margin="10" AllowDrop="True" Drop="StateRegionControl_Drop" PreviewMouseMove="RegionControl_PreviewMouseMove"/>-->

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,81 @@
using Serein.Library.Attributes;
using Serein.Library.Entity;
using Serein.Library.Utils;
using Serein.NodeFlow;
using Serein.NodeFlow.Tool;
using Serein.WorkBench.Node.View;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace Serein.WorkBench
{
public class MainWindowViewModel
{
private readonly MainWindow window ;
public MainWindowViewModel(MainWindow window)
{
FlowEnvironment = new FlowEnvironment();
this.window = window;
}
public FlowEnvironment FlowEnvironment { get; set; }
#region
public void LoadProjectFile(SereinOutputFileData projectFile)
{
var dllPaths = projectFile.Librarys.Select(it => it.Path).ToList();
foreach (var dll in dllPaths)
{
var filePath = System.IO.Path.GetFullPath(System.IO.Path.Combine(App.FileDataPath, dll));
//LoadAssembly(filePath);
}
}
private void DisplayControlDll(Assembly assembly,
List<MethodDetails> conditionTypes,
List<MethodDetails> actionTypes,
List<MethodDetails> flipflopMethods)
{
var dllControl = new DllControl
{
Header = "DLL name : " + assembly.GetName().Name // 设置控件标题为程序集名称
};
foreach (var item in actionTypes)
{
dllControl.AddAction(item.Clone()); // 添加动作类型到控件
}
foreach (var item in flipflopMethods)
{
dllControl.AddFlipflop(item.Clone()); // 添加触发器方法到控件
}
/*foreach (var item in stateTypes)
{
dllControl.AddState(item);
}*/
window.DllStackPanel.Children.Add(dllControl); // 将控件添加到界面上显示
}
#endregion
}
}

View File

@@ -1,4 +1,5 @@
using Serein.NodeFlow.Model;
using Serein.NodeFlow;
using Serein.NodeFlow.Model;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
@@ -107,8 +108,19 @@ namespace Serein.WorkBench.Node.View
{
if (sender is TextBlock typeText)
{
var dragData = new DataObject(MouseNodeType.RegionType, typeText.Tag);
MoveNodeData moveNodeData = new MoveNodeData
{
NodeControlType = Library.Enums.NodeControlType.ConditionRegion
};
// 创建一个 DataObject 用于拖拽操作,并设置拖拽效果
DataObject dragData = new DataObject(MouseNodeType.CreateDllNodeInCanvas, moveNodeData);
DragDrop.DoDragDrop(typeText, dragData, DragDropEffects.Move);
//var dragData = new DataObject(MouseNodeType.CreateNodeInCanvas, typeText.Tag);
//DragDrop.DoDragDrop(typeText, dragData, DragDropEffects.Move);
}
}
}

View File

@@ -1,5 +1,8 @@
using Serein.NodeFlow;
using Serein.Library.Entity;
using Serein.Library.Enums;
using Serein.NodeFlow;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Input;
@@ -115,12 +118,26 @@ namespace Serein.WorkBench.Node.View
{
// 获取触发事件的 TextBlock
TextBlock typeText = sender as TextBlock;
if (typeText != null)
if (sender is TextBlock typeText && typeText.Tag is MethodDetails md)
{
MoveNodeData moveNodeData = new MoveNodeData
{
NodeControlType = md.MethodDynamicType switch
{
NodeType.Action => NodeControlType.Action,
NodeType.Flipflop => NodeControlType.Flipflop,
_ => NodeControlType.None,
},
MethodDetails = md,
};
if(moveNodeData.NodeControlType == NodeControlType.None)
{
return;
}
// 创建一个 DataObject 用于拖拽操作,并设置拖拽效果
DataObject dragData = new DataObject(MouseNodeType.DllNodeType, typeText.Tag);
DataObject dragData = new DataObject(MouseNodeType.CreateDllNodeInCanvas, moveNodeData);
DragDrop.DoDragDrop(typeText, dragData, DragDropEffects.Move);
}
}

View File

@@ -1,5 +1,6 @@
using Serein.NodeFlow;
using Serein.NodeFlow.Model;
using Serein.Library.Api;
using Serein.Library.Entity;
using Serein.NodeFlow.Base;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
@@ -34,7 +35,7 @@ namespace Serein.WorkBench.Node.View
public abstract class NodeControlViewModelBase : INotifyPropertyChanged
{
public NodeControlViewModelBase(NodeBase node)
public NodeControlViewModelBase(NodeModelBase node)
{
this.Node = node;
MethodDetails = this.Node.MethodDetails;
@@ -43,7 +44,7 @@ namespace Serein.WorkBench.Node.View
/// <summary>
/// 对应的节点实体类
/// </summary>
public NodeBase Node { get; set; }
public NodeModelBase Node { get; }
/// <summary>
/// 表示节点控件是否被选中
@@ -63,13 +64,7 @@ namespace Serein.WorkBench.Node.View
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{

View File

@@ -1,4 +1,5 @@
using Serein.NodeFlow;
using Serein.Library.Entity;
using Serein.NodeFlow;
using System.Collections;
using System.Globalization;
using System.Windows;