忘记改啥了*1

This commit is contained in:
fengjiayi
2024-11-02 16:48:40 +08:00
parent 0088d32f12
commit cd1642dcf7
45 changed files with 1022 additions and 447 deletions

View File

@@ -2,13 +2,13 @@
using Serein.Library.Utils; using Serein.Library.Utils;
using System.Collections.Concurrent; using System.Collections.Concurrent;
namespace Serein.Library.Core.NodeFlow namespace Serein.Library.Core
{ {
/// <summary> /// <summary>
/// 动态流程上下文 /// 动态流程上下文
/// </summary> /// </summary>
public class DynamicContext: IDynamicContext public class DynamicContext : IDynamicContext
{ {
/// <summary> /// <summary>
/// 动态流程上下文 /// 动态流程上下文
@@ -30,6 +30,11 @@ namespace Serein.Library.Core.NodeFlow
/// </summary> /// </summary>
public RunState RunState { get; set; } = RunState.NoStart; public RunState RunState { get; set; } = RunState.NoStart;
/// <summary>
/// 用来在当前流程上下文间传递数据
/// </summary>
public Dictionary<string, object> ContextShareData { get; } = new Dictionary<string, object>();
/// <summary> /// <summary>
/// 当前节点执行完成后,设置该属性,让运行环境判断接下来要执行哪个分支的节点。 /// 当前节点执行完成后,设置该属性,让运行环境判断接下来要执行哪个分支的节点。
/// </summary> /// </summary>
@@ -52,7 +57,7 @@ namespace Serein.Library.Core.NodeFlow
/// <param name="PreviousNode">上一节点</param> /// <param name="PreviousNode">上一节点</param>
public void SetPreviousNode(NodeModelBase currentNodeModel, NodeModelBase PreviousNode) public void SetPreviousNode(NodeModelBase currentNodeModel, NodeModelBase PreviousNode)
{ {
dictPreviousNodes.AddOrUpdate(currentNodeModel, (_)=> PreviousNode, (_,_) => PreviousNode); dictPreviousNodes.AddOrUpdate(currentNodeModel, (_) => PreviousNode, (_, _) => PreviousNode);
} }
/// <summary> /// <summary>
@@ -80,7 +85,7 @@ namespace Serein.Library.Core.NodeFlow
/// <returns></returns> /// <returns></returns>
public object? GetFlowData(string nodeGuid) public object? GetFlowData(string nodeGuid)
{ {
if(dictNodeFlowData.TryGetValue(nodeGuid, out var data)) if (dictNodeFlowData.TryGetValue(nodeGuid, out var data))
{ {
return data; return data;
} }
@@ -98,7 +103,7 @@ namespace Serein.Library.Core.NodeFlow
public void AddOrUpdate(string nodeGuid, object? flowData) public void AddOrUpdate(string nodeGuid, object? flowData)
{ {
// this.dictNodeFlowData.TryGetValue(nodeGuid, out var oldFlowData); // this.dictNodeFlowData.TryGetValue(nodeGuid, out var oldFlowData);
this.dictNodeFlowData.AddOrUpdate(nodeGuid, _ => flowData, (_, _) => flowData); dictNodeFlowData.AddOrUpdate(nodeGuid, _ => flowData, (_, _) => flowData);
} }
/// <summary> /// <summary>
@@ -109,11 +114,11 @@ namespace Serein.Library.Core.NodeFlow
{ {
if (dictPreviousNodes.TryGetValue(nodeModel, out var previousNode)) // 首先获取当前节点的上一节点 if (dictPreviousNodes.TryGetValue(nodeModel, out var previousNode)) // 首先获取当前节点的上一节点
{ {
if (dictNodeFlowData.TryGetValue(previousNode.Guid, out var data)) // 其次获取上一节点的数据 if (dictNodeFlowData.TryGetValue(previousNode.Guid, out var data)) // 其次获取上一节点的数据
{ {
return data; return data;
//AddOrUpdate(nodeModel.Guid, data); // 然后作为当前节点的数据记录在上下文中 //AddOrUpdate(nodeModel.Guid, data); // 然后作为当前节点的数据记录在上下文中
} }
} }
return null; return null;
} }
@@ -134,7 +139,22 @@ namespace Serein.Library.Core.NodeFlow
} }
} }
} }
foreach (var nodeObj in ContextShareData.Values)
{
if (nodeObj is null)
{
continue;
}
else
{
if (typeof(IDisposable).IsAssignableFrom(nodeObj?.GetType()) && nodeObj is IDisposable disposable)
{
disposable?.Dispose();
}
}
}
this.dictNodeFlowData?.Clear(); this.dictNodeFlowData?.Clear();
this.ContextShareData?.Clear();
RunState = RunState.Completion; RunState = RunState.Completion;
} }

View File

@@ -1,6 +1,6 @@
using Serein.Library.Api; using Serein.Library.Api;
namespace Serein.Library.Core.NodeFlow namespace Serein.Library.Core
{ {
public static class FlipflopFunc public static class FlipflopFunc
{ {
@@ -56,7 +56,7 @@ namespace Serein.Library.Core.NodeFlow
//if (innerType == typeof(IFlipflopContext)) //if (innerType == typeof(IFlipflopContext))
//if (innerType.IsGenericType && innerType.GetGenericTypeDefinition() == typeof(FlipflopContext<>)) //if (innerType.IsGenericType && innerType.GetGenericTypeDefinition() == typeof(FlipflopContext<>))
//{ //{
//return true; //return true;
//} //}
} }

View File

@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<Version>1.0.15</Version> <Version>1.0.16</Version>
<TargetFramework>net8.0</TargetFramework> <TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
@@ -23,7 +23,6 @@
<Compile Remove="Flow\**" /> <Compile Remove="Flow\**" />
<Compile Remove="Http\**" /> <Compile Remove="Http\**" />
<Compile Remove="IOC\**" /> <Compile Remove="IOC\**" />
<Compile Remove="NodeFlow\Tool\**" />
<Compile Remove="obj\**" /> <Compile Remove="obj\**" />
<Compile Remove="SerinExpression\**" /> <Compile Remove="SerinExpression\**" />
<Compile Remove="Tool\**" /> <Compile Remove="Tool\**" />
@@ -31,7 +30,6 @@
<EmbeddedResource Remove="Flow\**" /> <EmbeddedResource Remove="Flow\**" />
<EmbeddedResource Remove="Http\**" /> <EmbeddedResource Remove="Http\**" />
<EmbeddedResource Remove="IOC\**" /> <EmbeddedResource Remove="IOC\**" />
<EmbeddedResource Remove="NodeFlow\Tool\**" />
<EmbeddedResource Remove="obj\**" /> <EmbeddedResource Remove="obj\**" />
<EmbeddedResource Remove="SerinExpression\**" /> <EmbeddedResource Remove="SerinExpression\**" />
<EmbeddedResource Remove="Tool\**" /> <EmbeddedResource Remove="Tool\**" />
@@ -39,15 +37,12 @@
<None Remove="Flow\**" /> <None Remove="Flow\**" />
<None Remove="Http\**" /> <None Remove="Http\**" />
<None Remove="IOC\**" /> <None Remove="IOC\**" />
<None Remove="NodeFlow\Tool\**" />
<None Remove="obj\**" /> <None Remove="obj\**" />
<None Remove="SerinExpression\**" /> <None Remove="SerinExpression\**" />
<None Remove="Tool\**" /> <None Remove="Tool\**" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Remove="NodeFlow\DynamicNodeCoreType.cs" />
<Compile Remove="NodeFlow\FlowStateType.cs" />
<Compile Remove="ServiceContainer.cs" /> <Compile Remove="ServiceContainer.cs" />
</ItemGroup> </ItemGroup>

View File

@@ -1,6 +1,7 @@
using Serein.Library.Api; using Serein.Library.Api;
using System; using System;
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Collections.Generic;
namespace Serein.Library.Framework.NodeFlow namespace Serein.Library.Framework.NodeFlow
{ {
@@ -29,6 +30,11 @@ namespace Serein.Library.Framework.NodeFlow
/// </summary> /// </summary>
public RunState RunState { get; set; } = RunState.NoStart; public RunState RunState { get; set; } = RunState.NoStart;
/// <summary>
/// 用来在当前流程上下文间传递数据
/// </summary>
public Dictionary<string, object> ContextShareData { get; } = new Dictionary<string, object>();
/// <summary> /// <summary>
/// 当前节点执行完成后,设置该属性,让运行环境判断接下来要执行哪个分支的节点。 /// 当前节点执行完成后,设置该属性,让运行环境判断接下来要执行哪个分支的节点。
/// </summary> /// </summary>
@@ -132,7 +138,22 @@ namespace Serein.Library.Framework.NodeFlow
} }
} }
} }
foreach (var nodeObj in ContextShareData.Values)
{
if (nodeObj is null)
{
continue;
}
else
{
if (typeof(IDisposable).IsAssignableFrom(nodeObj?.GetType()) && nodeObj is IDisposable disposable)
{
disposable?.Dispose();
}
}
}
this.dictNodeFlowData?.Clear(); this.dictNodeFlowData?.Clear();
this.ContextShareData?.Clear();
RunState = RunState.Completion; RunState = RunState.Completion;
} }
// public NodeRunCts NodeRunCts { get; set; } // public NodeRunCts NodeRunCts { get; set; }

View File

@@ -50,8 +50,8 @@
<Reference Include="System.Xml" /> <Reference Include="System.Xml" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Include="NodeFlow\FlipflopContext.cs" /> <Compile Include="FlipflopContext.cs" />
<Compile Include="NodeFlow\DynamicContext.cs" /> <Compile Include="DynamicContext.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<packages> <packages>
<package id="Newtonsoft.Json" version="13.0.3" targetFramework="net45" /> <package id="Newtonsoft.Json" version="13.0.3" targetFramework="net462" />
<package id="System.ValueTuple" version="4.5.0" targetFramework="net461" /> <package id="System.ValueTuple" version="4.5.0" targetFramework="net461" />
</packages> </packages>

View File

@@ -1,6 +1,7 @@
using Serein.Library; using Serein.Library;
using Serein.Library.Utils; using Serein.Library.Utils;
using System; using System;
using System.Collections.Generic;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace Serein.Library.Api namespace Serein.Library.Api
@@ -20,6 +21,11 @@ namespace Serein.Library.Api
/// </summary> /// </summary>
RunState RunState { get; } RunState RunState { get; }
/// <summary>
/// 用来在当前流程上下文间传递数据
/// </summary>
Dictionary<string, object> ContextShareData { get; }
/// <summary> /// <summary>
/// 下一个要执行的节点类别 /// 下一个要执行的节点类别
/// </summary> /// </summary>
@@ -52,7 +58,6 @@ namespace Serein.Library.Api
/// <param name="nodeModel"></param> /// <param name="nodeModel"></param>
object TransmissionData(NodeModelBase nodeModel); object TransmissionData(NodeModelBase nodeModel);
/// <summary> /// <summary>
/// 添加或更新当前节点的数据 /// 添加或更新当前节点的数据
/// </summary> /// </summary>
@@ -61,11 +66,13 @@ namespace Serein.Library.Api
void AddOrUpdate(string nodeGuid, object flowData); void AddOrUpdate(string nodeGuid, object flowData);
/// <summary> /// <summary>
/// 用以提前结束分支运行 /// 用以提前结束当前上下文流程的运行
/// </summary> /// </summary>
void Exit(); void Exit();
/*/// <summary> /*/// <summary>
/// 定时循环触发 /// 定时循环触发
/// </summary> /// </summary>

