System.Delegate.DynamicInvoke(params object[])

Here are the examples of the csharp api System.Delegate.DynamicInvoke(params object[]) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

692 Examples 7

19 View Source File : BSEvents.cs
License : MIT License
Project Creator : andruzzzhka

public void InvokeAll(Action action, params object[] args)
        {
            if (action == null) return;
            foreach (Delegate invoc in action.GetInvocationList())
            {
                try
                {
                    invoc?.DynamicInvoke(args);
                }
                catch (Exception e)
                {
                    Console.WriteLine($"Caught Exception when executing event");
                    Console.WriteLine(e);
                }
            }
        }

19 View Source File : Argument.cs
License : MIT License
Project Creator : AutoReviser

private static object CastIfNeeded(object value, Type type)
        {
            if (value == null)
            {
                return value;
            }

            if (value.GetType() == type)
            {
                return value;
            }

            // TODO: Cache the lambda Delegate.
            ParameterExpression parameter = Expression.Parameter(value.GetType());
            UnaryExpression body = Expression.Convert(parameter, type);
            LambdaExpression lambda = Expression.Lambda(body, parameter);
            return lambda.Compile().DynamicInvoke(value);
        }

19 View Source File : EventHandlerExtensions.cs
License : Apache License 2.0
Project Creator : AlexWan

public static void InvokeAll<TMessage>(this EventHandler<KrakenMessageEventArgs<TMessage>> eventHandler, object sender, TMessage message)
            where TMessage : IKrakenMessage, new()
        {
            var invocationList = eventHandler?.GetInvocationList();
            if (invocationList == null) return;
            foreach (var handler in invocationList)
            {
                handler.DynamicInvoke(sender, new KrakenMessageEventArgs<TMessage>(message));
            }
        }

19 View Source File : ShutdownEventCatcher.cs
License : MIT License
Project Creator : andruzzzhka

static void RaiseShutdownEvent(ShutdownEventArgs args)
        {
            foreach(var action in Shutdown.GetInvocationList())
            {
                try
                {
                    action.DynamicInvoke(args);
                }
                catch (Exception e)
                {
                    Logger.Instance.Warning($"Exception on Shutdown event in {action.Target.GetType().ToString()}.{action.Method.Name}: {e}");
                }
            }
        }

19 View Source File : ExpressionCompilationTests.cs
License : Apache License 2.0
Project Creator : alexz76

[Fact(Skip = "Ongoing tests")]
		public void OngoingTestLab()
		{
			// Arrange
			Expression<Func<ResourceModel, string>> expression = r => $"/api/resource/{r.Id}";

			var parameter = expression.Parameters[0];
			var body = expression.Body as MethodCallExpression;

			var argumentType = typeof(ResourceModel);
			var argumentAtRuntime = Activator.CreateInstance(argumentType);

			// Act
			var results = Expression.Lambda(body, parameter).Compile().DynamicInvoke(argumentAtRuntime);

			// replacedert
			results.Should().BeNull();
		}

19 View Source File : LinqToSql.cs
License : MIT License
Project Creator : AlenToma

protected object GetSingleValue(Expression ex)
        {
            if (ex.NodeType == ExpressionType.MemberAccess)
            {
                if (ex.ToString().Contains("DisplayClreplaced") || (ex as MemberExpression).Expression == null)
                    return Expression.Lambda(ex).Compile().DynamicInvoke();
                var member = (ex as MemberExpression).Expression as ConstantExpression;
                if (member?.Value.GetType().GetFields(_bindingFlags).Length > 0)
                    return member?.Value.GetType().GetFields(_bindingFlags).First().GetValue(member.Value);
                else if (member?.Value.GetType().GetProperties().Length > 0)
                    return member?.Value.GetType().GetProperties().First().GetValue(member.Value);
                else
                    return null;
            }
            else
            {
                var member = (ex as ConstantExpression);
                return member?.Value;
            }
        }

19 View Source File : WorkQueue.cs
License : MIT License
Project Creator : ansel86castro

private async void LoopMain()
        {
            while (running)
            {
                WorkItem workItem = new WorkItem();
                lock (lockItem)
                {
                    if (queue.Count > 0)
                    {
                        workItem = queue.Dequeue();
                    }
                    else
                    {
                        waiting = true;
                    }
                }

                if (waiting)
                {
                    waitHandle.WaitOne();
                    waiting = false;
                }

                else if (workItem.Action != null && !workItem.CancellationToken.IsCancellationRequested)
                {
                    await (Task)workItem.Action.DynamicInvoke(workItem.Args);
                    workItem.WaitHandler.Set();
                }

            }
        }

19 View Source File : ExpressionResolver.cs
License : MIT License
Project Creator : 17MKH

private static object ResolveDynamicInvoke(Expression exp)
    {
        var value = Expression.Lambda(exp).Compile().DynamicInvoke();
        if (exp.Type.IsEnum)
            value = value.ToInt();

        return value;
    }

19 View Source File : WeakEventManagerBase.cs
License : MIT License
Project Creator : AvaloniaUI

public virtual bool DeliverEvent(object sender, TEventArgs args)
            {
                var hreplacedtaleEntries = false;

                foreach (var handler in _handlers)
                {
                    if (handler.IsActive)
                    {
                        var @delegate = handler.Handler as Delegate;
                        @delegate?.DynamicInvoke(sender, args);
                    }
                    else
                    {
                        hreplacedtaleEntries = true;
                    }
                }

                return hreplacedtaleEntries;
            }

19 View Source File : DataFilterUtil.cs
License : MIT License
Project Creator : 2881099

