Example #1
0
        public void ILBytesForDifferentDelegatesAreTheSameTest()
        {
            var x = new Func<object, int>(y => 0);

            var z = new Func<object, int>(y => 0);

            Assert.False(x == z);

            var xBytes = x.GetMethodInfo().GetILBytes();
            Assert.False(xBytes.IsNullOrEmpty());

            var zBytes = x.GetMethodInfo().GetILBytes();
            Assert.False(zBytes.IsNullOrEmpty());

            Assert.True(xBytes.EqualTo(zBytes));
        }
 /// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary>
 /// <param name="method">The method to invoke.</param>
 /// <param name="start">true if this function should Start the Process; false if that responsibility is left up to the caller.</param>
 internal static RemoteInvokeHandle RemoteInvoke(
     Func<int> method, 
     bool start = true,
     ProcessStartInfo psi = null)
 {
     return RemoteInvoke(method.GetMethodInfo(), Array.Empty<string>(), start, psi);
 }
Example #3
0
 public void Static <T1, T2, T3, TResult>(Func <T1, T2, T3, TResult> target, Func <T1, T2, T3, TResult> deputy)
 {
     SwapMethod(
         IsStatic(NotNull(target?.GetMethodInfo(), nameof(target))),
         IsStatic(NotNull(deputy?.GetMethodInfo(), nameof(deputy)))
         );
 }
Example #4
0
 /// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary>
 /// <param name="method">The method to invoke.</param>
 /// <param name="arg1">The first argument to pass to the method.</param>
 /// <param name="arg2">The second argument to pass to the method.</param>
 /// <param name="arg3">The third argument to pass to the method.</param>
 /// <param name="options">Options to use for the invocation.</param>
 internal static RemoteInvokeHandle RemoteInvoke(
     Func<string, string, string, int> method, 
     string arg1, string arg2, string arg3, 
     RemoteInvokeOptions options = null)
 {
     return RemoteInvoke(method.GetMethodInfo(), new[] { arg1, arg2, arg3 }, options);
 }
 /// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary>
 /// <param name="method">The method to invoke.</param>
 /// <param name="arg1">The first argument to pass to the method.</param>
 /// <param name="arg2">The second argument to pass to the method.</param>
 /// <param name="arg3">The third argument to pass to the method.</param>
 /// <param name="start">true if this function should Start the Process; false if that responsibility is left up to the caller.</param>
 internal static RemoteInvokeHandle RemoteInvoke(
     Func<string, string, string, int> method, 
     string arg1, string arg2, string arg3, 
     bool start = true,
     ProcessStartInfo psi = null)
 {
     return RemoteInvoke(method.GetMethodInfo(), new[] { arg1, arg2, arg3 }, start, psi);
 }
 /// <summary>
 /// Accept the specified trigger, execute exit actions and re-execute entry actions.
 /// Reentry behaves as though the configured state transitions to an identical sibling state.
 /// </summary>
 /// <param name="trigger">The accepted trigger.</param>
 /// <param name="guard">Function that must return true in order for the
 /// trigger to be accepted.</param>
 /// <param name="guardDescription">Guard description</param>
 /// <returns>The reciever.</returns>
 /// <remarks>
 /// Applies to the current state only. Will not re-execute superstate actions, or
 /// cause actions to execute transitioning between super- and sub-states.
 /// </remarks>
 public StateConfiguration PermitReentryIf(TTrigger trigger, Func <bool> guard, string guardDescription = null)
 {
     return(InternalPermitIf(
                trigger,
                _representation.UnderlyingState,
                guard,
                guardDescription ?? guard?.GetMethodInfo().Name));
 }
Example #7
0
        public void ILBytesForDelegateAreAvailableTest()
        {
            var x = new Func<object, int>(y => 0);

            var bytes = x.GetMethodInfo().GetILBytes();

            Assert.False(bytes.IsNullOrEmpty());
        }
Example #8
0
 public void Instance <TClass, T1, T2, T3, TResult>(Func <T1, T2, T3, TResult> target, Func <TClass, T1, T2, T3, TResult> deputy)
     where TClass : class
 {
     SwapMethod(
         NotStatic(NotNull(target?.GetMethodInfo(), nameof(target))),
         IsStatic(NotNull(deputy?.GetMethodInfo(), nameof(deputy)))
         );
 }
 /// <summary>
 /// Accept the specified trigger and transition to the destination state.
 /// </summary>
 /// <param name="trigger">The accepted trigger.</param>
 /// <param name="destinationState">The state that the trigger will cause a
 /// transition to.</param>
 /// <param name="guard">Function that must return true in order for the
 /// trigger to be accepted.</param>
 /// <param name="guardDescription">Guard description</param>
 /// <returns>The reciever.</returns>
 public StateConfiguration PermitIf(TTrigger trigger, TState destinationState, Func <bool> guard, string guardDescription = null)
 {
     EnforceNotIdentityTransition(destinationState);
     return(InternalPermitIf(
                trigger,
                destinationState,
                guard,
                guardDescription ?? guard?.GetMethodInfo().Name));
 }
 /// <summary>
 /// Accept the specified trigger and transition to the destination state, calculated
 /// dynamically by the supplied function.
 /// </summary>
 /// <param name="trigger">The accepted trigger.</param>
 /// <param name="destinationStateSelector">Function to calculate the state
 /// that the trigger will cause a transition to.</param>
 /// <param name="guard">Function that must return true in order for the
 /// trigger to be accepted.</param>
 /// <param name="guardDescription">Guard description</param>
 /// <returns>The reciever.</returns>
 public StateConfiguration PermitDynamicIf(TTrigger trigger, Func <TState> destinationStateSelector, Func <bool> guard, string guardDescription = null)
 {
     Enforce.ArgumentNotNull(destinationStateSelector, nameof(destinationStateSelector));
     return(InternalPermitDynamicIf(
                trigger,
                args => destinationStateSelector(),
                guard,
                guardDescription ?? guard?.GetMethodInfo().Name));
 }
 public WeakRelayCommand(Action <object> executeCallback, Func <object, bool> canExecuteCallback = null)
 {
     ExecuteTargetReference = new WeakReference <object>(executeCallback.Target);
     if (canExecuteCallback != null)
     {
         CanExecuteTargetReference = new WeakReference <object>(canExecuteCallback.Target);
     }
     ExecuteCallbackInfo    = executeCallback.GetMethodInfo();
     CanExecuteCallbackInfo = canExecuteCallback?.GetMethodInfo();
 }
 /// <summary>
 /// Ignore the specified trigger when in the configured state, if the guard
 /// returns true..
 /// </summary>
 /// <param name="trigger">The trigger to ignore.</param>
 /// <param name="guardDescription">Guard description</param>
 /// <param name="guard">Function that must return true in order for the
 /// trigger to be ignored.</param>
 /// <returns>The receiver.</returns>
 public StateConfiguration IgnoreIf(TTrigger trigger, Func <bool> guard, string guardDescription = null)
 {
     Enforce.ArgumentNotNull(guard, nameof(guard));
     _representation.AddTriggerBehaviour(
         new IgnoredTriggerBehaviour(
             trigger,
             guard,
             guardDescription ?? guard?.GetMethodInfo().Name));
     return(this);
 }
 /// <summary>
 /// Accept the specified trigger and transition to the destination state, calculated
 /// dynamically by the supplied function.
 /// </summary>
 /// <param name="trigger">The accepted trigger.</param>
 /// <param name="destinationStateSelector">Function to calculate the state
 /// that the trigger will cause a transition to.</param>
 /// <param name="guard">Function that must return true in order for the
 /// trigger to be accepted.</param>
 /// <param name="guardDescription">Guard description</param>
 /// <returns>The reciever.</returns>
 /// <typeparam name="TArg0">Type of the first trigger argument.</typeparam>
 public StateConfiguration PermitDynamicIf <TArg0>(TriggerWithParameters <TArg0> trigger, Func <TArg0, TState> destinationStateSelector, Func <bool> guard, string guardDescription = null)
 {
     Enforce.ArgumentNotNull(trigger, nameof(trigger));
     Enforce.ArgumentNotNull(destinationStateSelector, nameof(destinationStateSelector));
     return(InternalPermitDynamicIf(
                trigger.Trigger,
                args => destinationStateSelector(
                    ParameterConversion.Unpack <TArg0>(args, 0)),
                guard,
                guardDescription ?? guard?.GetMethodInfo().Name));
 }
        public static void Run(this ApplicationInstance applicationInstance,
                               Func<Task> staticMethodToExecute,
            TestInjectorSettings testInjectorSettings = null)
        {
            var methodInfo =
            #if NET40
             staticMethodToExecute.Method;
            #else
                staticMethodToExecute.GetMethodInfo();
            #endif

            if (!methodInfo.IsStatic)
                throw new InvalidOperationException("Method must be static - don't reference any outside parameters");

            RunMethodImpl(applicationInstance, methodInfo, testInjectorSettings);
        }