View File

@@ -619,7 +619,7 @@ namespace Serein.Library.Api
event EnvOutHandler OnEnvOut; event EnvOutHandler OnEnvOut;
#endregion #endregion
#region #region
/// <summary> /// <summary>
/// 设置输出 /// 设置输出
@@ -891,6 +891,24 @@ namespace Serein.Library.Api
void TriggerInterrupt(string nodeGuid, string expression, InterruptTriggerEventArgs.InterruptTriggerType type); void TriggerInterrupt(string nodeGuid, string expression, InterruptTriggerEventArgs.InterruptTriggerType type);
#endregion
#region
/// <summary>
/// 运行时加载
/// </summary>
/// <param name="file">文件名</param>
/// <returns></returns>
bool LoadNativeLibraryOfRuning(string file);
/// <summary>
/// 运行时加载指定目录下的类库
/// </summary>
/// <param name="path">目录</param>
/// <param name="isRecurrence">是否递归加载</param>
void LoadAllNativeLibraryOfRuning(string path, bool isRecurrence = true);
#endregion #endregion
#region UI视觉 #region UI视觉

View File

@@ -64,13 +64,20 @@ namespace Serein.Library
[PropertyInfo] [PropertyInfo]
private string _methodAnotherName; private string _methodAnotherName;
/// <summary> /// <summary>
/// 参数描述 /// 参数描述
/// </summary> /// </summary>
[PropertyInfo] [PropertyInfo]
private ParameterDetails[] _parameterDetailss; private ParameterDetails[] _parameterDetailss;
/// <summary>
/// <para>描述该方法是否存在可选参数</para>
/// <para>-1表示不存在</para>
/// <para>0表示第一个参数是可选参数</para>
/// </summary>
[PropertyInfo]
private int _isParamsArgIndex = -1;
/// <summary> /// <summary>
/// 出参类型 /// 出参类型
/// </summary> /// </summary>
@@ -81,6 +88,83 @@ namespace Serein.Library
public partial class MethodDetails public partial class MethodDetails
{ {
#region
/// <summary>
/// 新增可选参数
/// </summary>
/// <param name="index"></param>
public void AddParamsArg(int index = 0)
{
if (IsParamsArgIndex >= 0 // 方法是否包含可选参数
&& index >= 0 // 如果包含,则判断从哪个参数赋值
&& index >= IsParamsArgIndex // 需要判断是否为可选参数的部分
&& index < ParameterDetailss.Length) // 防止下标越界
{
var newPd = ParameterDetailss[index].CloneOfModel(this.NodeModel); // 复制出属于本身节点的参数描述
newPd.Index = ParameterDetailss.Length; // 更新索引
newPd.IsParams = true;
ParameterDetailss = AddToArray(ParameterDetailss, newPd); // 新增
}
}
/// <summary>
/// 移除可选参数
/// </summary>
/// <param name="index"></param>
public void RemoveParamsArg(int index = 0)
{
if (IsParamsArgIndex >= 0 // 方法是否包含可选参数
&& index >= 0 // 如果包含,则判断从哪个参数赋值
&& index >= IsParamsArgIndex // 需要判断是否为可选参数的部分
&& index < ParameterDetailss.Length) // 防止下标越界
{
//var newPd = ParameterDetailss[index].CloneOfModel(this.NodeModel); // 复制出属于本身节点的参数描述
//newPd.Index = ParameterDetailss.Length; // 更新索引
ParameterDetailss[index] = null; // 释放对象引用
ParameterDetailss = RemoteToArray(ParameterDetailss, index); // 新增
}
}
public static T[] AddToArray<T>(T[] original, T newObject)
{
// 创建一个新数组比原数组大1
T[] newArray = new T[original.Length + 1];
// 复制原数组的元素
for (int i = 0; i < original.Length; i++)
{
newArray[i] = original[i];
}
// 将新对象放在最后一位
newArray[newArray.Length - 1] = newObject;
return newArray;
}
public static T[] RemoteToArray<T>(T[] original, int index)
{
if(index == 0)
{
return new T[0];
}
// 创建一个新数组比原数组小1
T[] newArray = new T[original.Length - 1];
for (int i = 0; i < index; i++)
{
newArray[i] = original[i];
}
for (int i = index; i < newArray.Length; i++)
{
newArray[i] = original[i+1];
}
return newArray;
}
#endregion
/// <summary> /// <summary>
/// 不包含方法信息的基础节点后续可能要改为DLL引入基础节点 /// 不包含方法信息的基础节点后续可能要改为DLL引入基础节点
/// </summary> /// </summary>
@@ -91,9 +175,8 @@ namespace Serein.Library
/// <summary> /// <summary>
/// 生成元数据 /// 生成元数据
/// </summary> /// </summary>
/// <param name="env">节点运行的环境</param>
/// <param name="nodeModel">标识属于哪个节点</param> /// <param name="nodeModel">标识属于哪个节点</param>
public MethodDetails(IFlowEnvironment env, NodeModelBase nodeModel) public MethodDetails(NodeModelBase nodeModel)
{ {
NodeModel = nodeModel; NodeModel = nodeModel;
} }
@@ -114,6 +197,7 @@ namespace Serein.Library
MethodDynamicType = nodeType; MethodDynamicType = nodeType;
ReturnType = Type.GetType(Info.ReturnTypeFullName); ReturnType = Type.GetType(Info.ReturnTypeFullName);
ParameterDetailss = Info.ParameterDetailsInfos.Select(pinfo => new ParameterDetails(pinfo)).ToArray(); ParameterDetailss = Info.ParameterDetailsInfos.Select(pinfo => new ParameterDetails(pinfo)).ToArray();
IsParamsArgIndex = Info.IsParamsArgIndex;
} }
/// <summary> /// <summary>
@@ -122,25 +206,25 @@ namespace Serein.Library
/// <returns></returns> /// <returns></returns>
public MethodDetailsInfo ToInfo() public MethodDetailsInfo ToInfo()
{ {
return new MethodDetailsInfo return new MethodDetailsInfo
{ {
MethodName = MethodName, MethodName = this.MethodName,
MethodAnotherName = MethodAnotherName, MethodAnotherName = this.MethodAnotherName,
NodeType = MethodDynamicType.ToString(), NodeType = this.MethodDynamicType.ToString(),
ParameterDetailsInfos = ParameterDetailss.Select(p => p.ToInfo()).ToArray(), ParameterDetailsInfos = this.ParameterDetailss.Select(p => p.ToInfo()).ToArray(),
ReturnTypeFullName = ReturnType.FullName, ReturnTypeFullName = this.ReturnType.FullName,
IsParamsArgIndex = this.IsParamsArgIndex,
}; };
} }
/// <summary> /// <summary>
/// 从DLL拖动出来时拷贝属于节点的实例 /// 从DLL拖动出来时,从元数据拷贝新的实例,作为属于节点独享的方法描述
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
public MethodDetails CloneOfNode(IFlowEnvironment env, NodeModelBase nodeModel) public MethodDetails CloneOfNode( NodeModelBase nodeModel)
{ {
var md = new MethodDetails(env, nodeModel) // 创建新节点时拷贝实例 // this => 是元数据
var md = new MethodDetails( nodeModel) // 创建新节点时拷贝实例
{ {
ActingInstance = this.ActingInstance, ActingInstance = this.ActingInstance,
ActingInstanceType = this.ActingInstanceType, ActingInstanceType = this.ActingInstanceType,
@@ -150,8 +234,9 @@ namespace Serein.Library
MethodName = this.MethodName, MethodName = this.MethodName,
MethodLockName = this.MethodLockName, MethodLockName = this.MethodLockName,
IsProtectionParameter = this.IsProtectionParameter, IsProtectionParameter = this.IsProtectionParameter,
IsParamsArgIndex= this.IsParamsArgIndex,
}; };
md.ParameterDetailss = this.ParameterDetailss?.Select(p => p?.CloneOfClone(env, nodeModel)).ToArray(); // 拷贝属于节点方法的新入参描述 md.ParameterDetailss = this.ParameterDetailss?.Select(p => p?.CloneOfModel(nodeModel)).ToArray(); // 拷贝属于节点方法的新入参描述
return md; return md;
} }
@@ -163,71 +248,16 @@ namespace Serein.Library
sb.AppendLine($"需要实例:{this.ActingInstanceType?.FullName}"); sb.AppendLine($"需要实例:{this.ActingInstanceType?.FullName}");
sb.AppendLine($""); sb.AppendLine($"");
sb.AppendLine($"入参参数信息:"); sb.AppendLine($"入参参数信息:");
foreach (var arg in this.ParameterDetailss) for (int i = 0; i < ParameterDetailss.Length; i++)
{ {
sb.AppendLine($" {arg.ToString()}"); ParameterDetails arg = this.ParameterDetailss[i];
} }
sb.AppendLine($""); sb.AppendLine($"");
sb.AppendLine($"返回值信息:"); sb.AppendLine($"返回值信息:");
sb.AppendLine($" {this.ReturnType.FullName}"); sb.AppendLine($" {this.ReturnType?.FullName}");
return sb.ToString(); return sb.ToString();
} }
///// <summary>
///// 每个节点有独自的MethodDetails实例
///// </summary>
//public partial class TmpMethodDetails
//{
// /// <summary>
// /// 是否保护参数(目前仅视觉效果参数,不影响运行实现,后续将设置作用在运行逻辑中)
// /// </summary>
// public bool IsProtectionParameter { get; set; } = false;
// /// <summary>
// /// 作用实例的类型(多个相同的节点将拥有相同的类型)
// /// </summary>
// public Type ActingInstanceType { get; set; }
// /// <summary>
// /// 作用实例(多个相同的节点将会共享同一个实例)
// /// </summary>
// public object ActingInstance { get; set; }
// /// <summary>
// /// 方法名称
// /// </summary>
// public string MethodName { 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 ParameterDetails[] ParameterDetailss { get; set; }
// /// <summary>
// /// 出参类型
// /// </summary>
// public Type ReturnType { get; set; }
//}
} }
} }

View File