internal static void SetRepositoryDataFilter(object repos, Action<FluentDataFilter> scopedDataFilter) {
			if (scopedDataFilter != null) {
				SetRepositoryDataFilter(repos, null);
			}
			if (scopedDataFilter == null) {
				scopedDataFilter = _globalDataFilter;
			}
			if (scopedDataFilter == null) return;
			using (var globalFilter = new FluentDataFilter()) {
				scopedDataFilter(globalFilter);

				var type = repos.GetType();
				Type enreplacedyType = (repos as IBaseRepository).EnreplacedyType;
				if (enreplacedyType == null) throw new Exception("FreeSql.Repository 设置过滤器失败,原因是对象不属于 IRepository");

				var notExists = _dicSetRepositoryDataFilterConvertFilterNotExists.GetOrAdd(type, t => new ConcurrentDictionary<string, bool>());
				var newFilter = new Dictionary<string, LambdaExpression>();
				foreach (var gf in globalFilter._filters) {
					if (notExists.ContainsKey(gf.name)) continue;

					LambdaExpression newExp = null;
					var filterParameter1 = Expression.Parameter(enreplacedyType, gf.exp.Parameters[0].Name);
					try {
						newExp = Expression.Lambda(
							typeof(Func<,>).MakeGenericType(enreplacedyType, typeof(bool)),
							new ReplaceVisitor().Modify(gf.exp.Body, filterParameter1),
							filterParameter1
						);
					} catch {
						notExists.TryAdd(gf.name, true); //防止第二次错误
						continue;
					}
					newFilter.Add(gf.name, newExp);
				}
				if (newFilter.Any() == false) return;

				var del = _dicSetRepositoryDataFilterApplyDataFilterFunc.GetOrAdd(type, t => {
					var reposParameter = Expression.Parameter(type);
					var nameParameter = Expression.Parameter(typeof(string));
					var expressionParameter = Expression.Parameter(
						typeof(Expression<>).MakeGenericType(typeof(Func<,>).MakeGenericType(enreplacedyType, typeof(bool)))
					);
					return Expression.Lambda(
						Expression.Block(
							Expression.Call(reposParameter, type.GetMethod("ApplyDataFilter", BindingFlags.Instance | BindingFlags.NonPublic), nameParameter, expressionParameter)
						),
						new[] {
						reposParameter, nameParameter, expressionParameter
						}
					).Compile();
				});
				foreach (var nf in newFilter) {
					del.DynamicInvoke(repos, nf.Key, nf.Value);
				}
				newFilter.Clear();
			}
		}

19 View Source File : RecurringJobRegistry.cs
License : MIT License
Project Creator : AlphaYu

public void Register(string recurringJobId, MethodInfo method, string cron, TimeZoneInfo timeZone, string queue)
		{
			if (recurringJobId == null) throw new ArgumentNullException(nameof(recurringJobId));
			if (method == null) throw new ArgumentNullException(nameof(method));
			if (cron == null) throw new ArgumentNullException(nameof(cron));
			if (timeZone == null) throw new ArgumentNullException(nameof(timeZone));
			if (queue == null) throw new ArgumentNullException(nameof(queue));

			var parameters = method.GetParameters();

			Expression[] args = new Expression[parameters.Length];

			for (int i = 0; i < parameters.Length; i++)
			{
				args[i] = Expression.Default(parameters[i].ParameterType);
			}

			var x = Expression.Parameter(method.DeclaringType, "x");

			var methodCall = method.IsStatic ? Expression.Call(method, args) : Expression.Call(x, method, args);

			var addOrUpdate = Expression.Call(
				typeof(RecurringJob),
				nameof(RecurringJob.AddOrUpdate),
				new Type[] { method.DeclaringType },
				new Expression[]
				{
					Expression.Constant(recurringJobId),
					Expression.Lambda(methodCall, x),
					Expression.Constant(cron),
					Expression.Constant(timeZone),
					Expression.Constant(queue)
				});

			Expression.Lambda(addOrUpdate).Compile().DynamicInvoke();
		}

19 View Source File : ExpressionCompilationTests.cs
License : Apache License 2.0
Project Creator : alexz76

[Fact]
		public void MethodCallExpression_Should_CompileAndReturnResult()
		{
			// Arrange
			var argument = new ResourceModel();
			Expression<Func<ResourceModel, string>> expression = r => $"/api/resource/{r.Id}";

			var parameter = expression.Parameters[0];
			var body = expression.Body as MethodCallExpression;

			// Act
			var results = Expression.Lambda(body, parameter).Compile().DynamicInvoke(argument);

			// replacedert
			results.Should().NotBeNull();
			results.ToString().Should().StartWith("/api/resource/");
		}

19 View Source File : ApiAction.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public override IApiResult Execute()
        {
            if (ArgumenType == null)
            {
                var action = Method.CreateDelegate(typeof(ApiDelegate), new TControler());
                return action.DynamicInvoke() as IApiResult;
            }
            else
            {
                var action = Method.CreateDelegate(typeof(ApiDelegate1), new TControler());
                return action.DynamicInvoke(_argument) as IApiResult;
            }
        }

19 View Source File : BSEvents.cs
License : MIT License
Project Creator : andruzzzhka

public void InvokeAll<T1, T2>(Action<T1, T2> action, params object[] args)
        {
            if (action == null) return;
            foreach (Delegate invoc in action.GetInvocationList())
            {
                try
                {
                    invoc?.DynamicInvoke(args);
                }
                catch (Exception e)
                {
                    Console.WriteLine($"Caught Exception when executing event");
                    Console.WriteLine(e);
                }
            }
        }

19 View Source File : XnaToFnaHelper.cs
License : zlib License
Project Creator : 0x0ade

public static void ApplyWindowChanges(
            IntPtr window,
            int clientWidth,
            int clientHeight,
            bool wantsFullscreen,
            string screenDeviceName,
            ref string resultDeviceName
        ) {
            object[] args = { window, clientWidth, clientHeight, wantsFullscreen, screenDeviceName, resultDeviceName };
            fna_ApplyWindowChanges.DynamicInvoke(args);
            resultDeviceName = (string) args[5];

            GameForm.Instance?.SDLWindowChanged(window, clientWidth, clientHeight, wantsFullscreen, screenDeviceName, ref resultDeviceName);

            if (resultDeviceName != screenDeviceName) {
                // TODO: Does a WM_ message exist for this? Why did I put this empty check in here? git blame myself.
            }
        }

