diff --git a/app/MindWork AI Studio/Tools/ExpressionExtensions.cs b/app/MindWork AI Studio/Tools/ExpressionExtensions.cs index 564c96a5..1521678a 100644 --- a/app/MindWork AI Studio/Tools/ExpressionExtensions.cs +++ b/app/MindWork AI Studio/Tools/ExpressionExtensions.cs @@ -1,4 +1,6 @@ using System.Linq.Expressions; +using System.Numerics; +using System.Reflection; namespace AIStudio.Tools; @@ -32,4 +34,48 @@ public static class ExpressionExtensions throw new ArgumentException($"Expression '{expression}' is not a valid property expression.", nameof(expression)); } } + + /// + /// Attempts to increment the value of an uint property for a specified object using a + /// provided expression. + /// + /// An expression representing the property to be incremented. The property + /// must be of type uint and belong to the provided object. + /// The object that contains the property referenced by the expression. + /// The type of the object that contains the property to be incremented. + /// The type of the property to be incremented. + /// True if the property was successfully incremented, otherwise false. + public static bool TryIncrement(this Expression> expression, TIn data) where TOut : IBinaryInteger + { + // Ensure that the expression body is a member expression: + if (expression.Body is not MemberExpression memberExpression) + return false; + + // Ensure that the member expression is a property: + if (memberExpression.Member is not PropertyInfo propertyInfo) + return false; + + // Ensure that the member expression has a target object: + if (memberExpression.Expression is null) + return false; + + // Get the target object for the expression, which is the object containing the property to increment: + var targetObjectExpression = Expression.Lambda(memberExpression.Expression, expression.Parameters); + + // Compile the lambda expression to get the target object + // (which is the object containing the property to increment): + var targetObject = targetObjectExpression.Compile().DynamicInvoke(data); + + // Was the compilation successful? + if (targetObject is null) + return false; + + // Read the current value of the property: + if (propertyInfo.GetValue(targetObject) is not TOut value) + return false; + + // Increment the value: + propertyInfo.SetValue(targetObject, value + TOut.CreateChecked(1)); + return true; + } } \ No newline at end of file