@@ -37,6 +37,11 @@ namespace Serein.Library
public ParameterDetailsInfo[] ParameterDetailsInfos { get; set; } public ParameterDetailsInfo[] ParameterDetailsInfos { get; set; }
/// <summary>
/// 可选参数信息
/// </summary>
public int IsParamsArgIndex { get; set; }
/// <summary> /// <summary>
/// 出参类型 /// 出参类型
/// </summary> /// </summary>

View File

@@ -87,9 +87,9 @@ namespace Serein.Library
public abstract partial class NodeModelBase : IDynamicFlowNode public abstract partial class NodeModelBase : IDynamicFlowNode
{ {
/// <summary> /// <summary>
/// 加载完成后调用的方法 /// 实体节点创建完成后调用的方法,调用时间早于 LoadInfo() 方法
/// </summary> /// </summary>
public abstract void OnLoading(); public abstract void OnCreating();
public NodeModelBase(IFlowEnvironment environment) public NodeModelBase(IFlowEnvironment environment)
{ {

View File

@@ -80,16 +80,43 @@ namespace Serein.Library
this.Position = nodeInfo.Position;// 加载位置信息 this.Position = nodeInfo.Position;// 加载位置信息
if (this.MethodDetails != null) if (this.MethodDetails != null)
{ {
for (int i = 0; i < nodeInfo.ParameterData.Length; i++) if(this.MethodDetails.ParameterDetailss is null)
{ {
var mdPd = this.MethodDetails.ParameterDetailss[i]; this.MethodDetails.ParameterDetailss = new ParameterDetails[nodeInfo.ParameterData.Length];
ParameterData pd = nodeInfo.ParameterData[i]; this.MethodDetails.ParameterDetailss = nodeInfo.ParameterData.Select((pd,index) =>
mdPd.IsExplicitData = pd.State; {
mdPd.DataValue = pd.Value; return new ParameterDetails()
mdPd.ArgDataSourceType = EnumHelper.ConvertEnum<ConnectionArgSourceType>(pd.SourceType); {
mdPd.ArgDataSourceNodeGuid = pd.SourceNodeGuid; Index = index,
NodeModel = this,
DataType = typeof(object),
ExplicitType = typeof(object),
Name = string.Empty,
ExplicitTypeName = "Value",
IsExplicitData = pd.State,
DataValue = pd.Value,
ArgDataSourceType = EnumHelper.ConvertEnum<ConnectionArgSourceType>(pd.SourceType),
ArgDataSourceNodeGuid = pd.SourceNodeGuid,
};
}).ToArray();
} }
else
{
for (int i = 0; i < nodeInfo.ParameterData.Length; i++)
{
var mdPd = this.MethodDetails.ParameterDetailss[i];
ParameterData pd = nodeInfo.ParameterData[i];
mdPd.IsExplicitData = pd.State;
mdPd.DataValue = pd.Value;
mdPd.ArgDataSourceType = EnumHelper.ConvertEnum<ConnectionArgSourceType>(pd.SourceType);
mdPd.ArgDataSourceNodeGuid = pd.SourceNodeGuid;
}
}
} }
return this; return this;
} }
@@ -160,7 +187,7 @@ namespace Serein.Library
// 从栈中弹出一个节点作为当前节点进行处理 // 从栈中弹出一个节点作为当前节点进行处理
var currentNode = stack.Pop(); var currentNode = stack.Pop();
#if false
// 筛选出上游分支 // 筛选出上游分支
var upstreamNodes = currentNode.SuccessorNodes[ConnectionInvokeType.Upstream].ToArray(); var upstreamNodes = currentNode.SuccessorNodes[ConnectionInvokeType.Upstream].ToArray();
for (int index = 0; index < upstreamNodes.Length; index++) for (int index = 0; index < upstreamNodes.Length; index++)
@@ -184,32 +211,63 @@ namespace Serein.Library
} }
} }
} }
#endif
// 上游分支执行完成,才执行当前节点 // 上游分支执行完成,才执行当前节点
if (IsBradk(context, flowCts)) break; // 退出执行 if (IsBradk(context, flowCts)) break; // 退出执行
context.NextOrientation = ConnectionInvokeType.None; // 重置上下文状态 context.NextOrientation = ConnectionInvokeType.None; // 重置上下文状态
object newFlowData = await currentNode.ExecutingAsync(context);
if (IsBradk(context, flowCts)) break; // 退出执行 object newFlowData;
try
{
if (IsBradk(context, flowCts)) break; // 退出执行
newFlowData = await currentNode.ExecutingAsync(context);
if (IsBradk(context, flowCts)) break; // 退出执行
if (context.NextOrientation == ConnectionInvokeType.None) // 没有手动设置时,进行自动设置
{
context.NextOrientation = ConnectionInvokeType.IsSucceed;
}
}
catch (Exception ex)
{
newFlowData = null;
await Console.Out.WriteLineAsync($"节点[{this.MethodDetails?.MethodName}]异常:" + ex);
context.NextOrientation = ConnectionInvokeType.IsError;
currentNode.RuningException = ex;
}
await RefreshFlowDataAndExpInterrupt(context, currentNode, newFlowData); // 执行当前节点后刷新数据 await RefreshFlowDataAndExpInterrupt(context, currentNode, newFlowData); // 执行当前节点后刷新数据
#endregion #endregion
#region #region
// 选择后继分支
var nextNodes = currentNode.SuccessorNodes[context.NextOrientation];
// 将下一个节点集合中的所有节点逆序推入栈中
for (int i = nextNodes.Count - 1; i >= 0; i--)
// 首先将指定类别后继分支的所有节点逆序推入栈中
var nextNodes = currentNode.SuccessorNodes[context.NextOrientation];
for (int index = nextNodes.Count - 1; index >= 0; index--)
{ {
// 筛选出启用的节点的节点 // 筛选出启用的节点的节点
if (nextNodes[i].DebugSetting.IsEnable) if (nextNodes[index].DebugSetting.IsEnable)
{ {
context.SetPreviousNode(nextNodes[i], currentNode); context.SetPreviousNode(nextNodes[index], currentNode);
stack.Push(nextNodes[i]); stack.Push(nextNodes[index]);
}
}
// 然后将指上游分支的所有节点逆序推入栈中
var upstreamNodes = currentNode.SuccessorNodes[ConnectionInvokeType.Upstream];
for (int index = upstreamNodes.Count - 1; index >= 0; index--)
{
// 筛选出启用的节点的节点
if (upstreamNodes[index].DebugSetting.IsEnable)
{
context.SetPreviousNode(upstreamNodes[index], currentNode);
stack.Push(upstreamNodes[index]);
} }
} }
#endregion #endregion
} }
@@ -245,73 +303,20 @@ namespace Serein.Library
{ {
md.ActingInstance = context.Env.IOC.Get(md.ActingInstanceType); md.ActingInstance = context.Env.IOC.Get(md.ActingInstanceType);
} }
try
{
object[] args = await GetParametersAsync(context, this, md);
var result = await dd.InvokeAsync(md.ActingInstance, args);
if(context.NextOrientation == ConnectionInvokeType.None) // 没有手动设置时,进行自动设置
{
context.NextOrientation = ConnectionInvokeType.IsSucceed;
}
return result;
}
catch (Exception ex)
{
await Console.Out.WriteLineAsync($"节点[{this.MethodDetails?.MethodName}]异常:" + ex);
context.NextOrientation = ConnectionInvokeType.IsError;
RuningException = ex;
return null;
}
}
/// <summary> object[] args = await GetParametersAsync(context, this, md);
/// 执行单个节点对应的方法,并不做状态检查 var result = await dd.InvokeAsync(md.ActingInstance, args);
/// </summary> return result;
/// <param name="context">运行时上下文</param>
/// <returns></returns>
public virtual async Task<object> InvokeAsync(IDynamicContext context)
{
try
{
MethodDetails md = MethodDetails;
if (md is null)
{
throw new Exception($"不存在方法信息{md.MethodName}");
}
if (!Env.TryGetDelegateDetails(md.MethodName, out var dd))
{
throw new Exception($"不存在对应委托{md.MethodName}");
}
if (md.ActingInstance is null)
{
md.ActingInstance = Env.IOC.Get(md.ActingInstanceType);
if (md.ActingInstance is null)
{
md.ActingInstance = Env.IOC.Instantiate(md.ActingInstanceType);
if (md.ActingInstance is null)
{
throw new Exception($"无法创建相应的实例{md.ActingInstanceType.FullName}");
}
}
}
object[] args = await GetParametersAsync(context, this, md);
var result = await dd.InvokeAsync(md.ActingInstance, args);
return result;
}
catch (Exception ex)
{
await Console.Out.WriteLineAsync($"节点[{this.MethodDetails?.MethodName}]异常:" + ex);
return null;
}
} }
/// <summary> /// <summary>
/// 获取对应的参数数组 /// 获取对应的参数数组
/// </summary> /// </summary>
public static async Task<object[]> GetParametersAsync(IDynamicContext context, NodeModelBase nodeModel, MethodDetails md) public static async Task<object[]> GetParametersAsync(IDynamicContext context,
NodeModelBase nodeModel,
MethodDetails md)
{ {
await Task.Delay(0);
// 用正确的大小初始化参数数组 // 用正确的大小初始化参数数组
if (md.ParameterDetailss.Length == 0) if (md.ParameterDetailss.Length == 0)
{ {
@@ -323,10 +328,30 @@ namespace Serein.Library
//var previousFlowData = nodeModel.PreviousNode?.FlowData; // 当前传递的数据 //var previousFlowData = nodeModel.PreviousNode?.FlowData; // 当前传递的数据
object[] paramsArgs = null; // 初始化可选参数
int paramsArgIndex = 0; // 可选参数下标
if (md.IsParamsArgIndex >= 0) // 是否存在入参参数
{
// 可选参数数组长度 = 方法参数个数 - 可选入参下标 + 1
int paramsLength = md.ParameterDetailss.Length - md.IsParamsArgIndex;
paramsArgs = new object[paramsLength]; // 重新实例化可选参数
parameters[md.ParameterDetailss.Length-1] = paramsArgs; // 如果存在可选参数,入参参数最后一项则为可选参数
}
bool hasParams = false;
for (int i = 0; i < parameters.Length; i++) for (int i = 0; i < parameters.Length; i++)
{ {
var pd = md.ParameterDetailss[i]; // 方法入参描述 var pd = md.ParameterDetailss[i]; // 方法入参描述
// 入参参数下标循环到可选参数时,开始写入到可选参数数组
if(i >= md.IsParamsArgIndex)
{
// 控制参数赋值方向:
// true => paramsArgs
// false => parameters
hasParams = true;
}
#region #region
if (pd.DataType == typeof(IFlowEnvironment)) // 获取流程上下文 if (pd.DataType == typeof(IFlowEnvironment)) // 获取流程上下文
{ {
@@ -344,28 +369,27 @@ namespace Serein.Library
object inputParameter; // 存放解析的临时参数 object inputParameter; // 存放解析的临时参数
if (pd.IsExplicitData) // 判断是否使用显示的输入参数 if (pd.IsExplicitData) // 判断是否使用显示的输入参数
{ {
if (pd.DataValue.StartsWith("@get", StringComparison.OrdinalIgnoreCase)) // 使用输入的固定值
{ inputParameter = pd.DataValue;
var previousNode = context.GetPreviousNode(nodeModel);
var previousFlowData = context.GetFlowData(previousNode.Guid); // 当前传递的数据
// 执行表达式从上一节点获取对象
inputParameter = SerinExpressionEvaluator.Evaluate(pd.DataValue, previousFlowData, out _);
}
else
{
// 使用输入的固定值
inputParameter = pd.DataValue;
}
} }
else else
{ {
#region
if (pd.ArgDataSourceType == ConnectionArgSourceType.GetPreviousNodeData) if (pd.ArgDataSourceType == ConnectionArgSourceType.GetPreviousNodeData)
{ {
var previousNode = context.GetPreviousNode(nodeModel); var previousNode = context.GetPreviousNode(nodeModel);
inputParameter = context.GetFlowData(previousNode.Guid); // 当前传递的数据 if (previousNode is null)
{
inputParameter = null;
}
else
{
inputParameter = context.GetFlowData(previousNode.Guid); // 当前传递的数据
}
} }
#endregion
#region
else if (pd.ArgDataSourceType == ConnectionArgSourceType.GetOtherNodeData) else if (pd.ArgDataSourceType == ConnectionArgSourceType.GetOtherNodeData)
{ {
// 获取指定节点的数据 // 获取指定节点的数据
@@ -373,26 +397,47 @@ namespace Serein.Library
// 如果执行过,会获取上一次执行结果作为预入参数据 // 如果执行过,会获取上一次执行结果作为预入参数据
inputParameter = context.GetFlowData(pd.ArgDataSourceNodeGuid); inputParameter = context.GetFlowData(pd.ArgDataSourceNodeGuid);
} }
#endregion
#region
else if (pd.ArgDataSourceType == ConnectionArgSourceType.GetOtherNodeDataOfInvoke) else if (pd.ArgDataSourceType == ConnectionArgSourceType.GetOtherNodeDataOfInvoke)
{ {
// 立刻调用对应节点获取数据。 // 立刻调用对应节点获取数据。
var result = await context.Env.InvokeNodeAsync(context, pd.ArgDataSourceNodeGuid); var result = await context.Env.InvokeNodeAsync(context, pd.ArgDataSourceNodeGuid);
inputParameter = result; inputParameter = result;
} }
#endregion
#region
else else
{ {
throw new Exception("节点执行方法获取入参参数时ConnectionArgSourceType枚举是意外的枚举值"); throw new Exception("节点执行方法获取入参参数时ConnectionArgSourceType枚举是意外的枚举值");
} }
#endregion
} }
if (inputParameter is null)
#region null检查
if (!pd.DataType.IsValueType && inputParameter is null)
{ {
parameters[i] = null;
throw new Exception($"[arg{pd.Index}][{pd.Name}][{pd.DataType}]参数不能为null"); throw new Exception($"[arg{pd.Index}][{pd.Name}][{pd.DataType}]参数不能为null");
// continue;
} }
#endregion
#region Get表达式
if (pd.IsExplicitData // 输入了表达式
&& pd.DataValue.StartsWith("@get", StringComparison.OrdinalIgnoreCase) // Get表达式
)
{
//var previousNode = context.GetPreviousNode(nodeModel);
//var previousFlowData = context.GetFlowData(previousNode.Guid); // 当前传递的数据
// 执行表达式从上一节点获取对象
inputParameter = SerinExpressionEvaluator.Evaluate(pd.DataValue, inputParameter, out _);
}
#endregion
#endregion #endregion
#region #region null
// 入参存在取值转换器
if (pd.ExplicitType.IsEnum && !(pd.Convertor is null)) if (pd.ExplicitType.IsEnum && !(pd.Convertor is null))
{ {
//var resultEnum = Enum.ToObject(ed.ExplicitType, ed.DataValue); //var resultEnum = Enum.ToObject(ed.ExplicitType, ed.DataValue);
@@ -405,13 +450,21 @@ namespace Serein.Library
} }
else else
{ {
parameters[i] = value; if (hasParams)
{
// 处理可选参数
paramsArgs[paramsArgIndex++] = value;
}
else
{
parameters[i] = value;
}
continue; continue;
} }
} }
#endregion #endregion
#region BinValue的类型转换器 #region BinValue的类型转换器null
// 入参存在基于BinValue的类型转换器获取枚举转换器中记录的类型 // 入参存在基于BinValue的类型转换器获取枚举转换器中记录的类型
if (pd.ExplicitType.IsEnum && pd.DataType != pd.ExplicitType) if (pd.ExplicitType.IsEnum && pd.DataType != pd.ExplicitType)
{ {
@@ -427,7 +480,15 @@ namespace Serein.Library
} }
else else
{ {
parameters[i] = value; if (hasParams)
{
// 处理可选参数
paramsArgs[paramsArgIndex++] = value;
}
else
{
parameters[i] = value;
}
continue; continue;
} }
} }
@@ -436,16 +497,16 @@ namespace Serein.Library
#endregion #endregion
#region #region
object tmpVaue = null; // 临时存放数据,最后才判断是否放置可选参数数组
if (inputParameter.GetType() == pd.DataType) if (inputParameter.GetType() == pd.DataType)
{ {
parameters[i] = inputParameter; // 类型一致无需转换,直接装入入参数组 tmpVaue = inputParameter; // 类型一致无需转换,直接装入入参数组
} }
else if (pd.DataType.IsValueType) else if (pd.DataType.IsValueType)
{ {
// 值类型 // 值类型
var valueStr = inputParameter?.ToString(); var valueStr = inputParameter?.ToString();
parameters[i] = valueStr.ToValueData(pd.DataType); // 类型不一致,尝试进行转换,如果转换失败返回类型对应的默认值 tmpVaue = valueStr.ToValueData(pd.DataType); // 类型不一致,尝试进行转换,如果转换失败返回类型对应的默认值
} }
else else
{ {
@@ -453,56 +514,60 @@ namespace Serein.Library
if (pd.DataType == typeof(string)) // 转为字符串 if (pd.DataType == typeof(string)) // 转为字符串
{ {
var valueStr = inputParameter?.ToString(); var valueStr = inputParameter?.ToString();
parameters[i] = valueStr; tmpVaue = valueStr;
} }
else if(pd.DataType.IsSubclassOf(inputParameter.GetType())) // 入参类型 是 预入参数据类型 的 子类/实现类 else if(pd.DataType.IsSubclassOf(inputParameter.GetType())) // 入参类型 是 预入参数据类型 的 子类/实现类
{ {
// 方法入参中,父类不能隐式转为子类,这里需要进行强制转换 // 方法入参中,父类不能隐式转为子类,这里需要进行强制转换
parameters[i] = ObjectConvertHelper.ConvertParentToChild(inputParameter, pd.DataType); tmpVaue = ObjectConvertHelper.ConvertParentToChild(inputParameter, pd.DataType);
} }
else if(pd.DataType.IsAssignableFrom(inputParameter.GetType())) // 入参类型 是 预入参数据类型 的 父类/接口 else if(pd.DataType.IsAssignableFrom(inputParameter.GetType())) // 入参类型 是 预入参数据类型 的 父类/接口
{ {
parameters[i] = inputParameter; tmpVaue = inputParameter;
} }
// 集合类型 // 集合类型
else if(inputParameter is IEnumerable collection) //else if(inputParameter is IEnumerable collection)
{
var enumerableMethods = typeof(Enumerable).GetMethods(); // 获取所有的 Enumerable 扩展方法
MethodInfo conversionMethod;
if (pd.DataType.IsArray) // 转为数组
{
parameters[i] = inputParameter;
conversionMethod = enumerableMethods.FirstOrDefault(m => m.Name == "ToArray" && m.IsGenericMethodDefinition);
}
else if (pd.DataType.GetGenericTypeDefinition() == typeof(List<>)) // 转为集合
{
conversionMethod = enumerableMethods.FirstOrDefault(m => m.Name == "ToList" && m.IsGenericMethodDefinition);
}
else
{
throw new InvalidOperationException("输入对象不是集合或目标类型不支持目前仅支持Array、List的自动转换");
}
var genericMethod = conversionMethod.MakeGenericMethod(pd.DataType);
var result = genericMethod.Invoke(null, new object[] { collection });
parameters[i] = result;
}
//else if (ed.DataType == typeof(MethodDetails)) // 希望获取节点对应的方法描述,好像没啥用
//{ //{
// parameters[i] = md; // var enumerableMethods = typeof(Enumerable).GetMethods(); // 获取所有的 Enumerable 扩展方法
//} // MethodInfo conversionMethod;
//else if (ed.DataType == typeof(NodeModelBase)) // 希望获取方法生成的节点,好像没啥用 // if (pd.DataType.IsArray) // 转为数组
//{ // {
// parameters[i] = nodeModel; // parameters[i] = inputParameter;
// conversionMethod = enumerableMethods.FirstOrDefault(m => m.Name == "ToArray" && m.IsGenericMethodDefinition);
// }
// else if (pd.DataType.GetGenericTypeDefinition() == typeof(List<>)) // 转为集合
// {
// conversionMethod = enumerableMethods.FirstOrDefault(m => m.Name == "ToList" && m.IsGenericMethodDefinition);
// }
// else
// {
// throw new InvalidOperationException("输入对象不是集合或目标类型不支持目前仅支持Array、List的自动转换");
// }
// var genericMethod = conversionMethod.MakeGenericMethod(pd.DataType);
// var result = genericMethod.Invoke(null, new object[] { collection });
// parameters[i] = result;
//} //}
}
if (hasParams)
{
// 处理可选参数
paramsArgs[paramsArgIndex++] = tmpVaue;
}
else
{
parameters[i] = tmpVaue;
} }
#endregion #endregion
} }
return parameters; return parameters;
} }