19 View Source File : ExpressionHelpers.cs
License : MIT License
Project Creator : angelsix

public static void SetPropertyValue<T>(this Expression<Func<T>> lambda, object value)
        {
            // Get the member expression
            var expression = GetMemberExpression(lambda);

            // Get the property info from the member
            var propertyInfo = (PropertyInfo)expression.Member;

            // Create a target value to set the property
            var target = Expression.Lambda(expression.Expression).Compile().DynamicInvoke();

            // Reflect to set the property value
            propertyInfo.SetValue(target, value);
        }

19 View Source File : LinqToSql.cs
License : MIT License
Project Creator : AlenToma

protected object VisitMember(MemberExpression m, bool columnOnly)
        {
            try
            {
                if (m.Expression != null && m.Expression.NodeType == ExpressionType.Constant && (_overridedNodeType == null))
                {
                    VisitConstantFixed(m.Expression as ConstantExpression, m.Member?.Name);
                    return m;
                }
                else if (m.Expression?.ToString().Contains("DisplayClreplaced") ?? false || m.Expression == null)
                {
                    var hasValueAttr = m.ToString().EndsWith(".HasValue");
                    bool isNot = sb.ToString().EndsWith("NOT ");
                    var value = ValuetoSql(Expression.Lambda(m).Compile().DynamicInvoke());
                    var column = value;
                    if (isNot)
                    {
                        var invert = GetInvert();
                        column = $"(CASE WHEN {value} = {boolString.Replace("#", "0T")} THEN {boolString.Replace("#", "0T")} ELSE {boolString.Replace("#", "1T")} END) {boolString.Replace("#", "0")}";
                    }
                    else if (hasValueAttr)
                    {
                        column = $"(CASE WHEN {value} = {boolString.Replace("#", "0T")} THEN {boolString.Replace("#", "0T")} ELSE {boolString.Replace("#", "1T")} END) {boolString.Replace("#", "1")}";
                    }


                    CleanDecoder(column);
                    return m;
                }
                else if (m.Expression != null && (m.Expression.NodeType == ExpressionType.Parameter || (m.ToString().EndsWith(".HasValue") && m.Expression.NodeType == ExpressionType.MemberAccess)) && (_overridedNodeType == null))
                {
                    var hasValueAttr = m.ToString().EndsWith(".HasValue");
                    _overridedNodeType = null;
                    var cl = hasValueAttr ? (m.Expression as MemberExpression).Expression.Type : m.Expression.Type;
                    var prop = DeepCloner.GetFastDeepClonerProperties(cl).First(x => x.Name == (hasValueAttr ? (m.Expression as MemberExpression).Member.Name : m.Member.Name));
                    var name = prop.GetPropertyName();
                    var table = cl.TableName().GetName(DataBaseTypes);
                    var columnName = string.Format("{0}.[{1}]", table, name).CleanValidSqlName(DataBaseTypes);
                    var dataEncode = prop.GetCustomAttribute<DataEncode>();
                    if (columnOnly)
                        return columnName;

                    bool isNot = sb.ToString().EndsWith("NOT ");
                    if (prop.PropertyType.IsEnum && prop.ContainAttribute<Stringify>())
                    {
                        if (!SavedTypes.ContainsKey(prop.FullName))
                            SavedTypes.TryAdd(prop.FullName, prop.PropertyType);
                        columnName += stringyFy.Replace("#", prop.FullName);
                    }
                    if (isNot)
                    {
                        var invert = GetInvert();
                        if (!hasValueAttr)
                            columnName = $"(CASE WHEN {columnName} = {boolString.Replace("#", "0T")} THEN {boolString.Replace("#", "1T")} ELSE {boolString.Replace("#", "0T")} END) {boolString.Replace("#", "0")}";
                        else
                            columnName = $"(CASE WHEN {columnName} IS NULL THEN {boolString.Replace("#", "0T")} ELSE {boolString.Replace("#", "1T")} END) {boolString.Replace("#", "0")}";
                    }
                    else if (hasValueAttr)
                    {
                        columnName = $"(CASE WHEN {columnName} IS NULL THEN {boolString.Replace("#", "0T")} ELSE {boolString.Replace("#", "1T")} END) {boolString.Replace("#", "1")}";
                    }
                    else if (prop.PropertyType == typeof(bool) || prop.PropertyType == typeof(bool?))
                        columnName = columnName + boolString.Replace("#", "1");

                    if (dataEncode != null)
                        columnName = columnName + dataEncodeString.Replace("#", dataEncode.Key + "|" + ((int)dataEncode.KeySize).ToString());
                    sb.Append(columnName);
                    return m;
                }
                else if (m.Expression != null && (m.Expression.NodeType == ExpressionType.MemberAccess))
                {
                    _overridedNodeType = null;
                    var key = string.Join("", m.ToString().Split('.').Take(m.ToString().Split('.').Length - 1));
                    var cl = m.Expression.Type;
                    if (cl.IsInterface)
                    {
                        var pr = (m.Expression as MemberExpression).Expression.Type;
                        var tb = m.Expression.ToString().Split('.').Last();
                        cl = DeepCloner.GetProperty(pr, tb)?.PropertyType ?? cl;

                    }


                    var prop = DeepCloner.GetFastDeepClonerProperties(cl).First(x => x.Name == m.Member.Name);
                    var name = prop.GetPropertyName();
                    var table = cl.TableName();
                    var randomTableName = JoinClauses.ContainsKey(key) ? JoinClauses[key].Item1 : RandomKey();
                    var primaryId = DeepCloner.GetFastDeepClonerProperties(cl).First(x => x.ContainAttribute<PrimaryKey>()).GetPropertyName();
                    var columnName = string.Format("[{0}].[{1}]", randomTableName, name).CleanValidSqlName(DataBaseTypes);
                    if (columnOnly)
                        return columnName;
                    sb.Append(columnName);
                    if (JoinClauses.ContainsKey(key))
                        return m;
                    // Ok lets build inner join 
                    var parentType = (m.Expression as MemberExpression).Expression.Type;
                    var parentTable = parentType.TableName();
                    prop = DeepCloner.GetFastDeepClonerProperties(parentType).FirstOrDefault(x => x.ContainAttribute<ForeignKey>() && x.GetCustomAttribute<ForeignKey>().Type == cl);
                    var v = "";
                    if (prop != null)
                    {
                        v += string.Format("LEFT JOIN {0} {1} ON [{2}].[{3}] = {4}.[{5}]", table.GetName(DataBaseTypes), randomTableName, randomTableName, primaryId, parentTable.GetName(DataBaseTypes), prop.GetPropertyName()).CleanValidSqlName(DataBaseTypes);
                    }
                    else
                    {
                        prop = DeepCloner.GetFastDeepClonerProperties(cl).FirstOrDefault(x => x.ContainAttribute<ForeignKey>() && x.GetCustomAttribute<ForeignKey>().Type == parentType);
                        if (prop != null)
                            v += string.Format("LEFT JOIN {0} {1} ON [{2}].[{3}] = {4}.[{5}]", table.GetName(DataBaseTypes), randomTableName, randomTableName, prop.GetPropertyName(), parentTable.GetName(DataBaseTypes), primaryId).CleanValidSqlName(DataBaseTypes);
                    }

                    if (string.IsNullOrEmpty(v))
                    {
                        sb = sb.Remove(sb.Length - columnName.Length, columnName.Length);
                        CleanDecoder(ValuetoSql(GetValue(m)));
                    }
                    else
                    {
                        JoinClauses.TryAdd(key, new Tuple<string, string>(randomTableName, v));
                    }


                    return m;
                }
                else if (m.Expression != null && _overridedNodeType == ExpressionType.MemberAccess)
                {
                    _overridedNodeType = null;
                    var key = string.Join("", m.ToString().Split('.').Take(m.ToString().Split('.').Length - 1));
                    var cl = m.Expression.Type;
                    if (cl.IsInterface)
                    {
                        var pr = (m.Expression as MemberExpression).Expression.Type.GetActualType();
                        var tb = m.Expression.ToString().Split('.').Last();
                        cl = DeepCloner.GetProperty(pr, tb)?.PropertyType ?? cl;
                    }

                    var prop = DeepCloner.GetFastDeepClonerProperties(cl).First(x => x.Name == m.Member.Name);
                    var table = cl.TableName();
                    var randomTableName = JoinClauses.ContainsKey(key) ? JoinClauses[key].Item1 : RandomKey();
                    var primaryId = DeepCloner.GetFastDeepClonerProperties(cl).First(x => x.ContainAttribute<PrimaryKey>()).GetPropertyName();
                    if (JoinClauses.ContainsKey(key))
                        return m;
                    // Ok lets build inner join 
                    var parentType = (m as MemberExpression).Type.GetActualType();
                    var parentTable = parentType.TableName();
                    prop = DeepCloner.GetFastDeepClonerProperties(parentType).FirstOrDefault(x => x.ContainAttribute<ForeignKey>() && x.GetCustomAttribute<ForeignKey>().Type == cl);
                    var v = "";
                    if (prop != null)
                    {
                        v += string.Format("INNER JOIN {0} {1} ON {2}.[{3}] = [{4}].[{5}]", parentTable.GetName(DataBaseTypes), randomTableName, table.GetName(DataBaseTypes), primaryId, randomTableName, prop.GetPropertyName()).CleanValidSqlName(DataBaseTypes);
                    }
                    else
                    {
                        throw new EnreplacedyException(string.Format("Expression STRUCTURE IS NOT SUPPORTED MEMBER{0} for EnreplacedyWorker", m.Member.Name));
                    }

                    if (!string.IsNullOrEmpty(v))
                        JoinClauses.TryAdd(key, new Tuple<string, string>(randomTableName, v));
                    return m;
                }

            }
            catch
            {
                throw new EnreplacedyException(string.Format("Expression '{0}' is not supported", m.ToString()));
            }

            if (m.Type.IsInternalType() && m.Expression.NodeType == ExpressionType.Call)
            {
                CleanDecoder(ValuetoSql(Expression.Lambda(m).Compile().DynamicInvoke()));
                return m;
            }
            throw new EnreplacedyException(string.Format("The member '{0}' is not supported", m.Member.Name));
        }