Example #15
0
        private async Task Accept(Func <byte[], Task <byte[]> > callback)
        {
            //run this through Task.Run so we can respond to the waitToken if its called for.
            using (var client = await Task.Run(() => tcpListener.AcceptTcpClientAsync(), _waitToken))
            {
                if (_waitToken.IsCancellationRequested)
                {
                    return;
                }
                client.Client.NoDelay = true;
                //client.Client.LingerState = new LingerOption(true, 0);
                var readBuffer = new byte[32768];

                using (var stream = client.GetStream())
                {
                    using (var memoryStream = new MemoryStream())
                    {
                        while (true)
                        {
                            using (var readTokenSource = new CancellationTokenSource(readTimeout))
                            {
                                readTokenSource.Token.Register(() =>
                                {
                                    if (memoryStream != null)
                                    {
                                        memoryStream.Close();
                                        memoryStream.Dispose();
                                    }

                                    if (stream != null)
                                    {
                                        stream.Close();
                                        stream.Dispose();
                                    }

                                    if (client != null)
                                    {
                                        //if (client.Client != null) client.Client.Disconnect(false);
                                        client.Close();
                                        client.Dispose();
                                    }

                                    readBuffer = null;
                                });

                                var read = await stream.ReadAsync(readBuffer, 0, readBuffer.Length,
                                                                  readTokenSource.Token);

                                if (read > 0)
                                {
                                    if (readBuffer[0] == 63)
                                    {
                                        var payload = _serializer.Serialize(new
                                        {
                                            _configuration?.DebugMode,
                                            _configuration?.Environment,
                                            _configuration?.Version,
                                            Owner = _onReceived?.GetMethodInfo()?.DeclaringType?.FullName,
                                            Counter,
                                            Environment.WorkingSet,
                                            Environment.MachineName,
                                            OnlineSince             = _captureAndAggregate.StartDateTimeOffset,
                                            OnlineDurationInSeconds =
                                                (DateTimeOffset.UtcNow - _captureAndAggregate.StartDateTimeOffset)
                                                .TotalSeconds,
                                            TotalAverage        = _captureAndAggregate.TotalAverage(),
                                            Last5SecondsAverage = _captureAndAggregate.Last5SecondsAverage()
                                        });
                                        await stream.WriteAsync(payload, 0, payload.Length, _waitToken);

                                        await stream.FlushAsync(_waitToken);

                                        break;
                                    }

                                    if (read > 0)
                                    {
                                        await memoryStream.WriteAsync(readBuffer, 0, read, _waitToken);
                                    }

                                    if (read <= 0 || readBuffer[read - 1] == PacketFormatter?.PacketTerminator)
                                    {
                                        var data = memoryStream.ToArray();
                                        if (PacketFormatter != null)
                                        {
                                            data = PacketFormatter.RemoveFooter(data);
                                        }

                                        //Client is done sending, process the packet
                                        var result = await callback(data);

                                        if (result != null && result.Any())
                                        {
                                            if (PacketFormatter != null)
                                            {
                                                result = PacketFormatter.AddFooter(result);
                                            }
                                            await stream.WriteAsync(result, 0, result.Length, _waitToken);

                                            await stream.FlushAsync(_waitToken);
                                        }

                                        result = null;
                                        data   = null;
                                        break;
                                    }
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }

                        memoryStream.Close();
                        memoryStream.Dispose();
                    }

                    stream.Close();
                    stream.Dispose();
                }

                readBuffer = null;
                client.Client.Disconnect(false);
                client.Close();
                client.Dispose();
            }
        }
Example #16
0
        private WrapperDelegate makeFastWrapper(ConstructorInfo constructorInfo)
        {
            Expression tree               = null;
            var        target             = Expression.Parameter(typeof(object), "target");
            var        context            = Expression.Parameter(typeof(Context), "context");
            var        arguments          = Expression.Parameter(typeof(Expressions.Expression[]), "arguments");
            var        argumentsObjectPrm = Expression.Parameter(typeof(Arguments), "argumentsObject");
            var        argumentsObject    = Expression.Condition(
                Expression.NotEqual(argumentsObjectPrm, Expression.Constant(null)),
                argumentsObjectPrm,
                Expression.Assign(argumentsObjectPrm, Expression.Call(((Func <Expressions.Expression[], Context, Arguments>)Tools.CreateArguments).GetMethodInfo(), arguments, context)));

            if (_parameters.Length == 0)
            {
                tree = Expression.New(constructorInfo);
            }
            else
            {
                if (_parameters.Length == 1 && _parameters[0].ParameterType == typeof(Arguments))
                {
                    tree = Expression.New(constructorInfo, argumentsObject);
                }
                else
                {
                    Func <Expressions.Expression[], Context, int, object> processArg     = processArgument;
                    Func <Expressions.Expression[], Context, int, object> processArgTail = processArgumentsTail;
                    Func <int, JSValue, object> convertArg = convertArgument;

                    var prms = new Expression[_parameters.Length];
                    for (var i = 0; i < prms.Length; i++)
                    {
                        prms[i] = Expression.Convert(
                            Expression.Call(
                                Expression.Constant(this),
                                i + 1 < prms.Length ? processArg.GetMethodInfo() : processArgTail.GetMethodInfo(),
                                arguments,
                                context,
                                Expression.Constant(i)),
                            _parameters[i].ParameterType);
                    }

                    tree = Expression.New(constructorInfo, prms);

                    for (var i = 0; i < prms.Length; i++)
                    {
                        prms[i] = Expression.Convert(
                            Expression.Call(
                                Expression.Constant(this),
                                convertArg.GetMethodInfo(),
                                Expression.Constant(i),
                                Expression.Call(argumentsObject, ArgumentsGetItemMethod, Expression.Constant(i))),
                            _parameters[i].ParameterType);
                    }

                    Expression treeWithObjectAsSource;
                    treeWithObjectAsSource = Expression.New(constructorInfo, prms);

                    tree = Expression.Condition(Expression.Equal(argumentsObjectPrm, Expression.Constant(null)),
                                                tree,
                                                treeWithObjectAsSource);
                }
            }

            try
            {
                return(Expression
                       .Lambda <WrapperDelegate>(
                           Expression.Convert(tree, typeof(object)),
                           constructorInfo.DeclaringType.Name,
                           new[]
                {
                    target,
                    context,
                    arguments,
                    argumentsObjectPrm
                })
                       .Compile());
            }
            catch
            {
                throw;
            }
        }
Example #17
0
        public WeakFunc(object target, Func <TResult> func, bool keepTargetAlive = false)
        {
#if NETFX_CORE
            if (func.GetMethodInfo().IsStatic)
#else
            if (func.Method.IsStatic)
#endif
            {
                _staticFunc = func;

                if (target != null)
                {
                    // Keep a reference to the target to control the
                    // WeakAction's lifetime.
                    Reference = new WeakReference(target);
                }

                return;
            }

#if SILVERLIGHT
            if (!func.Method.IsPublic ||
                (target != null &&
                 !target.GetType().IsPublic &&
                 !target.GetType().IsNestedPublic))
            {
                _func = func;
            }
            else
            {
                var name = func.Method.Name;

                if (name.Contains("<") &&
                    name.Contains(">"))
                {
                    // Anonymous method
                    _func = func;
                }
                else
                {
                    Method        = func.Method;
                    FuncReference = new WeakReference(func.Target);
                    LiveReference = keepTargetAlive ? func.Target : null;
                }
            }
#else
#if NETFX_CORE
            Method = func.GetMethodInfo();
#else
            Method = func.Method;
#endif
            FuncReference = new WeakReference(func.Target);
#endif

            LiveReference = keepTargetAlive ? func.Target : null;
            Reference     = new WeakReference(target);

#if DEBUG
            if (FuncReference != null &&
                FuncReference.Target != null &&
                !keepTargetAlive)
            {
                var type = FuncReference.Target.GetType();

                if (type.Name.StartsWith("<>") &&
                    type.Name.Contains("DisplayClass"))
                {
                    System.Diagnostics.Debug.WriteLine(
                        "You are attempting to register a lambda with a closure without using keepTargetAlive. Are you sure? Check http://galasoft.ch/s/mvvmweakaction for more info.");
                }
            }
#endif
        }
        public override Expression Visit(BinaryOperatorNode nodeIn)
        {
            Expression left  = TranslateNode(nodeIn.Left);
            Expression right = TranslateNode(nodeIn.Right);

            if (left.Type != right.Type)
            {
                Type leftType  = left.Type;
                Type rightType = right.Type;

                if (OeExpressionHelper.IsNullable(left) && !OeExpressionHelper.IsNull(left))
                {
                    if (OeExpressionHelper.IsNull(right))
                    {
                        right = OeConstantToVariableVisitor.NullConstantExpression;
                    }
                    else
                    {
                        leftType = Nullable.GetUnderlyingType(left.Type);
                    }
                }
                else if (OeExpressionHelper.IsNullable(right) && !OeExpressionHelper.IsNull(right))
                {
                    if (OeExpressionHelper.IsNull(left))
                    {
                        left = OeConstantToVariableVisitor.NullConstantExpression;
                    }
                    else
                    {
                        rightType = Nullable.GetUnderlyingType(right.Type);
                    }
                }

                if (right.Type != left.Type)
                {
                    if (left is ConstantExpression)
                    {
                        ConstantExpression oldConstant = left as ConstantExpression;
                        ConstantExpression newConstant = OeExpressionHelper.ConstantChangeType(oldConstant, rightType);
                        if (oldConstant != newConstant)
                        {
                            ReplaceConstant(oldConstant, newConstant);
                        }
                        left = Expression.Convert(newConstant, right.Type);
                    }
                    else if (right is ConstantExpression)
                    {
                        ConstantExpression oldConstant = right as ConstantExpression;
                        ConstantExpression newConstant = OeExpressionHelper.ConstantChangeType(oldConstant, leftType);
                        if (oldConstant != newConstant)
                        {
                            ReplaceConstant(oldConstant, newConstant);
                        }
                        right = Expression.Convert(newConstant, left.Type);
                    }
                    else
                    {
                        Type precedenceType = OeExpressionHelper.GetTypeConversion(left.Type, right.Type);
                        if (left.Type != precedenceType)
                        {
                            left = Expression.Convert(left, precedenceType);
                        }
                        if (right.Type != precedenceType)
                        {
                            right = Expression.Convert(right, precedenceType);
                        }
                    }
                }
            }
            ExpressionType binaryType = OeExpressionHelper.ToExpressionType(nodeIn.OperatorKind);

            if (!(binaryType == ExpressionType.Equal || binaryType == ExpressionType.NotEqual))
            {
                if (left.Type == typeof(String))
                {
                    Func <String, String, int> compareToFunc = String.Compare;
                    MethodCallExpression       compareToCall = Expression.Call(null, compareToFunc.GetMethodInfo(), left, right);
                    return(Expression.MakeBinary(binaryType, compareToCall, OeConstantToVariableVisitor.ZeroStringCompareConstantExpression));
                }

                Type underlyingType;
                if (left.Type.IsEnum)
                {
                    Type enumUnderlyingType = Enum.GetUnderlyingType(left.Type);
                    left  = ConvertEnumExpression(left, enumUnderlyingType);
                    right = ConvertEnumExpression(right, enumUnderlyingType);
                }
                else if ((underlyingType = Nullable.GetUnderlyingType(left.Type)) != null && underlyingType.IsEnum)
                {
                    Type enumUnderlyingType     = Enum.GetUnderlyingType(underlyingType);
                    Type nullableUnderlyingType = typeof(Nullable <>).MakeGenericType(enumUnderlyingType);
                    left  = ConvertEnumExpression(left, nullableUnderlyingType);
                    right = ConvertEnumExpression(right, nullableUnderlyingType);
                }
            }

            return(Expression.MakeBinary(binaryType, left, right));

            UnaryExpression ConvertEnumExpression(Expression e, Type nullableType)
            {
                if (e is UnaryExpression unaryExpression)
                {
                    var value = (ConstantExpression)unaryExpression.Operand;
                    return(Expression.Convert(value, nullableType));
                }

                return(Expression.Convert(e, nullableType));
            }
        }
Example #19
0
 public void AddFunction <TIn, TIn2, TOut>(string rawName, Func <TIn, TIn2, TOut> func)
 {
     AddMethodInfo(rawName, func.Target, func.GetMethodInfo());
 }
Example #20
0
 public TypeTransform AddStaticMethod <T1, T2, TResult>(Func <T1, T2, TResult> method, string tsDecl = null)
 {
     return(AddStaticMethod(method.GetMethodInfo(), tsDecl));
 }
Example #21
0
 public TypeTransform AddExtensionMethod <TResult>(Func <TResult> method, string tsDecl = null)
 {
     return(AddExtensionMethod(method.GetMethodInfo(), tsDecl));
 }
Example #22
0
 /// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary>
 /// <param name="method">The method to invoke.</param>
 /// <param name="options">Options to use for the invocation.</param>
 internal static RemoteInvokeHandle RemoteInvoke(
     Func <Task <int> > method,
     RemoteInvokeOptions options = null)
 {
     return(RemoteInvoke(method.GetMethodInfo(), Array.Empty <string>(), options));
 }
        private Expression ProduceComparatorExpressionForSingleFieldCondition(Expression fieldExpression, Type fieldType, bool isFieldTypeNullable = false)
        {
            // this must determine an appropriate runtime comparison given the field type, the predicate, and the comparand
            TypeCode fieldTypeCode = Type.GetTypeCode(fieldType);

            switch (fieldTypeCode)
            {
            case TypeCode.Boolean:
            {
                this.ThrowOnInvalidFilter(fieldType, !this.comparandBoolean.HasValue);

                switch (this.predicate)
                {
                case Predicate.Equal:
                    // fieldValue == this.comparandBoolean.Value;
                    return(Expression.Equal(fieldExpression, Expression.Constant(this.comparandBoolean.Value, isFieldTypeNullable ? typeof(bool?) : typeof(bool))));

                case Predicate.NotEqual:
                    // fieldValue != this.comparandBoolean.Value;
                    return(Expression.NotEqual(fieldExpression, Expression.Constant(this.comparandBoolean.Value, isFieldTypeNullable ? typeof(bool?) : typeof(bool))));

                default:
                    this.ThrowOnInvalidFilter(fieldType);
                    break;
                }
            }

            break;

            case TypeCode.SByte:
            case TypeCode.Int16:
            case TypeCode.Int32:
            case TypeCode.Int64:
            case TypeCode.Byte:
            case TypeCode.UInt16:
            case TypeCode.UInt32:
            case TypeCode.UInt64:
            case TypeCode.Single:
            case TypeCode.Double:
            {
                if (fieldType.GetTypeInfo().IsEnum)
                {
                    // this is actually an Enum
                    object enumValue = null;
                    try
                    {
                        enumValue = Enum.Parse(fieldType, this.comparand, true);
                    }
                    catch (Exception)
                    {
                        // we must throw unless this.predicate is either Contains or DoesNotContain, in which case it's ok
                        this.ThrowOnInvalidFilter(fieldType, this.predicate != Predicate.Contains && this.predicate != Predicate.DoesNotContain);
                    }

                    Type enumUnderlyingType = fieldType.GetTypeInfo().GetEnumUnderlyingType();

                    switch (this.predicate)
                    {
                    case Predicate.Equal:
                        // fieldValue == enumValue
                        return(Expression.Equal(fieldExpression, Expression.Constant(enumValue, isFieldTypeNullable ? typeof(Nullable <>).MakeGenericType(fieldType) : fieldType)));

                    case Predicate.NotEqual:
                        // fieldValue != enumValue
                        return(Expression.NotEqual(fieldExpression, Expression.Constant(enumValue, isFieldTypeNullable ? typeof(Nullable <>).MakeGenericType(fieldType) : fieldType)));

                    case Predicate.LessThan:
                        // (int)fieldValue < (int)enumValue
                        // (int?)fieldValue < (int?)enumValue
                        Type underlyingType = isFieldTypeNullable ? typeof(Nullable <>).MakeGenericType(enumUnderlyingType) : enumUnderlyingType;
                        return(Expression.LessThan(
                                   Expression.Convert(fieldExpression, underlyingType),
                                   Expression.Convert(Expression.Constant(enumValue, fieldType), underlyingType)));

                    case Predicate.GreaterThan:
                        // (int)fieldValue > (int)enumValue
                        // (int?)fieldValue > (int?)enumValue
                        underlyingType = isFieldTypeNullable ? typeof(Nullable <>).MakeGenericType(enumUnderlyingType) : enumUnderlyingType;
                        return(Expression.GreaterThan(
                                   Expression.Convert(fieldExpression, underlyingType),
                                   Expression.Convert(Expression.Constant(enumValue, fieldType), underlyingType)));

                    case Predicate.LessThanOrEqual:
                        // (int)fieldValue <= (int)enumValue
                        // (int?)fieldValue <= (int?)enumValue
                        underlyingType = isFieldTypeNullable ? typeof(Nullable <>).MakeGenericType(enumUnderlyingType) : enumUnderlyingType;
                        return(Expression.LessThanOrEqual(
                                   Expression.Convert(fieldExpression, underlyingType),
                                   Expression.Convert(Expression.Constant(enumValue, fieldType), underlyingType)));

                    case Predicate.GreaterThanOrEqual:
                        // (int)fieldValue >= (int)enumValue
                        // (int?)fieldValue >= (int?)enumValue
                        underlyingType = isFieldTypeNullable ? typeof(Nullable <>).MakeGenericType(enumUnderlyingType) : enumUnderlyingType;
                        return(Expression.GreaterThanOrEqual(
                                   Expression.Convert(fieldExpression, underlyingType),
                                   Expression.Convert(Expression.Constant(enumValue, fieldType), underlyingType)));

                    case Predicate.Contains:
                        // fieldValue.ToString(CultureInfo.InvariantCulture).IndexOf(this.comparand, StringComparison.OrdinalIgnoreCase) != -1
                        Expression toStringCall = Expression.Call(fieldExpression, isFieldTypeNullable ? ValueTypeToStringMethodInfo : ObjectToStringMethodInfo);
                        Expression indexOfCall  = Expression.Call(toStringCall, StringIndexOfMethodInfo, Expression.Constant(this.comparand), Expression.Constant(StringComparison.OrdinalIgnoreCase));
                        return(Expression.NotEqual(indexOfCall, Expression.Constant(-1)));

                    case Predicate.DoesNotContain:
                        // fieldValue.ToString(CultureInfo.InvariantCulture).IndexOf(this.comparand, StringComparison.OrdinalIgnoreCase) == -1
                        toStringCall = Expression.Call(fieldExpression, isFieldTypeNullable ? ValueTypeToStringMethodInfo : ObjectToStringMethodInfo);
                        indexOfCall  = Expression.Call(toStringCall, StringIndexOfMethodInfo, Expression.Constant(this.comparand), Expression.Constant(StringComparison.OrdinalIgnoreCase));
                        return(Expression.Equal(indexOfCall, Expression.Constant(-1)));

                    default:
                        this.ThrowOnInvalidFilter(fieldType);
                        break;
                    }
                }
                else
                {
                    // this is a regular numerical type
                    // in order for the expression to compile, we must cast to double unless it's already double
                    // we're using double as the lowest common denominator for all numerical types
                    Expression fieldConvertedExpression = fieldTypeCode == TypeCode.Double
                                                                      ? fieldExpression
                                                                      : Expression.ConvertChecked(fieldExpression, isFieldTypeNullable ? typeof(double?) : typeof(double));

                    switch (this.predicate)
                    {
                    case Predicate.Equal:
                        this.ThrowOnInvalidFilter(fieldType, !this.comparandDouble.HasValue);
                        return(Expression.Equal(
                                   fieldConvertedExpression,
                                   Expression.Constant(this.comparandDouble.Value, isFieldTypeNullable ? typeof(Nullable <>).MakeGenericType(typeof(double)) : typeof(double))));

                    case Predicate.NotEqual:
                        this.ThrowOnInvalidFilter(fieldType, !this.comparandDouble.HasValue);
                        return(Expression.NotEqual(
                                   fieldConvertedExpression,
                                   Expression.Constant(this.comparandDouble.Value, isFieldTypeNullable ? typeof(Nullable <>).MakeGenericType(typeof(double)) : typeof(double))));

                    case Predicate.LessThan:
                        this.ThrowOnInvalidFilter(fieldType, !this.comparandDouble.HasValue);
                        return(Expression.LessThan(
                                   fieldConvertedExpression,
                                   Expression.Constant(this.comparandDouble.Value, isFieldTypeNullable ? typeof(Nullable <>).MakeGenericType(typeof(double)) : typeof(double))));

                    case Predicate.GreaterThan:
                        this.ThrowOnInvalidFilter(fieldType, !this.comparandDouble.HasValue);
                        return(Expression.GreaterThan(
                                   fieldConvertedExpression,
                                   Expression.Constant(this.comparandDouble.Value, isFieldTypeNullable ? typeof(Nullable <>).MakeGenericType(typeof(double)) : typeof(double))));

                    case Predicate.LessThanOrEqual:
                        this.ThrowOnInvalidFilter(fieldType, !this.comparandDouble.HasValue);
                        return(Expression.LessThanOrEqual(
                                   fieldConvertedExpression,
                                   Expression.Constant(this.comparandDouble.Value, isFieldTypeNullable ? typeof(Nullable <>).MakeGenericType(typeof(double)) : typeof(double))));

                    case Predicate.GreaterThanOrEqual:
                        this.ThrowOnInvalidFilter(fieldType, !this.comparandDouble.HasValue);
                        return(Expression.GreaterThanOrEqual(
                                   fieldConvertedExpression,
                                   Expression.Constant(this.comparandDouble.Value, isFieldTypeNullable ? typeof(Nullable <>).MakeGenericType(typeof(double)) : typeof(double))));

                    case Predicate.Contains:
                        // fieldValue.ToString(CultureInfo.InvariantCulture).IndexOf(this.comparand, StringComparison.OrdinalIgnoreCase) != -1
                        Expression toStringCall = isFieldTypeNullable
                                                                  ? Expression.Call(fieldConvertedExpression, NullableDoubleToStringMethodInfo)
                                                                  : Expression.Call(fieldConvertedExpression, DoubleToStringMethodInfo, Expression.Constant(CultureInfo.InvariantCulture));
                        Expression indexOfCall = Expression.Call(toStringCall, StringIndexOfMethodInfo, Expression.Constant(this.comparand), Expression.Constant(StringComparison.OrdinalIgnoreCase));
                        return(Expression.NotEqual(indexOfCall, Expression.Constant(-1)));

                    case Predicate.DoesNotContain:
                        // fieldValue.ToString(CultureInfo.InvariantCulture).IndexOf(this.comparand, StringComparison.OrdinalIgnoreCase) == -1
                        toStringCall = isFieldTypeNullable
                                                       ? Expression.Call(fieldConvertedExpression, NullableDoubleToStringMethodInfo)
                                                       : Expression.Call(fieldConvertedExpression, DoubleToStringMethodInfo, Expression.Constant(CultureInfo.InvariantCulture));
                        indexOfCall = Expression.Call(toStringCall, StringIndexOfMethodInfo, Expression.Constant(this.comparand), Expression.Constant(StringComparison.OrdinalIgnoreCase));
                        return(Expression.Equal(indexOfCall, Expression.Constant(-1)));

                    default:
                        this.ThrowOnInvalidFilter(fieldType);
                        break;
                    }
                }
            }

            break;

            case TypeCode.String:
            {
                Expression fieldValueOrEmptyString = Expression.Condition(Expression.Equal(fieldExpression, Expression.Constant(null)), Expression.Constant(string.Empty), fieldExpression);

                Expression indexOfCall = Expression.Call(fieldValueOrEmptyString, StringIndexOfMethodInfo, Expression.Constant(this.comparand), Expression.Constant(StringComparison.OrdinalIgnoreCase));

                switch (this.predicate)
                {
                case Predicate.Equal:
                    // (fieldValue ?? string.Empty).Equals(this.comparand, StringComparison.OrdinalIgnoreCase)
                    return(Expression.Call(fieldValueOrEmptyString, StringEqualsMethodInfo, Expression.Constant(this.comparand), Expression.Constant(StringComparison.OrdinalIgnoreCase)));

                case Predicate.NotEqual:
                    // !(fieldValue ?? string.Empty).Equals(this.comparand, StringComparison.OrdinalIgnoreCase)
                    return(Expression.Not(Expression.Call(fieldValueOrEmptyString, StringEqualsMethodInfo, Expression.Constant(this.comparand), Expression.Constant(StringComparison.OrdinalIgnoreCase))));

                case Predicate.LessThan:
                case Predicate.GreaterThan:
                case Predicate.LessThanOrEqual:
                case Predicate.GreaterThanOrEqual:
                    // double.TryParse(fieldValue, out temp) && temp {<, <=, >, >=} comparandDouble
                    this.ThrowOnInvalidFilter(fieldType, !this.comparandDouble.HasValue);
                    return(this.CreateStringToDoubleComparisonBlock(fieldExpression, this.predicate));

                case Predicate.Contains:
                    // fieldValue => (fieldValue ?? string.Empty).IndexOf(this.comparand, StringComparison.OrdinalIgnoreCase) != -1;
                    return(Expression.NotEqual(indexOfCall, Expression.Constant(-1)));

                case Predicate.DoesNotContain:
                    // fieldValue => (fieldValue ?? string.Empty).IndexOf(this.comparand, StringComparison.OrdinalIgnoreCase) == -1;
                    return(Expression.Equal(indexOfCall, Expression.Constant(-1)));

                default:
                    this.ThrowOnInvalidFilter(fieldType);
                    break;
                }
            }

            break;

            default:
                Type nullableUnderlyingType;
                if (fieldType == typeof(TimeSpan))
                {
                    this.ThrowOnInvalidFilter(fieldType, !this.comparandTimeSpan.HasValue);

                    switch (this.predicate)
                    {
                    case Predicate.Equal:
                        Func <TimeSpan, bool> comparator = fieldValue => fieldValue == this.comparandTimeSpan.Value;
                        return(Expression.Call(Expression.Constant(comparator.Target), comparator.GetMethodInfo(), fieldExpression));

                    case Predicate.NotEqual:
                        comparator = fieldValue => fieldValue != this.comparandTimeSpan.Value;
                        return(Expression.Call(Expression.Constant(comparator.Target), comparator.GetMethodInfo(), fieldExpression));

                    case Predicate.LessThan:
                        comparator = fieldValue => fieldValue < this.comparandTimeSpan.Value;
                        return(Expression.Call(Expression.Constant(comparator.Target), comparator.GetMethodInfo(), fieldExpression));

                    case Predicate.GreaterThan:
                        comparator = fieldValue => fieldValue > this.comparandTimeSpan.Value;
                        return(Expression.Call(Expression.Constant(comparator.Target), comparator.GetMethodInfo(), fieldExpression));

                    case Predicate.LessThanOrEqual:
                        comparator = fieldValue => fieldValue <= this.comparandTimeSpan.Value;
                        return(Expression.Call(Expression.Constant(comparator.Target), comparator.GetMethodInfo(), fieldExpression));

                    case Predicate.GreaterThanOrEqual:
                        comparator = fieldValue => fieldValue >= this.comparandTimeSpan.Value;
                        return(Expression.Call(Expression.Constant(comparator.Target), comparator.GetMethodInfo(), fieldExpression));

                    default:
                        this.ThrowOnInvalidFilter(fieldType);
                        break;
                    }
                }
                else if (fieldType == typeof(Uri))
                {
                    Expression toStringCall = Expression.Call(fieldExpression, UriToStringMethodInfo);

                    Expression fieldValueOrEmptyString = Expression.Condition(Expression.Equal(fieldExpression, Expression.Constant(null)), Expression.Constant(string.Empty), toStringCall);

                    Expression indexOfCall = Expression.Call(fieldValueOrEmptyString, StringIndexOfMethodInfo, Expression.Constant(this.comparand), Expression.Constant(StringComparison.OrdinalIgnoreCase));

                    switch (this.predicate)
                    {
                    case Predicate.Equal:
                        // (fieldValue?.ToString() ?? string.Empty).Equals(this.comparand, StringComparison.OrdinalIgnoreCase)
                        return(Expression.Call(fieldValueOrEmptyString, StringEqualsMethodInfo, Expression.Constant(this.comparand), Expression.Constant(StringComparison.OrdinalIgnoreCase)));

                    case Predicate.NotEqual:
                        // !(fieldValue?.ToString() ?? string.Empty).Equals(this.comparand, StringComparison.OrdinalIgnoreCase)
                        return(Expression.Not(Expression.Call(fieldValueOrEmptyString, StringEqualsMethodInfo, Expression.Constant(this.comparand), Expression.Constant(StringComparison.OrdinalIgnoreCase))));

                    case Predicate.Contains:
                        // fieldValue => (fieldValue?.ToString() ?? string.Empty).IndexOf(this.comparand, StringComparison.OrdinalIgnoreCase) != -1;
                        return(Expression.NotEqual(indexOfCall, Expression.Constant(-1)));

                    case Predicate.DoesNotContain:
                        // fieldValue => (fieldValue?.ToString() ?? string.Empty).IndexOf(this.comparand, StringComparison.OrdinalIgnoreCase) == -1;
                        return(Expression.Equal(indexOfCall, Expression.Constant(-1)));

                    default:
                        this.ThrowOnInvalidFilter(fieldType);
                        break;
                    }
                }
                else if ((nullableUnderlyingType = Nullable.GetUnderlyingType(fieldType)) != null)
                {
                    // make a recursive call for the underlying type
                    return(ProduceComparatorExpressionForSingleFieldCondition(fieldExpression, nullableUnderlyingType, true));
                }
                else
                {
                    this.ThrowOnInvalidFilter(fieldType);
                }

                break;
            }

            return(null);
        }
 /// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary>
 /// <param name="method">The method to invoke.</param>
 /// <param name="start">true if this function should Start the Process; false if that responsibility is left up to the caller.</param>
 internal static RemoteInvokeHandle RemoteInvoke(
     Func <int> method,
     bool start = true)
 {
     return(RemoteInvoke(method.GetMethodInfo(), Array.Empty <string>(), start));
 }
        // REVIEW: It would be nice to support propagation of select metadata.
        public static IDataView Create <TSrc, TDst>(IHostEnvironment env, string name, IDataView input,
                                                    string src, string dst, DataViewType typeSrc, DataViewType typeDst, ValueMapper <TSrc, TDst> mapper,
                                                    ValueGetter <VBuffer <ReadOnlyMemory <char> > > keyValueGetter = null, ValueGetter <VBuffer <ReadOnlyMemory <char> > > slotNamesGetter = null)
        {
            Contracts.CheckValue(env, nameof(env));
            env.CheckNonEmpty(name, nameof(name));
            env.CheckValue(input, nameof(input));
            env.CheckNonEmpty(src, nameof(src));
            env.CheckNonEmpty(dst, nameof(dst));
            env.CheckValue(typeSrc, nameof(typeSrc));
            env.CheckValue(typeDst, nameof(typeDst));
            env.CheckValue(mapper, nameof(mapper));
            env.Check(keyValueGetter == null || typeDst.GetItemType() is KeyType);
            env.Check(slotNamesGetter == null || typeDst.IsKnownSizeVector());

            if (typeSrc.RawType != typeof(TSrc))
            {
                throw env.ExceptParam(nameof(mapper),
                                      "The source column type '{0}' doesn't match the input type of the mapper", typeSrc);
            }
            if (typeDst.RawType != typeof(TDst))
            {
                throw env.ExceptParam(nameof(mapper),
                                      "The destination column type '{0}' doesn't match the output type of the mapper", typeDst);
            }

            bool tmp = input.Schema.TryGetColumnIndex(src, out int colSrc);

            if (!tmp)
            {
                throw env.ExceptParam(nameof(src), "The input data doesn't have a column named '{0}'", src);
            }
            var typeOrig = input.Schema[colSrc].Type;

            // REVIEW: Ideally this should support vector-type conversion. It currently doesn't.
            bool     ident;
            Delegate conv;

            if (typeOrig.SameSizeAndItemType(typeSrc))
            {
                ident = true;
                conv  = null;
            }
            else if (!Conversions.Instance.TryGetStandardConversion(typeOrig, typeSrc, out conv, out ident))
            {
                throw env.ExceptParam(nameof(mapper),
                                      "The type of column '{0}', '{1}', cannot be converted to the input type of the mapper '{2}'",
                                      src, typeOrig, typeSrc);
            }

            var       col = new Column(src, dst);
            IDataView impl;

            if (ident)
            {
                impl = new Impl <TSrc, TDst, TDst>(env, name, input, col, typeDst, mapper, keyValueGetter: keyValueGetter, slotNamesGetter: slotNamesGetter);
            }
            else
            {
                Func <IHostEnvironment, string, IDataView, Column, DataViewType, ValueMapper <int, int>,
                      ValueMapper <int, int>, ValueGetter <VBuffer <ReadOnlyMemory <char> > >, ValueGetter <VBuffer <ReadOnlyMemory <char> > >,
                      Impl <int, int, int> > del = CreateImpl <int, int, int>;
                var meth = del.GetMethodInfo().GetGenericMethodDefinition()
                           .MakeGenericMethod(typeOrig.RawType, typeof(TSrc), typeof(TDst));
                impl = (IDataView)meth.Invoke(null, new object[] { env, name, input, col, typeDst, conv, mapper, keyValueGetter, slotNamesGetter });
            }

            return(new OpaqueDataView(impl));
        }
Example #26
0
 public ITypeDependencyBuilder <T> Creating <TImplementation>(Func <TImplementation> func)
     where TImplementation : T
 {
     return(Creating(func.GetMethodInfo()));
 }
Example #27
0
        /// <summary>
        /// DO NOT USE THIS MANUALLY.
        /// </summary>
        /// <param name="client">DO NOT USE THIS MANUALLY.</param>
        /// <exception cref="InvalidOperationException"/>
        protected internal override void Setup(DiscordClient client)
        {
            if (this.Client != null)
            {
                throw new InvalidOperationException("What did I tell you?");
            }

            this.Client = client;

            this._executed = new AsyncEvent <CommandExecutionEventArgs>(this.Client.EventErrorHandler, "COMMAND_EXECUTED");
            this._error    = new AsyncEvent <CommandErrorEventArgs>(this.Client.EventErrorHandler, "COMMAND_ERRORED");

            this.Client.MessageCreated += this.HandleCommandsAsync;

            if (this.Config.EnableDefaultHelp)
            {
                var dlg = new Func <CommandContext, string[], Task>(this.DefaultHelpAsync);
                var mi  = dlg.GetMethodInfo();
                this.MakeCallable(mi, dlg.Target, out var cbl, out var args);

                var attrs = mi.GetCustomAttributes();
                if (!attrs.Any(xa => xa.GetType() == typeof(CommandAttribute)))
                {
                    return;
                }

                var cmd = new Command();

                var cbas = new List <CheckBaseAttribute>();
                foreach (var xa in attrs)
                {
                    switch (xa)
                    {
                    case CommandAttribute c:
                        cmd.Name = c.Name;
                        break;

                    case AliasesAttribute a:
                        cmd.Aliases = a.Aliases;
                        break;

                    case CheckBaseAttribute p:
                        cbas.Add(p);
                        break;

                    case DescriptionAttribute d:
                        cmd.Description = d.Description;
                        break;

                    case HiddenAttribute h:
                        cmd.IsHidden = true;
                        break;
                    }
                }

                if (this.Config.DefaultHelpChecks != null && this.Config.DefaultHelpChecks.Any())
                {
                    cbas.AddRange(this.Config.DefaultHelpChecks);
                }

                cmd.ExecutionChecks = new ReadOnlyCollection <CheckBaseAttribute>(cbas);
                cmd.Arguments       = args;
                cmd.Callable        = cbl;

                this.AddToCommandDictionary(cmd);
            }
        }
Example #28
0
 /// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary>
 /// <param name="method">The method to invoke.</param>
 /// <param name="options">Options to use for the invocation.</param>
 internal static RemoteInvokeHandle RemoteInvoke(
     Func<int> method, 
     RemoteInvokeOptions options = null)
 {
     return RemoteInvoke(method.GetMethodInfo(), Array.Empty<string>(), options);
 }
Example #29
0
        private NAReplaceTransform(IHost host, ModelLoadContext ctx, IDataView input)
            : base(host, ctx, input, TestType)
        {
            Host.AssertValue(ctx);
            Host.AssertNonEmpty(Infos);

            GetInfoAndMetadata(out _types, out _isNAs);

            // *** Binary format ***
            // <base>
            // for each column:
            //   type and value
            _repValues    = new object[Infos.Length];
            _repIsDefault = new BitArray[Infos.Length];
            var saver = new BinarySaver(Host, new BinarySaver.Arguments());

            for (int iinfo = 0; iinfo < Infos.Length; iinfo++)
            {
                object     repValue;
                ColumnType repType;
                if (!saver.TryLoadTypeAndValue(ctx.Reader.BaseStream, out repType, out repValue))
                {
                    throw Host.ExceptDecode();
                }
                if (!_types[iinfo].ItemType.Equals(repType.ItemType))
                {
                    throw Host.ExceptParam(nameof(input), "Decoded serialization of type '{0}' does not match expected ColumnType of '{1}'", repType.ItemType, _types[iinfo].ItemType);
                }
                // If type is a vector and the value is not either a scalar or a vector of the same size, throw an error.
                if (repType.IsVector)
                {
                    if (!_types[iinfo].IsVector)
                    {
                        throw Host.ExceptParam(nameof(input), "Decoded serialization of type '{0}' cannot be a vector when Columntype is a scalar of type '{1}'", repType, _types[iinfo]);
                    }
                    if (!_types[iinfo].IsKnownSizeVector)
                    {
                        throw Host.ExceptParam(nameof(input), "Decoded serialization for unknown size vector '{0}' must be a scalar instead of type '{1}'", _types[iinfo], repType);
                    }
                    if (_types[iinfo].VectorSize != repType.VectorSize)
                    {
                        throw Host.ExceptParam(nameof(input), "Decoded serialization of type '{0}' must be a scalar or a vector of the same size as Columntype '{1}'",
                                               repType, _types[iinfo]);
                    }

                    // REVIEW: The current implementation takes the serialized VBuffer, densifies it, and stores the values array.
                    // It might be of value to consider storing the VBUffer in order to possibly benefit from sparsity. However, this would
                    // necessitate a reimplementation of the FillValues code to accomodate sparse VBuffers.
                    object[] args = new object[] { repValue, _types[iinfo], iinfo };
                    Func <VBuffer <int>, ColumnType, int, int[]> func = GetValuesArray <int>;
                    var meth = func.GetMethodInfo().GetGenericMethodDefinition().MakeGenericMethod(repType.ItemType.RawType);
                    _repValues[iinfo] = meth.Invoke(this, args);
                }
                else
                {
                    _repValues[iinfo] = repValue;
                }

                Host.Assert(repValue.GetType() == _types[iinfo].RawType || repValue.GetType() == _types[iinfo].ItemType.RawType);
            }
        }
 private MethodInfo CreateSerializeMethod(Func <object, string> serializeMethod) => serializeMethod.GetMethodInfo();
 public InjectionFactory(Func<IUnityContainer, object> factoryFunc)
 {
     var parameters = new Expression[] { Expression.Constant(DummyContainer) };
     this.Factory = factoryFunc.Target == null ? Expression.Call(factoryFunc.GetMethodInfo(), parameters) : Expression.Call(Expression.Constant(factoryFunc.Target), factoryFunc.GetMethodInfo(), parameters);
 }
 public void Register(string endpoint, string version, Func <HttpContext, Task> method)
 {
     MethodRegister(endpoint, version, method.GetMethodInfo());
 }
 private static MethodInfo GetMethodInfoOf <T1, T2>(Func <T1, T2> func)
 {
     Debug.Assert(func != null);
     return(func.GetMethodInfo());
 }
Example #34
0
        private Expression GenerateMethodBody(Operation operation, ParameterExpression contextParameter,
                                              IFunctionRegistry functionRegistry)
        {
            if (operation == null)
            {
                throw new ArgumentNullException("operation");
            }

            if (operation.GetType() == typeof(IntegerConstant))
            {
                IntegerConstant constant = (IntegerConstant)operation;

                double value = constant.Value;
                return(Expression.Constant(value, typeof(double)));
            }
            else if (operation.GetType() == typeof(FloatingPointConstant))
            {
                FloatingPointConstant constant = (FloatingPointConstant)operation;

                return(Expression.Constant(constant.Value, typeof(double)));
            }
            else if (operation.GetType() == typeof(Variable))
            {
                Variable variable = (Variable)operation;

                Func <string, FormulaContext, double> getVariableValueOrThrow = PrecompiledMethods.GetVariableValueOrThrow;
                return(Expression.Call(null,
                                       getVariableValueOrThrow.GetMethodInfo(),
                                       Expression.Constant(variable.Name),
                                       contextParameter));
            }
            else if (operation.GetType() == typeof(Multiplication))
            {
                Multiplication multiplication = (Multiplication)operation;
                Expression     argument1      = GenerateMethodBody(multiplication.Argument1, contextParameter, functionRegistry);
                Expression     argument2      = GenerateMethodBody(multiplication.Argument2, contextParameter, functionRegistry);

                return(Expression.Multiply(argument1, argument2));
            }
            else if (operation.GetType() == typeof(Addition))
            {
                Addition   addition  = (Addition)operation;
                Expression argument1 = GenerateMethodBody(addition.Argument1, contextParameter, functionRegistry);
                Expression argument2 = GenerateMethodBody(addition.Argument2, contextParameter, functionRegistry);

                return(Expression.Add(argument1, argument2));
            }
            else if (operation.GetType() == typeof(Subtraction))
            {
                Subtraction addition  = (Subtraction)operation;
                Expression  argument1 = GenerateMethodBody(addition.Argument1, contextParameter, functionRegistry);
                Expression  argument2 = GenerateMethodBody(addition.Argument2, contextParameter, functionRegistry);

                return(Expression.Subtract(argument1, argument2));
            }
            else if (operation.GetType() == typeof(Division))
            {
                Division   division = (Division)operation;
                Expression dividend = GenerateMethodBody(division.Dividend, contextParameter, functionRegistry);
                Expression divisor  = GenerateMethodBody(division.Divisor, contextParameter, functionRegistry);

                return(Expression.Divide(dividend, divisor));
            }
            else if (operation.GetType() == typeof(Modulo))
            {
                Modulo     modulo   = (Modulo)operation;
                Expression dividend = GenerateMethodBody(modulo.Dividend, contextParameter, functionRegistry);
                Expression divisor  = GenerateMethodBody(modulo.Divisor, contextParameter, functionRegistry);

                return(Expression.Modulo(dividend, divisor));
            }
            else if (operation.GetType() == typeof(Exponentiation))
            {
                Exponentiation exponentation = (Exponentiation)operation;
                Expression     @base         = GenerateMethodBody(exponentation.Base, contextParameter, functionRegistry);
                Expression     exponent      = GenerateMethodBody(exponentation.Exponent, contextParameter, functionRegistry);

                return(Expression.Call(null, typeof(Math).GetRuntimeMethod("Pow", new Type[] { typeof(double), typeof(double) }), @base, exponent));
            }
            else if (operation.GetType() == typeof(UnaryMinus))
            {
                UnaryMinus unaryMinus = (UnaryMinus)operation;
                Expression argument   = GenerateMethodBody(unaryMinus.Argument, contextParameter, functionRegistry);
                return(Expression.Negate(argument));
            }
            else if (operation.GetType() == typeof(And))
            {
                And        and       = (And)operation;
                Expression argument1 = Expression.NotEqual(GenerateMethodBody(and.Argument1, contextParameter, functionRegistry), Expression.Constant(0.0));
                Expression argument2 = Expression.NotEqual(GenerateMethodBody(and.Argument2, contextParameter, functionRegistry), Expression.Constant(0.0));

                return(Expression.Condition(Expression.And(argument1, argument2),
                                            Expression.Constant(1.0),
                                            Expression.Constant(0.0)));
            }
            else if (operation.GetType() == typeof(Or))
            {
                Or         and       = (Or)operation;
                Expression argument1 = Expression.NotEqual(GenerateMethodBody(and.Argument1, contextParameter, functionRegistry), Expression.Constant(0.0));
                Expression argument2 = Expression.NotEqual(GenerateMethodBody(and.Argument2, contextParameter, functionRegistry), Expression.Constant(0.0));

                return(Expression.Condition(Expression.Or(argument1, argument2),
                                            Expression.Constant(1.0),
                                            Expression.Constant(0.0)));
            }
            else if (operation.GetType() == typeof(LessThan))
            {
                LessThan   lessThan  = (LessThan)operation;
                Expression argument1 = GenerateMethodBody(lessThan.Argument1, contextParameter, functionRegistry);
                Expression argument2 = GenerateMethodBody(lessThan.Argument2, contextParameter, functionRegistry);

                return(Expression.Condition(Expression.LessThan(argument1, argument2),
                                            Expression.Constant(1.0),
                                            Expression.Constant(0.0)));
            }
            else if (operation.GetType() == typeof(LessOrEqualThan))
            {
                LessOrEqualThan lessOrEqualThan = (LessOrEqualThan)operation;
                Expression      argument1       = GenerateMethodBody(lessOrEqualThan.Argument1, contextParameter, functionRegistry);
                Expression      argument2       = GenerateMethodBody(lessOrEqualThan.Argument2, contextParameter, functionRegistry);

                return(Expression.Condition(Expression.LessThanOrEqual(argument1, argument2),
                                            Expression.Constant(1.0),
                                            Expression.Constant(0.0)));
            }
            else if (operation.GetType() == typeof(GreaterThan))
            {
                GreaterThan greaterThan = (GreaterThan)operation;
                Expression  argument1   = GenerateMethodBody(greaterThan.Argument1, contextParameter, functionRegistry);
                Expression  argument2   = GenerateMethodBody(greaterThan.Argument2, contextParameter, functionRegistry);

                return(Expression.Condition(Expression.GreaterThan(argument1, argument2),
                                            Expression.Constant(1.0),
                                            Expression.Constant(0.0)));
            }
            else if (operation.GetType() == typeof(GreaterOrEqualThan))
            {
                GreaterOrEqualThan greaterOrEqualThan = (GreaterOrEqualThan)operation;
                Expression         argument1          = GenerateMethodBody(greaterOrEqualThan.Argument1, contextParameter, functionRegistry);
                Expression         argument2          = GenerateMethodBody(greaterOrEqualThan.Argument2, contextParameter, functionRegistry);

                return(Expression.Condition(Expression.GreaterThanOrEqual(argument1, argument2),
                                            Expression.Constant(1.0),
                                            Expression.Constant(0.0)));
            }
            else if (operation.GetType() == typeof(Equal))
            {
                Equal      equal     = (Equal)operation;
                Expression argument1 = GenerateMethodBody(equal.Argument1, contextParameter, functionRegistry);
                Expression argument2 = GenerateMethodBody(equal.Argument2, contextParameter, functionRegistry);

                return(Expression.Condition(Expression.Equal(argument1, argument2),
                                            Expression.Constant(1.0),
                                            Expression.Constant(0.0)));
            }
            else if (operation.GetType() == typeof(NotEqual))
            {
                NotEqual   notEqual  = (NotEqual)operation;
                Expression argument1 = GenerateMethodBody(notEqual.Argument1, contextParameter, functionRegistry);
                Expression argument2 = GenerateMethodBody(notEqual.Argument2, contextParameter, functionRegistry);

                return(Expression.Condition(Expression.NotEqual(argument1, argument2),
                                            Expression.Constant(1.0),
                                            Expression.Constant(0.0)));
            }
            else if (operation.GetType() == typeof(Function))
            {
                Function function = (Function)operation;

                FunctionInfo functionInfo = functionRegistry.GetFunctionInfo(function.FunctionName);
                Type         funcType;
                Type[]       parameterTypes;
                Expression[] arguments;

                if (functionInfo.IsDynamicFunc)
                {
                    funcType       = typeof(DynamicFunc <double, double>);
                    parameterTypes = new Type[] { typeof(double[]) };


                    Expression[] arrayArguments = new Expression[function.Arguments.Count];
                    for (int i = 0; i < function.Arguments.Count; i++)
                    {
                        arrayArguments[i] = GenerateMethodBody(function.Arguments[i], contextParameter, functionRegistry);
                    }

                    arguments    = new Expression[1];
                    arguments[0] = NewArrayExpression.NewArrayInit(typeof(double), arrayArguments);
                }
                else
                {
                    funcType       = GetFuncType(functionInfo.NumberOfParameters);
                    parameterTypes = (from i in Enumerable.Range(0, functionInfo.NumberOfParameters)
                                      select typeof(double)).ToArray();

                    arguments = new Expression[functionInfo.NumberOfParameters];
                    for (int i = 0; i < functionInfo.NumberOfParameters; i++)
                    {
                        arguments[i] = GenerateMethodBody(function.Arguments[i], contextParameter, functionRegistry);
                    }
                }

                Expression getFunctionRegistry = Expression.Property(contextParameter, "FunctionRegistry");

                ParameterExpression functionInfoVariable = Expression.Variable(typeof(FunctionInfo));

                Expression funcInstance;
                if (!functionInfo.IsOverWritable)
                {
                    funcInstance = Expression.Convert(
                        Expression.Property(
                            Expression.Call(
                                getFunctionRegistry,
                                typeof(IFunctionRegistry).GetRuntimeMethod("GetFunctionInfo", new Type[] { typeof(string) }),
                                Expression.Constant(function.FunctionName)),
                            "Function"),
                        funcType);
                }
                else
                {
                    funcInstance = Expression.Constant(functionInfo.Function, funcType);
                }

                return(Expression.Call(
                           funcInstance,
                           funcType.GetRuntimeMethod("Invoke", parameterTypes),
                           arguments));
            }
            else
            {
                throw new ArgumentException(string.Format("Unsupported operation \"{0}\".", operation.GetType().FullName), "operation");
            }
        }
Example #35
0
        /// <summary>
        /// Fill the repValues array with the correct replacement values based on the user-given replacement kinds.
        /// Vectors default to by-slot imputation unless otherwise specified, except for unknown sized vectors
        /// which force across-slot imputation.
        /// </summary>
        private void GetReplacementValues(Arguments args, out object[] repValues, out BitArray[] slotIsDefault)
        {
            repValues     = new object[Infos.Length];
            slotIsDefault = new BitArray[Infos.Length];

            ReplacementKind?[] imputationModes = new ReplacementKind?[Infos.Length];

            List <int> columnsToImpute = null;
            // REVIEW: Would like to get rid of the sourceColumns list but seems to be the best way to provide
            // the cursor with what columns to cursor through.
            HashSet <int> sourceColumns = null;

            for (int iinfo = 0; iinfo < Infos.Length; iinfo++)
            {
                ReplacementKind kind = args.Column[iinfo].Kind ?? args.ReplacementKind;
                switch (kind)
                {
                case ReplacementKind.SpecifiedValue:
                    repValues[iinfo] = GetSpecifiedValue(args.Column[iinfo].ReplacementString, _types[iinfo], _isNAs[iinfo]);
                    break;

                case ReplacementKind.DefaultValue:
                    repValues[iinfo] = GetDefault(_types[iinfo]);
                    break;

                case ReplacementKind.Mean:
                case ReplacementKind.Min:
                case ReplacementKind.Max:
                    if (!_types[iinfo].ItemType.IsNumber && !_types[iinfo].ItemType.IsTimeSpan && !_types[iinfo].ItemType.IsDateTime)
                    {
                        throw Host.Except("Cannot perform mean imputations on non-numeric '{0}'", _types[iinfo].ItemType);
                    }
                    imputationModes[iinfo] = kind;
                    Utils.Add(ref columnsToImpute, iinfo);
                    Utils.Add(ref sourceColumns, Infos[iinfo].Source);
                    break;

                default:
                    Host.Assert(false);
                    throw Host.Except("Internal error, undefined ReplacementKind '{0}' assigned in NAReplaceTransform.", kind);
                }
            }

            // Exit if there are no columns needing a replacement value imputed.
            if (Utils.Size(columnsToImpute) == 0)
            {
                return;
            }

            // Impute values.
            using (var ch = Host.Start("Computing Statistics"))
                using (var cursor = Source.GetRowCursor(sourceColumns.Contains))
                {
                    StatAggregator[] statAggregators = new StatAggregator[columnsToImpute.Count];
                    for (int ii = 0; ii < columnsToImpute.Count; ii++)
                    {
                        int  iinfo  = columnsToImpute[ii];
                        bool bySlot = args.Column[ii].Slot ?? args.ImputeBySlot;
                        if (_types[iinfo].IsVector && !_types[iinfo].IsKnownSizeVector && bySlot)
                        {
                            ch.Warning("By-slot imputation can not be done on variable-length column");
                            bySlot = false;
                        }
                        statAggregators[ii] = CreateStatAggregator(ch, _types[iinfo], imputationModes[iinfo], bySlot,
                                                                   cursor, Infos[iinfo].Source);
                    }

                    while (cursor.MoveNext())
                    {
                        for (int ii = 0; ii < statAggregators.Length; ii++)
                        {
                            statAggregators[ii].ProcessRow();
                        }
                    }

                    for (int ii = 0; ii < statAggregators.Length; ii++)
                    {
                        repValues[columnsToImpute[ii]] = statAggregators[ii].GetStat();
                    }

                    ch.Done();
                }

            // Construct the slotIsDefault bit arrays.
            for (int ii = 0; ii < columnsToImpute.Count; ii++)
            {
                int slot = columnsToImpute[ii];
                if (repValues[slot] is Array)
                {
                    Func <ColumnType, int[], BitArray> func = ComputeDefaultSlots <int>;
                    var meth = func.GetMethodInfo().GetGenericMethodDefinition().MakeGenericMethod(_types[slot].ItemType.RawType);
                    slotIsDefault[slot] = (BitArray)meth.Invoke(this, new object[] { _types[slot], repValues[slot] });
                }
            }
        }
 public void Register <TReq, TRes>(string endpoint, string version, Func <HttpContext, TReq, Task <TRes> > method, string schema)
 {
     MethodRegister(endpoint, version, method.GetMethodInfo(), schema);
 }
Example #37
0
 /// <summary>
 /// Returns the MethodInfo for the given delegate.
 /// </summary>
 public static MethodInfo Fn <T1, T2>(Func <T1, T2> fn)
 {
     Contracts.AssertValue(fn);
     Contracts.Assert(fn.Target == null);
     return(fn.GetMethodInfo());
 }
Example #38
0
        ReturnsLazily <TReturnType, T1, T2, T3>(this IReturnValueConfiguration <ValueTask <TReturnType> > configuration, Func <T1, T2, T3, TReturnType> valueProducer)
        {
            Guard.AgainstNull(configuration, nameof(configuration));
            Guard.AgainstNull(valueProducer, nameof(valueProducer));

            return(configuration.ReturnsLazily(call =>
            {
                ValueProducerSignatureHelper.AssertThatValueProducerSignatureSatisfiesCallSignature(call.Method, valueProducer.GetMethodInfo(), NameOfReturnsLazilyFeature);

                return new ValueTask <TReturnType>(valueProducer(call.GetArgument <T1>(0), call.GetArgument <T2>(1), call.GetArgument <T3>(2)));
            }));
        }