View File

@@ -1,6 +1,7 @@
using Serein.Library.Api; using Serein.Library.Api;
using Serein.Library.Utils; using Serein.Library.Utils;
using System; using System;
using System.Collections.Generic;
using System.Linq; using System.Linq;
namespace Serein.Library namespace Serein.Library
@@ -12,7 +13,7 @@ namespace Serein.Library
[NodeProperty(ValuePath = NodeValuePath.Parameter)] [NodeProperty(ValuePath = NodeValuePath.Parameter)]
public partial class ParameterDetails public partial class ParameterDetails
{ {
private readonly IFlowEnvironment env; // private readonly IFlowEnvironment env;
/// <summary> /// <summary>
/// 所在的节点 /// 所在的节点
@@ -48,9 +49,9 @@ namespace Serein.Library
/// <summary> /// <summary>
/// 目前存在三种状态Select/Bool/Value /// 目前存在三种状态Select/Bool/Value
/// <para>Select : 枚举值</para> /// <para>Select : 枚举值/可选值</para>
/// <para>Bool : 布尔类型</para> /// <para>Bool : 布尔类型</para>
/// <para>Value 除以上类型之外的任意参数</para> /// <para>Value :除以上类型之外的任意参数</para>
/// </summary> /// </summary>
[PropertyInfo] [PropertyInfo]
private string _explicitTypeName ; private string _explicitTypeName ;
@@ -91,6 +92,12 @@ namespace Serein.Library
/// </summary> /// </summary>
[PropertyInfo(IsNotification = true)] [PropertyInfo(IsNotification = true)]
private string[] _items ; private string[] _items ;
/// <summary>
/// 指示该属性是可变参数的其中一员(可变参数为数组类型)
/// </summary>
[PropertyInfo]
private bool _isParams;
} }
@@ -109,9 +116,8 @@ namespace Serein.Library
/// <summary> /// <summary>
/// 为节点实例化新的入参描述 /// 为节点实例化新的入参描述
/// </summary> /// </summary>
public ParameterDetails(IFlowEnvironment env, NodeModelBase nodeModel) public ParameterDetails(NodeModelBase nodeModel)
{ {
this.env = env;
this.NodeModel = nodeModel; this.NodeModel = nodeModel;
} }
@@ -147,14 +153,13 @@ namespace Serein.Library
} }
/// <summary> /// <summary>
/// 为某个节点拷贝方法描述的入参描述 /// 为某个节点从元数据中拷贝方法描述的入参描述
/// </summary> /// </summary>
/// <param name="env">运行环境</param>
/// <param name="nodeModel">对应的节点</param> /// <param name="nodeModel">对应的节点</param>
/// <returns></returns> /// <returns></returns>
public ParameterDetails CloneOfClone(IFlowEnvironment env, NodeModelBase nodeModel) public ParameterDetails CloneOfModel(NodeModelBase nodeModel)
{ {
var pd = new ParameterDetails(env, nodeModel) var pd = new ParameterDetails(nodeModel)
{ {
Index = this.Index, Index = this.Index,
IsExplicitData = this.IsExplicitData, IsExplicitData = this.IsExplicitData,

View File

@@ -241,15 +241,15 @@ namespace Serein.Library
/// </summary> /// </summary>
public string SourceType { get; set; } public string SourceType { get; set; }
/// <summary> /// <summary>
/// 自定义入参 /// 自定义入参
/// </summary> /// </summary>
public string Value { get; set; } public string Value { get; set; }
/// <summary> /// <summary>
/// 表达式相关节点的表达式内容 /// 表达式相关节点的表达式内容
/// </summary> /// </summary>
public string Expression { get; set; } // public string Expression { get; set; }
} }

View File

@@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Serein.Library.Network.Mqtt
{
internal interface IMqttServer
{
void Staer();
void Stop();
void HandleMsg(string msg);
void AddHandleConfig();
}
}

View File

@@ -3,10 +3,6 @@ using Newtonsoft.Json.Linq;
using System; using System;
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Collections.Generic; using System.Collections.Generic;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace Serein.Library.Network.WebSocketCommunication.Handle namespace Serein.Library.Network.WebSocketCommunication.Handle

View File

@@ -1,10 +1,4 @@
using System; namespace Serein.Library.Network.WebSocketCommunication.Handle
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Serein.Library.Network.WebSocketCommunication.Handle
{ {
/// <summary> /// <summary>
/// 远程环境配置 /// 远程环境配置

View File

@@ -1,8 +1,5 @@
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace Serein.Library.Network.WebSocketCommunication.Handle namespace Serein.Library.Network.WebSocketCommunication.Handle

View File

@@ -1,23 +1,8 @@
using Newtonsoft.Json.Linq; using System;
using System;
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Runtime.CompilerServices;
using Newtonsoft.Json;
using Serein.Library.Utils;
using System.Net.Http.Headers;
using System.Linq.Expressions;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Diagnostics.CodeAnalysis; using System.Diagnostics.CodeAnalysis;
using System.Reactive; using System.Linq;
using System.Reflection;
namespace Serein.Library.Network.WebSocketCommunication.Handle namespace Serein.Library.Network.WebSocketCommunication.Handle
{ {

View File

@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<Version>1.0.18</Version> <Version>1.0.19</Version>
<TargetFrameworks>net8.0;net462</TargetFrameworks> <TargetFrameworks>net8.0;net462</TargetFrameworks>
<!--<TargetFrameworks>net8.0</TargetFrameworks>--> <!--<TargetFrameworks>net8.0</TargetFrameworks>-->
<BaseOutputPath>D:\Project\C#\DynamicControl\SereinFlow\.Output</BaseOutputPath> <BaseOutputPath>D:\Project\C#\DynamicControl\SereinFlow\.Output</BaseOutputPath>
@@ -32,11 +32,13 @@
<ItemGroup> <ItemGroup>
<Compile Remove="FlowNode\Attribute.cs" /> <Compile Remove="FlowNode\Attribute.cs" />
<Compile Remove="Utils\NativeDllHelper.cs" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\Serein.Library.MyGenerator\Serein.Library.NodeGenerator.csproj" OutputItemType="Analyzer" /> <ProjectReference Include="..\Serein.Library.MyGenerator\Serein.Library.NodeGenerator.csproj" OutputItemType="Analyzer" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" /> <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="System.Reactive" Version="6.0.1" /> <PackageReference Include="System.Reactive" Version="6.0.1" />
<PackageReference Include="System.Threading.Channels" Version="8.0.0" /> <PackageReference Include="System.Threading.Channels" Version="8.0.0" />

View File

@@ -1,6 +1,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Reactive;
using System.Reflection; using System.Reflection;
using System.Reflection.Emit; using System.Reflection.Emit;
using System.Text; using System.Text;
@@ -56,43 +57,37 @@ namespace Serein.Library.Utils
/// <param name="methodInfo"></param> /// <param name="methodInfo"></param>
/// <param name="delegate"></param> /// <param name="delegate"></param>
/// <returns></returns> /// <returns></returns>
public static EmitMethodType CreateDynamicMethod( MethodInfo methodInfo,out Delegate @delegate) public static EmitMethodType CreateDynamicMethod(MethodInfo methodInfo,out Delegate @delegate)
{ {
bool IsTask = IsGenericTask(methodInfo.ReturnType, out var taskGenericsType); bool IsTask = IsGenericTask(methodInfo.ReturnType, out var taskGenericsType);
bool IsTaskGenerics = taskGenericsType != null; bool IsTaskGenerics = taskGenericsType != null;
DynamicMethod dynamicMethod; DynamicMethod dynamicMethod;
if (IsTask)
{
if (IsTaskGenerics)
{
dynamicMethod = new DynamicMethod( Type returnType;
name: methodInfo.Name + "_DynamicMethod", if (!IsTask)
returnType: typeof(Task<object>), {
parameterTypes: new[] { typeof(object), typeof(object[]) }, // 普通方法
restrictedSkipVisibility: true // 跳过私有方法访问限制 returnType = typeof(object);
);
}
else
{
dynamicMethod = new DynamicMethod(
name: methodInfo.Name + "_DynamicMethod",
returnType: typeof(Task),
parameterTypes: new[] { typeof(object), typeof(object[]) },
restrictedSkipVisibility: true // 跳过私有方法访问限制
);
}
} }
else else
{ {
dynamicMethod = new DynamicMethod( // 异步方法
name: methodInfo.Name + "_DynamicMethod", if (IsTaskGenerics)
returnType: typeof(object), {
parameterTypes: new[] { typeof(object), typeof(object[]) }, returnType = typeof(Task<object>);
restrictedSkipVisibility: true // 跳过私有方法访问限制 }
); else
{
returnType = typeof(Task);
}
} }
dynamicMethod = new DynamicMethod(
name: methodInfo.Name + "_DynamicEmitMethod",
returnType: returnType,
parameterTypes: new[] { typeof(object), typeof(object[]) }, // 方法实例、方法入参
restrictedSkipVisibility: true // 跳过私有方法访问限制
);

View File

@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace Serein.Library.Utils
{
}

View File

@@ -51,6 +51,10 @@ namespace Serein.Library.Utils.SereinExpression
/// <exception cref="NotSupportedException"></exception> /// <exception cref="NotSupportedException"></exception>
public static object Evaluate(string expression, object targetObJ, out bool isChange) public static object Evaluate(string expression, object targetObJ, out bool isChange)
{ {
if(expression is null || targetObJ is null)
{
throw new Exception("表达式条件expression is null、 targetObJ is null");
}
var parts = expression.Split(new[] { ' ' }, 2, StringSplitOptions.None); var parts = expression.Split(new[] { ' ' }, 2, StringSplitOptions.None);
if (parts.Length != 2) if (parts.Length != 2)
{ {
@@ -60,6 +64,7 @@ namespace Serein.Library.Utils.SereinExpression
var operation = parts[0].ToLower(); var operation = parts[0].ToLower();
var operand = parts[1][0] == '.' ? parts[1].Substring(1) : parts[1]; var operand = parts[1][0] == '.' ? parts[1].Substring(1) : parts[1];
object result; object result;
isChange = false;
if (operation == "@num") if (operation == "@num")
{ {
result = ComputedNumber(targetObJ, operand); result = ComputedNumber(targetObJ, operand);
@@ -70,10 +75,12 @@ namespace Serein.Library.Utils.SereinExpression
} }
else if (operation == "@get") else if (operation == "@get")
{ {
isChange = true;
result = GetMember(targetObJ, operand); result = GetMember(targetObJ, operand);
} }
else if (operation == "@set") else if (operation == "@set")
{ {
isChange = true;
result = SetMember(targetObJ, operand); result = SetMember(targetObJ, operand);
} }
else else
@@ -81,14 +88,7 @@ namespace Serein.Library.Utils.SereinExpression
throw new NotSupportedException($"Operation {operation} is not supported."); throw new NotSupportedException($"Operation {operation} is not supported.");
} }
if(operation == "@set")
{
isChange = true;
}
else
{
isChange = false;
}
return result; return result;
} }

View File

@@ -1,4 +1,5 @@
using System; using Serein.Library;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;

File diff suppressed because one or more lines are too long

View File

@@ -2,6 +2,7 @@
using Serein.Library.Api; using Serein.Library.Api;
using Serein.Library.FlowNode; using Serein.Library.FlowNode;
using Serein.Library.Utils; using Serein.Library.Utils;
using Serein.NodeFlow.Tool;
namespace Serein.NodeFlow.Env namespace Serein.NodeFlow.Env
{ {
@@ -426,6 +427,30 @@ namespace Serein.NodeFlow.Env
#region
/// <summary>
/// 运行时加载
/// </summary>
/// <param name="file">文件名</param>
/// <returns></returns>
public bool LoadNativeLibraryOfRuning(string file)
{
return currentFlowEnvironment.LoadNativeLibraryOfRuning(file);
}
/// <summary>
/// 运行时加载指定目录下的类库
/// </summary>
/// <param name="path">目录</param>
/// <param name="isRecurrence">是否递归加载</param>
public void LoadAllNativeLibraryOfRuning(string path, bool isRecurrence = true)
{
currentFlowEnvironment.LoadAllNativeLibraryOfRuning(path,isRecurrence);
}
#endregion
#region IOC容器 #region IOC容器
public ISereinIOC Build() public ISereinIOC Build()
{ {

View File

@@ -55,7 +55,7 @@ namespace Serein.NodeFlow.Env
var md = methodDetails.CloneOfNode(nodeModel.Env, nodeModel); var md = methodDetails.CloneOfNode(nodeModel.Env, nodeModel);
nodeModel.DisplayName = md.MethodAnotherName; nodeModel.DisplayName = md.MethodAnotherName;
nodeModel.MethodDetails = md; nodeModel.MethodDetails = md;
nodeModel.OnLoading(); nodeModel.OnCreating();
return nodeModel; return nodeModel;
} }

View File

@@ -835,5 +835,31 @@ namespace Serein.NodeFlow.Env
}); });
} }
#region
/// <summary>
/// 运行时加载
/// </summary>
/// <param name="file">文件名</param>
/// <returns></returns>
public bool LoadNativeLibraryOfRuning(string file)
{
Console.WriteLine("远程环境尚未实现的接口LoadNativeLibraryOfRuning");
return false;
}
/// <summary>
/// 运行时加载指定目录下的类库
/// </summary>
/// <param name="path">目录</param>
/// <param name="isRecurrence">是否递归加载</param>
public void LoadAllNativeLibraryOfRuning(string path, bool isRecurrence = true)
{
Console.WriteLine("远程环境尚未实现的接口LoadAllNativeLibraryOfRuning");
}
#endregion
} }
} }

View File

@@ -1,10 +1,12 @@
using Serein.Library; using Serein.Library;
using Serein.Library.Api; using Serein.Library.Api;
using Serein.Library.Core.NodeFlow; using Serein.Library.Core;
using Serein.Library.Network.WebSocketCommunication; using Serein.Library.Network.WebSocketCommunication;
using Serein.Library.Utils;
using Serein.Library.Web; using Serein.Library.Web;
using Serein.NodeFlow.Env; using Serein.NodeFlow.Env;
using Serein.NodeFlow.Model; using Serein.NodeFlow.Model;
using Serein.NodeFlow.Tool;
using System.Collections.Concurrent; using System.Collections.Concurrent;
namespace Serein.NodeFlow namespace Serein.NodeFlow
@@ -48,9 +50,9 @@ namespace Serein.NodeFlow
{ {
IDynamicContext context; IDynamicContext context;
#if NET6_0_OR_GREATER #if NET6_0_OR_GREATER
context = new Serein.Library.Core.NodeFlow.DynamicContext(env); // 从起始节点启动流程时创建上下文 context = new Serein.Library.Core.DynamicContext(env); // 从起始节点启动流程时创建上下文
#else #else
Context = new Serein.Library.Framework.NodeFlow.DynamicContext(env); Context = new Serein.Library.Framework.DynamicContext(env);
#endif #endif
await startNode.StartFlowAsync(context); // 开始运行时从选定节点开始运行 await startNode.StartFlowAsync(context); // 开始运行时从选定节点开始运行
context.Exit(); context.Exit();
@@ -112,9 +114,9 @@ namespace Serein.NodeFlow
// 判断使用哪一种流程上下文 // 判断使用哪一种流程上下文
IDynamicContext Context; IDynamicContext Context;
#if NET6_0_OR_GREATER #if NET6_0_OR_GREATER
Context = new Serein.Library.Core.NodeFlow.DynamicContext(env); // 从起始节点启动流程时创建上下文 Context = new Serein.Library.Core.DynamicContext(env); // 从起始节点启动流程时创建上下文
#else #else
Context = new Serein.Library.Framework.NodeFlow.DynamicContext(env); Context = new Serein.Library.Framework.DynamicContext(env);
#endif #endif
#endregion #endregion
@@ -233,13 +235,19 @@ namespace Serein.NodeFlow
await dd.InvokeAsync(md.ActingInstance, [Context]); await dd.InvokeAsync(md.ActingInstance, [Context]);
} }
TerminateAllGlobalFlipflop();
if (_flipFlopCts != null && !_flipFlopCts.IsCancellationRequested) if (_flipFlopCts != null && !_flipFlopCts.IsCancellationRequested)
{ {
_flipFlopCts?.Cancel(); _flipFlopCts?.Cancel();
_flipFlopCts?.Dispose(); _flipFlopCts?.Dispose();
} } // 通知所有流程上下文停止运行
TerminateAllGlobalFlipflop(); // 确保所有触发器不再运行
NativeDllHelper.FreeLibrarys(); // 卸载所有已加载的 Native Dll
//NativeDllHelper.FreeLibrarys(); // 卸载所有已加载的 Native Dll
env.FlowState = RunState.Completion; env.FlowState = RunState.Completion;
env.FlipFlopState = RunState.Completion; env.FlipFlopState = RunState.Completion;
@@ -379,8 +387,8 @@ namespace Serein.NodeFlow
await Console.Out.WriteLineAsync($"[{nextNodes[i].MethodDetails.MethodName}]中断已{cancelType},开始执行后继分支"); await Console.Out.WriteLineAsync($"[{nextNodes[i].MethodDetails.MethodName}]中断已{cancelType},开始执行后继分支");
} }
await nextNodes[i].StartFlowAsync(context); // 启动执行触发器后继分支的节点 await nextNodes[i].StartFlowAsync(context); // 启动执行触发器后继分支的节点
context.Exit();
} }
context.Exit();
}); });
} }