19 View Source File : AppBuilder.cs
License : Apache License 2.0
Project Creator : aspnet

private object ConvertOneHop(Type signature, object app)
        {
            if (signature.IsInstanceOfType(app))
            {
                return app;
            }
            if (typeof(Delegate).IsreplacedignableFrom(signature))
            {
                Delegate memberDelegate = ToMemberDelegate(signature, app);
                if (memberDelegate != null)
                {
                    return memberDelegate;
                }
            }
            foreach (var conversion in _conversions)
            {
                Type returnType = conversion.Key.Item1;
                Type parameterType = conversion.Key.Item2;
                if (parameterType.IsInstanceOfType(app) &&
                    signature.IsreplacedignableFrom(returnType))
                {
                    return conversion.Value.DynamicInvoke(app);
                }
            }
            return null;
        }

19 View Source File : Control.cs
License : zlib License
Project Creator : 0x0ade

public object Invoke(Delegate method) {
            return method.DynamicInvoke();
        }

19 View Source File : WeakDelegatesManager.cs
License : MIT License
Project Creator : AvaloniaCommunity

public void Raise(params object[] args)
        {
            this.listeners.RemoveAll(listener => listener.Target == null);

            foreach (Delegate handler in this.listeners.ToList().Select(listener => listener.Target).Where(listener => listener != null))
            {
                handler.DynamicInvoke(args);
            }
        }

19 View Source File : EventHandlerExtensions.cs
License : Apache License 2.0
Project Creator : AlexWan

public static void InvokeAll<TData>(this EventHandler<KrakenPrivateEventArgs<TData>> eventHandler, object sender, KrakenPrivateEventArgs<TData> eventArgs)
        {
            var invocationList = eventHandler?.GetInvocationList();
            if (invocationList == null) return;
            foreach (var handler in invocationList)
            {
                handler.DynamicInvoke(sender, eventArgs);
            }
        }

