重构了底层,方便向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

@@ -1,13 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Serein.NodeFlow
{
public interface IDynamicFlowNode
{
}
}

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

@@ -0,0 +1,189 @@
using Serein.Library.Api;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Serein.NodeFlow
{
/* /// <summary>
/// 输出文件
/// </summary>
public class SereinOutputFileData
{
/// <summary>
/// 基础
/// </summary>
public Basic basic { get; set; }
/// <summary>
/// 依赖的DLL
/// </summary>
public Library[] library { 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 string tips { get; set; }
}
/// <summary>
/// 节点
/// </summary>
public class NodeInfo
{
/// <summary>
/// GUID
/// </summary>
public string guid { get; set; }
/// <summary>
/// 名称
/// </summary>
public string name { get; set; }
/// <summary>
/// 显示标签
/// </summary>
public string label { get; set; }
/// <summary>
/// 类型
/// </summary>
public string type { get; set; }
/// <summary>
/// 于画布中的位置
/// </summary>
public Position position { get; set; }
/// <summary>
/// 真分支节点GUID
/// </summary>
public string[] trueNodes { get; set; }
/// <summary>
/// 假分支节点
/// </summary>
public string[] falseNodes { get; set; }
public string[] upstreamNodes { get; set; }
public Parameterdata[] parameterData { 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

@@ -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
}
}