View File

@@ -32,7 +32,7 @@ namespace Serein.NodeFlow.Model
/// <summary> /// <summary>
/// 加载完成后调用的方法 /// 加载完成后调用的方法
/// </summary> /// </summary>
public override void OnLoading() public override void OnCreating()
{ {
Console.WriteLine("CompositeConditionNode 暂未实现 OnLoading"); Console.WriteLine("CompositeConditionNode 暂未实现 OnLoading");
} }

View File

@@ -17,9 +17,9 @@ namespace Serein.NodeFlow.Model
/// <summary> /// <summary>
/// 加载完成后调用的方法 /// 加载完成后调用的方法
/// </summary> /// </summary>
public override void OnLoading() public override void OnCreating()
{ {
Console.WriteLine("SingleActionNode 暂未实现 OnLoading"); // Console.WriteLine("SingleActionNode 暂未实现 OnLoading");
} }
public override ParameterData[] GetParameterdatas() public override ParameterData[] GetParameterdatas()

View File

@@ -1,5 +1,6 @@
using Serein.Library; using Serein.Library;
using Serein.Library.Api; using Serein.Library.Api;
using Serein.Library.Utils;
using Serein.Library.Utils.SereinExpression; using Serein.Library.Utils.SereinExpression;
using System.ComponentModel; using System.ComponentModel;
@@ -22,14 +23,13 @@ namespace Serein.NodeFlow.Model
/// 自定义参数值 /// 自定义参数值
/// </summary> /// </summary>
[PropertyInfo(IsNotification = true)] [PropertyInfo(IsNotification = true)]
private object? _customData; private string? _customData;
/// <summary> /// <summary>
/// 条件表达式 /// 条件表达式
/// </summary> /// </summary>
[PropertyInfo(IsNotification = true)] [PropertyInfo(IsNotification = true)]
private string _expression; private string _expression;
} }
public partial class SingleConditionNode : NodeModelBase public partial class SingleConditionNode : NodeModelBase
@@ -39,32 +39,9 @@ namespace Serein.NodeFlow.Model
this.IsCustomData = false; this.IsCustomData = false;
this.CustomData = null; this.CustomData = null;
this.Expression = "PASS"; this.Expression = "PASS";
} }
/// <summary>
/// 加载完成后调用的方法
/// </summary>
public override void OnLoading()
{
var pd = new ParameterDetails
{
Index = 0,
Name = "Exp",
DataType = typeof(object),
ExplicitType = typeof(object),
IsExplicitData = false,
DataValue = string.Empty,
ArgDataSourceNodeGuid = string.Empty,
ArgDataSourceType = ConnectionArgSourceType.GetPreviousNodeData,
NodeModel = this,
Convertor = null,
ExplicitTypeName = "Value",
Items = Array.Empty<string>(),
};
this.MethodDetails.ParameterDetailss = new ParameterDetails[] { pd };
}
/// <summary> /// <summary>
@@ -138,36 +115,102 @@ namespace Serein.NodeFlow.Model
return result; return result;
} }
public override ParameterData[] GetParameterdatas() public override ParameterData[] GetParameterdatas()
{ {
var value = CustomData switch var pd1 = MethodDetails.ParameterDetailss[0];
{ var pd2 = MethodDetails.ParameterDetailss[1];
Type when CustomData.GetType() == typeof(int) var pd3 = MethodDetails.ParameterDetailss[2];
&& CustomData.GetType() == typeof(double) return [
&& CustomData.GetType() == typeof(float) new ParameterData // 保存表达式
=> ((double)CustomData).ToString(), {
Type when CustomData.GetType() == typeof(bool) => ((bool)CustomData).ToString(), Value = Expression ,
_ => CustomData?.ToString()!, SourceNodeGuid = pd1.ArgDataSourceNodeGuid,
}; SourceType = pd1.ArgDataSourceType.ToString(),
return [new ParameterData },
{ new ParameterData // 保存自定义参数
State = IsCustomData, {
Expression = Expression, Value = CustomData?.ToString() ,
Value = value, SourceNodeGuid = pd2.ArgDataSourceNodeGuid,
}]; SourceType = pd2.ArgDataSourceType.ToString(),
},
new ParameterData // 参数来源状态
{
Value = IsCustomData.ToString() ,
SourceNodeGuid = pd3.ArgDataSourceNodeGuid,
SourceType = pd3.ArgDataSourceType.ToString(),
}];
} }
public override void OnCreating()
{
// 自定义节点初始化默认的参数实体
var tmpParameterDetails = new ParameterDetails[3];
for (int index = 0; index <= 2; index++)
{
tmpParameterDetails[index] = new ParameterDetails
{
Index = index,
IsExplicitData = false,
DataValue = string.Empty,
ArgDataSourceNodeGuid = string.Empty,
ArgDataSourceType = ConnectionArgSourceType.GetPreviousNodeData,
NodeModel = this,
Convertor = null,
ExplicitTypeName = "Value",
Items = Array.Empty<string>(),
};
}
var pd1 = tmpParameterDetails[0]; // 表达式
var pd2 = tmpParameterDetails[1]; // 自定义参数
var pd3 = tmpParameterDetails[2]; // 参数来源
// 表达式
pd1.Name = nameof(Expression);
pd1.DataType = typeof(string);
pd1.ExplicitType = typeof(string);
// 自定义参数
pd2.Name = nameof(CustomData);
pd2.DataType = typeof(string);
pd2.ExplicitType = typeof(string);
// 参数来源
pd3.Name = nameof(IsCustomData);
pd3.DataType = typeof(bool);
pd3.ExplicitType = typeof(bool);
//this.MethodDetails.ParameterDetailss = new ParameterDetails[2] { pd1, pd2 };
this.MethodDetails.ParameterDetailss = [..tmpParameterDetails];
}
public override NodeModelBase LoadInfo(NodeInfo nodeInfo) public override NodeModelBase LoadInfo(NodeInfo nodeInfo)
{ {
var node = this; this.Guid = nodeInfo.Guid;
node.Guid = nodeInfo.Guid;
this.Position = nodeInfo.Position;// 加载位置信息 this.Position = nodeInfo.Position;// 加载位置信息
var pdInfo1 = nodeInfo.ParameterData[0];
this.Expression = pdInfo1.Value; // 加载表达式
var pdInfo2 = nodeInfo.ParameterData[1];
this.CustomData = pdInfo2.Value; // 加载自定义参数信息
var pdInfo3 = nodeInfo.ParameterData[2];
bool.TryParse(pdInfo3.Value,out var @bool); // 参数来源状态
this.IsCustomData = @bool;
for (int i = 0; i < nodeInfo.ParameterData.Length; i++) for (int i = 0; i < nodeInfo.ParameterData.Length; i++)
{ {
ParameterData? pd = nodeInfo.ParameterData[i]; var pd = this.MethodDetails.ParameterDetailss[i]; // 本节点的参数信息
node.IsCustomData = pd.State; ParameterData? pdInfo = nodeInfo.ParameterData[i]; // 项目文件的保存信息
node.CustomData = pd.Value;
node.Expression = pd.Expression; pd.ArgDataSourceNodeGuid = pdInfo.SourceNodeGuid;
pd.ArgDataSourceType = EnumHelper.ConvertEnum<ConnectionArgSourceType>(pdInfo.SourceType);
} }
return this; return this;
} }