19 View Source File : HateoasResultProvider.cs
License : Apache License 2.0
Project Creator : alexz76

private object GetLambdaResult(Expression expression, object sourcePayload)
		{
			var lambdaExpression = (expression as LambdaExpression);

			if (lambdaExpression == null)
				return null;

			var body = lambdaExpression.Body;
			var parameter = lambdaExpression.Parameters[0];

			return Expression.Lambda(body, parameter).Compile().DynamicInvoke(sourcePayload);
		}

19 View Source File : Control.cs
License : zlib License
Project Creator : 0x0ade

public object Invoke(Delegate method, params object[] args) {
            return method.DynamicInvoke(args);
        }

19 View Source File : ExpressionCompilationTests.cs
License : Apache License 2.0
Project Creator : alexz76

[Theory]
		[InlineData("F52813B6-346C-11E9-874F-0A27172E52BC")]
		[InlineData("F528191A-346C-11E9-874F-0A27172E52BC")]
		[InlineData("F5281D16-346C-11E9-874F-0A27172E52BC")]
		public void MethodCallExpression_Should_CompileAndReturnResults_ForReflectedTypes(string argumentIdValue)
		{
			// Arrange
			Expression<Func<BookViewModel, string>> expression = r => $"/api/resource/{r.Id}";

			var parameter = expression.Parameters[0];
			var body = expression.Body as MethodCallExpression;

			var sourcePayload = new BookViewModel
			{
				replacedle = argumentIdValue,
				Id = Guid.Parse(argumentIdValue)
			};

			// Act
			var results = Expression.Lambda(body, parameter).Compile().DynamicInvoke(sourcePayload);

			// replacedert
			results.Should().NotBeNull();
			results.ToString().ToLower().Should().Be($"/api/resource/{argumentIdValue.ToLower()}");
		}

19 View Source File : DynamicDNAConverterBehaviourEditor.cs
License : Apache License 2.0
Project Creator : A7ocin

private void ImportConverterDropArea(Rect dropArea, int addMethod, Action<DynamicDNAConverterBehaviour, int> callback )
		{
			Event evt = Event.current;
			if (evt.type == EventType.DragUpdated)
			{
				if (dropArea.Contains(evt.mousePosition))
				{
					DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
				}
				Event.current.Use();
				return;
			}
			if (evt.type == EventType.DragPerform)
			{
				if (dropArea.Contains(evt.mousePosition))
				{
					DragAndDrop.AcceptDrag();

					UnityEngine.Object[] draggedObjects = DragAndDrop.objectReferences as UnityEngine.Object[];
					for (int i = 0; i < draggedObjects.Length; i++)
					{
						if (draggedObjects[i])
						{
							GameObject tempDnaGO = draggedObjects[i] as GameObject;
							DynamicDNAConverterBehaviour tempDnareplacedet = tempDnaGO.GetComponent<DynamicDNAConverterBehaviour>();
							if (tempDnareplacedet)
							{
								callback.DynamicInvoke(tempDnareplacedet, addMethod);
								continue;
							}

							var path = replacedetDatabase.GetreplacedetPath(draggedObjects[i]);
							if (System.IO.Directory.Exists(path))
							{
								RecursiveScanFoldersForreplacedets(path, callback, addMethod);
							}
						}
					}
				}
				Event.current.Use();
				return;
			}
		}

19 View Source File : KeyedPropertyInfo.cs
License : MIT License
Project Creator : AlFasGD

public virtual void Set(object instance, object newValue) => SetMethodDelegate?.DynamicInvoke(instance, newValue);

19 View Source File : ExpressionCompilationTests.cs
License : Apache License 2.0
Project Creator : alexz76

[Fact]
		public void ConstantExpression_Should_CompiledAndReturnResult()
		{
			// Arrange
			const string value = "/api/get/{0}";
			var constant = Expression.Constant(value, typeof(string));

			// Act
			var result = Expression.Lambda(constant).Compile().DynamicInvoke();

			// replacedert
			result.Should().Be(value);
		}

19 View Source File : ApiAction.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public override IApiResult Execute()
        {
            if (ArgumenType == null)
            {
                var action = Method.CreateDelegate(typeof(ApiDelegate), new TControler());
                return action.DynamicInvoke() as IApiResult;
            }
            else
            {
                var action = Method.CreateDelegate(typeof(ApiDelegate1), new TControler());
                return action.DynamicInvoke(_argument) as IApiResult;
            }
        }

19 View Source File : EventExtensions.cs
License : GNU General Public License v3.0
Project Creator : AndreiFedarets

public static void RaiseEventSilent<T>(EventHandler<T> commonHandler, object sender, T eventArgs) where T : EventArgs
        {
            Delegate[] handlers = commonHandler.GetInvocationList();
            List<Exception> exceptions = null;
            foreach (Delegate handler in handlers)
            {
                try
                {
                    handler.DynamicInvoke(sender, eventArgs);
                }
                catch (Exception exception)
                {
                    exceptions = exceptions ?? new List<Exception>();
                    exceptions.Add(exception);
                }
            }
            if (exceptions != null)
            {
                AggregateException exception = new AggregateException(exceptions);
                //throw exception;
                LoggingProvider.Current.Log(TraceEventType.Information, exception);
            }
        }

19 View Source File : Control.cs
License : zlib License
Project Creator : 0x0ade

public IAsyncResult BeginInvoke(Delegate method, params object[] args) {
            return new SyncResult(method.DynamicInvoke(args));
        }

19 View Source File : BSEvents.cs
License : MIT License
Project Creator : andruzzzhka

public void InvokeAll<T1, T2, T3>(Action<T1, T2, T3> action, params object[] args)
        {
            if (action == null) return;
            foreach (Delegate invoc in action.GetInvocationList())
            {
                try
                {
                    invoc?.DynamicInvoke(args);
                }
                catch (Exception e)
                {
                    Console.WriteLine($"Caught Exception when executing event");
                    Console.WriteLine(e);
                }
            }
        }