View File

@@ -1,5 +1,6 @@
using Serein.Library; using Serein.Library;
using Serein.Library.Api; using Serein.Library.Api;
using Serein.Library.Utils;
using Serein.Library.Utils.SereinExpression; using Serein.Library.Utils.SereinExpression;
using System.Reactive; using System.Reactive;
using System.Reflection.Metadata; using System.Reflection.Metadata;
@@ -32,14 +33,14 @@ namespace Serein.NodeFlow.Model
/// <summary> /// <summary>
/// 加载完成后调用的方法 /// 加载完成后调用的方法
/// </summary> /// </summary>
public override void OnLoading() public override void OnCreating()
{ {
var pd = new ParameterDetails var pd = new ParameterDetails
{ {
Index = 0, Index = 0,
Name = "Exp", Name = nameof(Expression),
DataType = typeof(object), DataType = typeof(string),
ExplicitType = typeof(object), ExplicitType = typeof(string),
IsExplicitData = false, IsExplicitData = false,
DataValue = string.Empty, DataValue = string.Empty,
ArgDataSourceNodeGuid = string.Empty, ArgDataSourceNodeGuid = string.Empty,
@@ -92,7 +93,7 @@ namespace Serein.NodeFlow.Model
} }
context.NextOrientation = ConnectionInvokeType.IsSucceed; context.NextOrientation = ConnectionInvokeType.IsSucceed;
return Task.FromResult(result); return result;
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -105,7 +106,11 @@ namespace Serein.NodeFlow.Model
public override ParameterData[] GetParameterdatas() public override ParameterData[] GetParameterdatas()
{ {
return [new ParameterData { Expression = Expression }]; return [new ParameterData {
Value = Expression,
SourceNodeGuid = this.MethodDetails.ParameterDetailss[0].ArgDataSourceNodeGuid,
SourceType = this.MethodDetails.ParameterDetailss[0].ArgDataSourceType.ToString(),
}];
} }
@@ -113,11 +118,17 @@ namespace Serein.NodeFlow.Model
public override NodeModelBase LoadInfo(NodeInfo nodeInfo) public override NodeModelBase LoadInfo(NodeInfo nodeInfo)
{ {
var node = this; var node = this;
this.Position = nodeInfo.Position;// 加载位置信息
node.Guid = nodeInfo.Guid; node.Guid = nodeInfo.Guid;
this.Position = nodeInfo.Position;// 加载位置信息
var pdInfo1 = nodeInfo.ParameterData[0];
node.Expression = pdInfo1.Value; // 加载表达式
for (int i = 0; i < nodeInfo.ParameterData.Length; i++) for (int i = 0; i < nodeInfo.ParameterData.Length; i++)
{ {
node.Expression = nodeInfo.ParameterData[i].Expression; ParameterData? pd = nodeInfo.ParameterData[i];
node.MethodDetails.ParameterDetailss[i].ArgDataSourceNodeGuid = pd.SourceNodeGuid;
node.MethodDetails.ParameterDetailss[i].ArgDataSourceType = EnumHelper.ConvertEnum<ConnectionArgSourceType>(pd.SourceType);
} }
return this; return this;
} }

View File

@@ -19,9 +19,9 @@ namespace Serein.NodeFlow.Model
/// <summary> /// <summary>
/// 加载完成后调用的方法 /// 加载完成后调用的方法
/// </summary> /// </summary>
public override void OnLoading() public override void OnCreating()
{ {
Console.WriteLine("SingleFlipflopNode 暂未实现 OnLoading"); // Console.WriteLine("SingleFlipflopNode 暂未实现 OnLoading");
} }
@@ -50,16 +50,18 @@ namespace Serein.NodeFlow.Model
object instance = md.ActingInstance; object instance = md.ActingInstance;
try try
{ {
var args = await GetParametersAsync(context, this, md); var args = await GetParametersAsync(context, this, md);
var result = await dd.InvokeAsync(md.ActingInstance, args); // 因为这里会返回不确定的泛型 IFlipflopContext<TRsult>
dynamic flipflopContext = result; // 而我们只需要获取到 State 和 Value返回的数据
FlipflopStateType flipflopStateType = flipflopContext.State; dynamic dynamicFlipflopContext = await dd.InvokeAsync(md.ActingInstance, args);
FlipflopStateType flipflopStateType = dynamicFlipflopContext.State;
context.NextOrientation = flipflopStateType.ToContentType(); context.NextOrientation = flipflopStateType.ToContentType();
if (flipflopContext.Type == TriggerType.Overtime) if (dynamicFlipflopContext.Type == TriggerType.Overtime)
{ {
throw new FlipflopException(base.MethodDetails.MethodName + "触发器超时触发。Guid" + base.Guid); throw new FlipflopException(base.MethodDetails.MethodName + "触发器超时触发。Guid" + base.Guid);
} }
return flipflopContext.Value; return dynamicFlipflopContext.Value;
} }
catch (FlipflopException ex) catch (FlipflopException ex)

View File

@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<Version>1.0.18</Version> <Version>1.0.19</Version>
<TargetFramework>net8.0</TargetFramework> <TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
@@ -60,6 +60,7 @@
</None> </None>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\Serein.Library.MyGenerator\Serein.Library.NodeGenerator.csproj" OutputItemType="Analyzer" /> <ProjectReference Include="..\Serein.Library.MyGenerator\Serein.Library.NodeGenerator.csproj" OutputItemType="Analyzer" />

View File

@@ -0,0 +1,53 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
using System.Text;
using System.Threading.Tasks;
namespace Serein.NodeFlow.Tool
{
/// <summary>
/// 管理加载在流程的程序集
/// </summary>
public class FlowLibraryLoader : AssemblyLoadContext
{
private Assembly _pluginAssembly;
/// <summary>
/// 加载程序集
/// </summary>
/// <param name="pluginPath"></param>
public FlowLibraryLoader(string pluginPath) : base(isCollectible: true)
{
_pluginAssembly = LoadFromAssemblyPath(pluginPath);
}
/// <summary>
/// 保持默认加载行为
/// </summary>
/// <param name="assemblyName"></param>
/// <returns></returns>
protected override Assembly Load(AssemblyName assemblyName)
{
return null; // 保持默认加载行为
}
/// <summary>
/// 是否对程序集的引用
/// </summary>
public void UnloadPlugin()
{
_pluginAssembly = null; // 释放对程序集的引用
Unload(); // 触发卸载
// 强制进行垃圾回收,以便完成卸载
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
}

View File

@@ -0,0 +1,182 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace Serein.NodeFlow.Tool
{
internal class NativeDllHelper
{
// 引入 Windows API 函数
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr LoadLibrary(string lpFileName);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool FreeLibrary(IntPtr hModule);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
// 引入 Unix/Linux 的动态库加载函数
[DllImport("libdl.so.2", SetLastError = true)]
private static extern IntPtr dlopen(string filename, int flag);
[DllImport("libdl.so.2", SetLastError = true)]
private static extern IntPtr dlsym(IntPtr handle, string symbol);
[DllImport("libdl.so.2", SetLastError = true)]
private static extern int dlclose(IntPtr handle);
private const int RTLD_NOW = 2;
// bool LoadDll(string file)
// void LoadAllDll(string path, bool isRecurrence = true);
private static List<IntPtr> Nints = new List<nint>();
/// <summary>
/// 加载单个Dll
/// </summary>
/// <param name="file"></param>
public static bool LoadDll(string file)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
return LoadWindowsLibrarie(file);
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
return LoadLinuxLibrarie(file);
}
else
{
Console.WriteLine("Unsupported OS.");
return false;
}
}
public static void LoadAllDll(string path, bool isRecurrence = true)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
foreach (var file in Directory.GetFiles(path, "*.dll"))
{
LoadWindowsLibrarie(file);
}
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
foreach (var file in Directory.GetFiles(path, "*.so"))
{
LoadLinuxLibrarie(file);
}
}
else
{
Console.WriteLine("Unsupported OS.");
}
foreach (var dir in Directory.GetDirectories(path))
{
LoadAllDll(dir, true);
}
}
/// <summary>
/// 加载Windows类库
/// </summary>
/// <param name="path"></param>
/// <param name="isRecurrence">是否递归加载</param>
private static bool LoadWindowsLibrarie(string file)
{
IntPtr hModule = IntPtr.Zero;
try
{
hModule = LoadLibrary(file);
// 加载 DLL
if (hModule != IntPtr.Zero)
{
Nints.Add(hModule);
Console.WriteLine($"Loaded: {file}");
return true;
}
else
{
Console.WriteLine($"Failed to load {file}: {Marshal.GetLastWin32Error()}");
return false;
}
}
catch (Exception ex)
{
Console.WriteLine($"Error loading {file}: {ex.Message}");
return false;
}
}
/// <summary>
/// 加载Linux类库
/// </summary>
/// <param name="file"></param>
private static bool LoadLinuxLibrarie(string file)
{
IntPtr handle = IntPtr.Zero;
try
{
handle = dlopen(file, RTLD_NOW);
if (handle != IntPtr.Zero)
{
Nints.Add(handle);
Console.WriteLine($"Loaded: {file}");
return true;
// 可以调用共享库中的函数
// IntPtr procAddress = dlsym(handle, "my_function");
}
else
{
Console.WriteLine($"Failed to load {file}: {Marshal.GetLastWin32Error()}");
return false;
}
}
catch (Exception ex)
{
Console.WriteLine($"Error loading {file}: {ex.Message}");
return false;
}
}
/// <summary>
/// 卸载所有已加载DLL
/// </summary>
public static void FreeLibrarys()
{
for (int i = 0; i < Nints.Count; i++)
{
IntPtr hModule = Nints[i];
FreeLibrary(hModule);
}
Nints.Clear();
}
}
}