19 View Source File : Evaluator.cs
License : MIT License
Project Creator : albyho

public object Eval(Expression exp)
        {
            if (exp.NodeType == ExpressionType.Constant)
            {
                return ((ConstantExpression)exp).Value;
            }

            LambdaExpression lambda = Expression.Lambda(exp);
            Delegate fn = lambda.Compile();

            return fn.DynamicInvoke(null);
        }

19 View Source File : BSEvents.cs
License : MIT License
Project Creator : andruzzzhka

public void InvokeAll<T>(Action<T> action, params object[] args)
        {
            if (action == null) return;
            foreach (Delegate invoc in action.GetInvocationList())
            {
                try
                {
                    invoc?.DynamicInvoke(args);
                }
                catch (Exception e)
                {
                    Console.WriteLine($"Caught Exception when executing event");
                    Console.WriteLine(e);
                }
            }
        }

19 View Source File : Form.cs
License : zlib License
Project Creator : 0x0ade

protected override void WndProc(ref Message msg)
            => msg.Result = (IntPtr) WindowHook?.DynamicInvoke(msg.HWnd, msg.Msg, msg.WParam, msg.LParam);

19 View Source File : ExpressionHelpers.cs
License : MIT License
Project Creator : angelsix

public static void SetPropertyValue<T>(this Expression<Func<T>> lambda, T value)
        {
            // Converts a lambda () => some.Property, to some.Property
            var expression = (lambda as LambdaExpression).Body as MemberExpression;

            // Get the property information so we can set it
            var propertyInfo = (PropertyInfo)expression.Member;
            var target = Expression.Lambda(expression.Expression).Compile().DynamicInvoke();

            // Set the property value
            propertyInfo.SetValue(target, value);
        }

19 View Source File : LinqToSql.cs
License : MIT License
Project Creator : AlenToma

protected override Expression VisitMethodCall(MethodCallExpression m)
        {
            if (m.Method.DeclaringType == typeof(Queryable) || (m.Method.Name == "Any"))
            {
                var invert = GetInvert();
                var typecast = m.Arguments.First().Type.GenericTypeArguments.First();
                var cl = new LinqToSql(typecast, _transaction);
                cl._generatedKeys = _generatedKeys;
                cl.DataBaseTypes = DataBaseTypes;
                cl.Translate(m.Arguments.Last() as Expression);
                cl._overridedNodeType = ExpressionType.MemberAccess;
                cl.Visit(m.Arguments[0]);
                if (!string.IsNullOrEmpty(invert))
                    sb.Append(invert);
                sb.Append(cl.QuaryExist);
                cl._overridedNodeType = null;
                _generatedKeys = cl._generatedKeys;
                return m;
            }
            else if (m.Method.Name == "IsNullOrEmpty")
            {

                var invert = sb.ToString().EndsWith("NOT ");
                GetInvert();
                sb.Append("((CASE WHEN ");
                this.Visit(m.Arguments[0]);
                CleanDecoder("");
                sb.Append(" IS NULL THEN " + boolString.Replace("#", "1T") + " ELSE CASE WHEN ");
                this.Visit(m.Arguments[0]);
                CleanDecoder("");
                sb.Append(" = String[] THEN " + boolString.Replace("#", "1T") + " ELSE " + boolString.Replace("#", "0T") + " END END)");
                sb.Append(")");
                sb.Append(boolString.Replace("#", invert ? "0" : "1"));
                return m;
            }
            else if (m.Method.Name == "Contains")
            {
                var ex = (((MemberExpression)m.Object).Expression as ConstantExpression);

                if (ex == null && ((MemberExpression)m.Object).Expression != null)
                {
                    var invert = GetInvert();
                    var value = GetSingleValue(m.Arguments[0]);
                    sb.Append("(CASE WHEN ");
                    this.Visit(m.Object);
                    InsertBeforeDecoder(" LIKE ");
                    CleanDecoder(string.Format("String[%{0}%]", value));
                    sb.Append(" THEN " + boolString.Replace("#", "1T") + " ELSE " + boolString.Replace("#", "0T") + " END) ");
                    sb.Append(boolString.Replace("#", !string.IsNullOrEmpty(invert) ? "0" : "1"));
                }
                else
                {
                    var invert = GetInvert();
                    sb.Append("(CASE WHEN ");
                    this.Visit(m.Arguments[0]);
                    InsertBeforeDecoder(" in (");
                    try
                    {
                        var Stringify = (m.Arguments[0] as MemberExpression).Member as PropertyInfo != null ? ((m.Arguments[0] as MemberExpression).Member as PropertyInfo).GetCustomAttributes<Stringify>() != null : false;
                        var value = GetSingleValue((MemberExpression)m.Object);
                        if (value == null)
                            this.Visit(ex);
                        else
                        {
                            var v = ValuetoSql(value, Stringify);
                            if (string.IsNullOrEmpty(v))
                            {
                                if (Stringify)
                                    v = ValuetoSql(string.Format("DefaultValueForEmptyArray({0})", Guid.NewGuid().ToString()), Stringify);
                                else
                                    v = ValuetoSql(-1, Stringify);
                            }

                            CleanDecoder(v);
                        }
                    }
                    catch
                    {
                        this.Visit(ex);
                    }
                    sb.Append(") THEN " + boolString.Replace("#", "1T") + " ELSE " + boolString.Replace("#", "0T") + " END) ");
                    sb.Append(boolString.Replace("#", !string.IsNullOrEmpty(invert) ? "0" : "1"));
                }
                return m;
            }
            else if (m.Method.Name == "StartsWith")
            {
                var ex = (((MemberExpression)m.Object).Expression as ConstantExpression);
                if (ex == null && ((MemberExpression)m.Object).Expression != null)
                {
                    var invert = GetInvert();
                    var value = GetSingleValue(m.Arguments[0]);
                    sb.Append("(CASE WHEN ");
                    this.Visit(m.Object);
                    InsertBeforeDecoder(" LIKE ");
                    CleanDecoder(string.Format("String[{0}%]", value));
                    sb.Append(" THEN " + boolString.Replace("#", "1T") + " ELSE " + boolString.Replace("#", "0T") + " END) ");
                    sb.Append(boolString.Replace("#", !string.IsNullOrEmpty(invert) ? "0" : "1"));

                }
                else
                {

                    var invert = GetInvert();
                    sb.Append("(CASE WHEN ");
                    this.Visit(m.Arguments[0]);
                    InsertBeforeDecoder(" LIKE ");
                    var value = GetSingleValue((MemberExpression)m.Object);
                    CleanDecoder(string.Format("String[{0}%]", value));
                    sb.Append(" THEN " + boolString.Replace("#", "1T") + " ELSE " + boolString.Replace("#", "0T") + " END) ");
                    sb.Append(boolString.Replace("#", !string.IsNullOrEmpty(invert) ? "0" : "1"));

                }
                return m;
            }
            else
            if (m.Method.Name == "EndsWith")
            {
                var ex = (((MemberExpression)m.Object).Expression as ConstantExpression);
                if (ex == null && ((MemberExpression)m.Object).Expression != null)
                {
                    var invert = GetInvert();
                    var value = GetSingleValue(m.Arguments[0]);
                    sb.Append("(CASE WHEN ");
                    this.Visit(m.Object);
                    InsertBeforeDecoder(" LIKE ");
                    CleanDecoder(string.Format("String[%{0}]", value));
                    sb.Append(" THEN " + boolString.Replace("#", "1T") + " ELSE " + boolString.Replace("#", "0T") + " END) ");
                    sb.Append(boolString.Replace("#", !string.IsNullOrEmpty(invert) ? "0" : "1"));

                }
                else
                {

                    var invert = GetInvert();
                    sb.Append("(CASE WHEN ");
                    this.Visit(m.Arguments[0]);
                    InsertBeforeDecoder(" LIKE ");
                    var value = GetSingleValue((MemberExpression)m.Object);
                    CleanDecoder(string.Format("String[%{0}]", value));
                    sb.Append(" THEN " + boolString.Replace("#", "1T") + " ELSE " + boolString.Replace("#", "0T") + " END) ");
                    sb.Append(boolString.Replace("#", !string.IsNullOrEmpty(invert) ? "0" : "1"));

                }
                return m;
            }
            else if (m.Method.Name == "Take")
            {
                if (this.ParseTakeExpression(m))
                {
                    return null;
                }
            }
            else if (m.Method.Name == "Skip")
            {
                if (this.ParseSkipExpression(m))
                {
                    return null;
                }
            }
            else if (m.Method.Name == "OrderBy")
            {
                if (this.ParseOrderByExpression(m, "ASC"))
                {
                    return null;
                }
            }
            else if (m.Method.Name == "OrderByDescending")
            {
                if (this.ParseOrderByExpression(m, "DESC"))
                {
                    return null;
                }
            }
            else if (m.Method.ReturnType.IsInternalType())
            {
                CleanDecoder(ValuetoSql(Expression.Lambda(m).Compile().DynamicInvoke()));
                return m;
            }
            else if ((m.Arguments?.Any() ?? false))
            {
                var expression = m.Arguments.First();
                if ((expression?.ToString().Contains("DisplayClreplaced") ?? false))
                {
                    CleanDecoder(ValuetoSql(Expression.Lambda(m).Compile().DynamicInvoke()));
                    return m;
                }
                else
                    throw new EnreplacedyException(string.Format("The method '{0}' is not supported", m.Method.Name));
            }

            throw new EnreplacedyException(string.Format("The method '{0}' is not supported", m.Method.Name));
        }

19 View Source File : CacheAOPbase.cs
License : Apache License 2.0
Project Creator : anjoy8

private static string Like(MethodCallExpression expression)
        {

            var Temp = expression.Arguments[0];
            LambdaExpression lambda = Expression.Lambda(Temp);
            Delegate fn = lambda.Compile();
            var tempValue = Expression.Constant(fn.DynamicInvoke(null), Temp.Type);
            string Value = $"%{tempValue}%";
            string Name = (expression.Object as MemberExpression).Member.Name;
            string Result = $"{Name} like {Value}";
            return Result;
        }

19 View Source File : ExpressionResovle.cs
License : Apache License 2.0
Project Creator : 1448376744

public object VisitConstantValue(Expression expression)
        {
            var names = new Stack<string>();
            var exps = new Stack<Expression>();
            var mifs = new Stack<MemberInfo>();
            if (expression is ConstantExpression constant)
                return constant.Value;
            else if (expression is MemberExpression)
            {
                var temp = expression;
                object value = null;
                while (temp is MemberExpression memberExpression)
                {
                    names.Push(memberExpression.Member.Name);
                    exps.Push(memberExpression.Expression);
                    mifs.Push(memberExpression.Member);
                    temp = memberExpression.Expression;
                }
                foreach (var name in names)
                {
                    var exp = exps.Pop();
                    var mif = mifs.Pop();
                    if (exp is ConstantExpression cex)
                        value = cex.Value;
                    if (mif is PropertyInfo pif)
                        value = pif.GetValue(value);
                    else if (mif is FieldInfo fif)
                        value = fif.GetValue(value);
                }
                return value;
            }
            else
            {
                return Expression.Lambda(expression).Compile().DynamicInvoke();
            }
        }

19 View Source File : AppBuilder.cs
License : Apache License 2.0
Project Creator : aspnet

private object ConvertMultiHop(Type signature, object app)
        {
            foreach (var conversion in _conversions)
            {
                object preConversion = ConvertOneHop(conversion.Key.Item2, app);
                if (preConversion == null)
                {
                    continue;
                }
                object intermediate = conversion.Value.DynamicInvoke(preConversion);
                if (intermediate == null)
                {
                    continue;
                }
                object postConversion = ConvertOneHop(signature, intermediate);
                if (postConversion == null)
                {
                    continue;
                }

                return postConversion;
            }
            return null;
        }