View File

@@ -174,11 +174,11 @@ public static class NodeMethodDetailsHelper
ConvertorInstance[key] = (instance, convertMethod); ConvertorInstance[key] = (instance, convertMethod);
} }
Func<object, object> func = (enumValue) => object func(object enumValue)
{ {
(var obj,var methodInfo) = ConvertorInstance[key]; (var obj, var methodInfo) = ConvertorInstance[key];
return methodInfo?.Invoke(obj, [enumValue]); return methodInfo?.Invoke(obj, [enumValue]);
}; }
// 确保实例实现了所需接口 // 确保实例实现了所需接口
ParameterDetails ed = GetExplicitDataOfParameter(it, index, paremType, true, func); ParameterDetails ed = GetExplicitDataOfParameter(it, index, paremType, true, func);
@@ -206,26 +206,29 @@ public static class NodeMethodDetailsHelper
} }
private static ParameterDetails GetExplicitDataOfParameter(ParameterInfo parameterInfo, private static ParameterDetails GetExplicitDataOfParameter(ParameterInfo parameterInfo,
int index, int index,
Type paremType, Type paremType,
bool isExplicitData, bool isExplicitData,
Func<object, object> func = null) Func<object, object> func = null)
{ {
bool hasParams = parameterInfo.IsDefined(typeof(ParamArrayAttribute)); // 判断是否为可变参数
string explicitTypeName = GetExplicitTypeName(paremType); string explicitTypeName = GetExplicitTypeName(paremType);
var items = GetExplicitItems(paremType, explicitTypeName); var items = GetExplicitItems(paremType, explicitTypeName);
if ("Bool".Equals(explicitTypeName)) explicitTypeName = "Select"; // 布尔值 转为 可选类型 if ("Bool".Equals(explicitTypeName)) explicitTypeName = "Select"; // 布尔值 转为 可选类型
return new ParameterDetails return new ParameterDetails
{ {
IsExplicitData = isExplicitData, //attribute is null ? parameterInfo.HasDefaultValue : true, IsExplicitData = isExplicitData, //attribute is null ? parameterInfo.HasDefaultValue : true,
Index = index, Index = index, // 索引
ExplicitTypeName = explicitTypeName, ExplicitTypeName = explicitTypeName, // Select/Bool/Value
ExplicitType = paremType, ExplicitType = paremType,// 显示的入参类型
Convertor = func, Convertor = func, // 转换器
DataType = parameterInfo.ParameterType, DataType = parameterInfo.ParameterType, // 实际的入参类型
Name = parameterInfo.Name, Name = parameterInfo.Name,
DataValue = parameterInfo.HasDefaultValue ? parameterInfo?.DefaultValue?.ToString() : "", // 如果存在默认值,则使用默认值 DataValue = parameterInfo.HasDefaultValue ? parameterInfo?.DefaultValue?.ToString() : "", // 如果存在默认值,则使用默认值
Items = items.ToArray(), // 如果是枚举值入参,则获取枚举类型的字面量 Items = items.ToArray(), // 如果是枚举值入参,则获取枚举类型的字面量
IsParams = hasParams, // 判断是否为可变参数
}; };
} }