19 View Source File : KrakenSocket.cs
License : Apache License 2.0
Project Creator : AlexWan

private void InvokeAllHandlers(Delegate[] handlers, EventArgs eventArgs)
        {
            if (handlers != null)
            {
                foreach (var handler in handlers)
                {
                    handler.DynamicInvoke(this, eventArgs);
                }
            }
        }

19 View Source File : AppBuilder.cs
License : Apache License 2.0
Project Creator : aspnet

private object BuildInternal(Type signature)
        {
            object app;
            if (!_properties.TryGetValue(Constants.BuilderDefaultApp, out app))
            {
                app = NotFound;
            }

            foreach (var middleware in _middleware.Reverse())
            {
                Type neededSignature = middleware.Item1;
                Delegate middlewareDelegate = middleware.Item2;
                object[] middlewareArgs = middleware.Item3;

                app = Convert(neededSignature, app);
                object[] invokeParameters = new[] { app }.Concat(middlewareArgs).ToArray();
                app = middlewareDelegate.DynamicInvoke(invokeParameters);
                app = Convert(neededSignature, app);
            }

            return Convert(signature, app);
        }

19 View Source File : PInvokeHooks.cs
License : zlib License
Project Creator : 0x0ade

public static IntPtr ContinueHookChain(int nCode, IntPtr wParam, IntPtr lParam) {
            List<Delegate> hooks = CurrentHookChain.Value;
            for (int i = CurrentHookIndex.Value + 1; i < hooks.Count; i++) {
                Delegate hook = hooks[i];
                // Find the next non-null (still registered) hook.
                if (hook == null)
                    continue;
                CurrentHookIndex.Value = i;
                return (IntPtr) hook.DynamicInvoke(nCode < 0 ? nCode + 1 : 0, wParam, lParam);
            }
            // End of chain. What should we return here?
            return IntPtr.Zero;
        }

19 View Source File : ExpressionExtensions.cs
License : MIT License
Project Creator : AutoReviser

public static object Evaluate(this Expression expression)
            => Lambda(expression).Compile().DynamicInvoke();

19 View Source File : EventHandlerExtensions.cs
License : Apache License 2.0
Project Creator : AlexWan

public static void InvokeAll<TData>(this EventHandler<KrakenDataEventArgs<TData>> eventHandler, object sender, KrakenDataEventArgs<TData> eventArgs)
        {
            var invocationList = eventHandler?.GetInvocationList();
            if (invocationList == null) return;
            foreach (var handler in invocationList)
            {
                handler.DynamicInvoke(sender, eventArgs);
            }
        }

19 View Source File : X86Assembly.cs
License : MIT License
Project Creator : 20chan

public static object RunMachineCode(byte[] codes, Type delegateType, params dynamic[] parameters)
        {
            var func = CompileMachineCode(codes, out var buf, delegateType);
            var res = func.DynamicInvoke(parameters);
            WinAPI.VirtualFree(buf, codes.Length, WinAPI.FreeType.Release);
            return res;
        }

19 View Source File : PInvokeHooks.cs
License : zlib License
Project Creator : 0x0ade

public static IntPtr CallHookChain(HookType hookType, IntPtr wParam, IntPtr lParam, ref Message lParamMsg) {
            List<Delegate> hooks = Hooks[hookType];
            if (hooks.Count == 0)
                return IntPtr.Zero;
            CurrentHookChain.Value = hooks;
            for (int i = 0; i < hooks.Count; i++) {
                Delegate hook = hooks[i];
                // Find the first non-null (still registered) hook.
                if (hook == null)
                    continue;
                CurrentHookIndex.Value = i;
                // HookProc expects HC_ACTION (0; take action) or < 0 (preplaced to next hook).
                object[] args = { 0, wParam, lParamMsg };
                object result = hook.DynamicInvoke(args);
                lParamMsg = (Message) args[2];
                return result != null ? (IntPtr) Convert.ToInt32(result) : IntPtr.Zero;
            }
            return IntPtr.Zero;
        }

19 View Source File : PInvokeHooks.cs
License : zlib License
Project Creator : 0x0ade

public static IntPtr CallWindowProc(IntPtr lpPrevWndFunc, IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam) {
            if (lpPrevWndFunc == IntPtr.Zero)
                return IntPtr.Zero;
            return (IntPtr) Marshal.GetDelegateForFunctionPointer(lpPrevWndFunc, typeof(MulticastDelegate))
                .DynamicInvoke(hWnd, Msg, wParam, lParam);
        }

19 View Source File : Control.cs
License : zlib License
Project Creator : 0x0ade

public IAsyncResult BeginInvoke(Delegate method) {
            return new SyncResult(method.DynamicInvoke());
        }

19 View Source File : DynamicDNAConverterBehaviourEditor.cs
License : Apache License 2.0
Project Creator : A7ocin

private void RecursiveScanFoldersForreplacedets(string path, Delegate callback, int addMethod)
		{
			var replacedetFiles = System.IO.Directory.GetFiles(path, "*.prefab");
			foreach (var replacedetFile in replacedetFiles)
			{
				var tempDnaGO = replacedetDatabase.LoadreplacedetAtPath(replacedetFile, typeof(GameObject)) as GameObject;
				DynamicDNAConverterBehaviour tempDnareplacedet = tempDnaGO.GetComponent<DynamicDNAConverterBehaviour>();
				if (tempDnareplacedet)
				{
					callback.DynamicInvoke(tempDnareplacedet, addMethod);
				}
			}
			foreach (var subFolder in System.IO.Directory.GetDirectories(path))
			{
				RecursiveScanFoldersForreplacedets(subFolder.Replace('\\', '/'), callback,  addMethod);
			}
		}

19 View Source File : KeyedPropertyInfo.cs
License : MIT License
Project Creator : AlFasGD

public virtual object Get(object instance) => GetMethodDelegate?.DynamicInvoke(instance);

See More Examples