View File

@@ -22,8 +22,11 @@
<None Remove="bin\**" /> <None Remove="bin\**" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.11.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.11.0" PrivateAssets="all" /> <PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.11.0" PrivateAssets="all" />
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.11.0" PrivateAssets="all" />
</ItemGroup> </ItemGroup>
<!--<ItemGroup> <!--<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.11.0"> <PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.11.0">

View File

@@ -1,5 +1,6 @@
using Newtonsoft.Json; using Newtonsoft.Json;
using Serein.Library; using Serein.Library;
using System.IO;
using System.Windows; using System.Windows;
using System.Windows.Threading; using System.Windows.Threading;
@@ -12,14 +13,19 @@ namespace Serein.Workbench
{ {
void LoadLocalProject() void LoadLocalProject()
{ {
#if DEBUG #if DEBUG
if (1 == 1) if (1 == 11)
{ {
string filePath; string filePath;
filePath = @"F:\临时\project\linux\project.dnf";
filePath = @"F:\临时\project\linux\http\project.dnf"; filePath = @"F:\临时\project\linux\http\project.dnf";
filePath = @"F:\临时\project\yolo flow\project.dnf";
string content = System.IO.File.ReadAllText(filePath); // 读取整个文件内容 string content = System.IO.File.ReadAllText(filePath); // 读取整个文件内容
App.FlowProjectData = JsonConvert.DeserializeObject<SereinProjectData>(content); App.FlowProjectData = JsonConvert.DeserializeObject<SereinProjectData>(content);
App.FileDataPath = System.IO.Path.GetDirectoryName(filePath)!; // filePath;// App.FileDataPath = System.IO.Path.GetDirectoryName(filePath)!; // filePath;//
var dir = Path.GetDirectoryName(filePath);
//System.IO.Directory.SetCurrentDirectory(dir);
} }
#endif #endif
} }

View File

@@ -12,6 +12,8 @@ using Serein.Workbench.Node.ViewModel;
using Serein.Workbench.Themes; using Serein.Workbench.Themes;
using System; using System;
using System.IO; using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows; using System.Windows;
using System.Windows.Controls; using System.Windows.Controls;
using System.Windows.Controls.Primitives; using System.Windows.Controls.Primitives;
@@ -247,10 +249,11 @@ namespace Serein.Workbench
return; return;
} }
InitializeCanvas(project.Basic.Canvas.Width, project.Basic.Canvas.Height);// 设置画布大小 InitializeCanvas(project.Basic.Canvas.Width, project.Basic.Canvas.Height);// 设置画布大小
foreach (var connection in Connections) //foreach (var connection in Connections)
{ //{
connection.RefreshLine(); // 窗体完成加载后试图刷新所有连接线 // connection.RefreshLine(); // 窗体完成加载后试图刷新所有连接线
} //}
Console.WriteLine($"运行环境当前工作目录:{System.IO.Directory.GetCurrentDirectory()}");
var canvasData = project.Basic.Canvas; var canvasData = project.Basic.Canvas;
if (canvasData is not null) if (canvasData is not null)
@@ -267,7 +270,12 @@ namespace Serein.Workbench
FlowChartCanvas.RenderTransform = canvasTransformGroup; FlowChartCanvas.RenderTransform = canvasTransformGroup;
} }
} }
#endregion #endregion
#region #region

View File

@@ -21,7 +21,7 @@ namespace Serein.Workbench.Node.ViewModel
/// <summary> /// <summary>
/// 自定义参数值 /// 自定义参数值
/// </summary> /// </summary>
public object? CustomData public string? CustomData
{ {
get => NodeModel.CustomData; get => NodeModel.CustomData;
set { NodeModel.CustomData = value ; OnPropertyChanged(); } set { NodeModel.CustomData = value ; OnPropertyChanged(); }
@@ -42,9 +42,12 @@ namespace Serein.Workbench.Node.ViewModel
public ConditionNodeControlViewModel(SingleConditionNode node) : base(node) public ConditionNodeControlViewModel(SingleConditionNode node) : base(node)
{ {
this.NodeModel = node; this.NodeModel = node;
IsCustomData = false; if(node is null)
CustomData = ""; {
Expression = "PASS"; IsCustomData = false;
CustomData = "";
Expression = "PASS";
}
} }
} }

View File

@@ -21,13 +21,15 @@
<ColumnDefinition Width="auto"/> <ColumnDefinition Width="auto"/>
<ColumnDefinition Width="*"/> <ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions> </Grid.ColumnDefinitions>
<!--连接控制器-->
<view:ArgJunctionControl x:Name="ArgJunctionControl" Grid.Column="0" ArgIndex="{Binding Index}" MyNode="{Binding NodeModel}" /> <view:ArgJunctionControl x:Name="ArgJunctionControl" Grid.Column="0" ArgIndex="{Binding Index}" MyNode="{Binding NodeModel}" />
<ContentControl Content="{Binding}" Grid.Column="1"> <ContentControl Content="{Binding}" Grid.Column="1">
<ContentControl.Style> <ContentControl.Style>
<Style TargetType="ContentControl"> <Style TargetType="ContentControl">
<Style.Triggers> <Style.Triggers>
<!--无须指定参数-->
<MultiDataTrigger> <MultiDataTrigger>
<!--无须指定参数-->
<MultiDataTrigger.Conditions> <MultiDataTrigger.Conditions>
<Condition Binding="{Binding IsExplicitData}" Value="false" /> <Condition Binding="{Binding IsExplicitData}" Value="false" />
</MultiDataTrigger.Conditions> </MultiDataTrigger.Conditions>
@@ -84,6 +86,7 @@
</Setter.Value> </Setter.Value>
</Setter> </Setter>
</MultiDataTrigger> </MultiDataTrigger>
<!--指定参数:文本类型(可输入)--> <!--指定参数:文本类型(可输入)-->
<MultiDataTrigger> <MultiDataTrigger>
<MultiDataTrigger.Conditions> <MultiDataTrigger.Conditions>

View File

@@ -98,12 +98,6 @@ namespace Serein.Workbench.Node.View
#endregion #endregion
/// <summary> /// <summary>
/// 连接控件,表示控件的连接关系 /// 连接控件,表示控件的连接关系
/// </summary> /// </summary>