Пример #1
0
        /// <summary>
        /// This adds the delegate value as a listener to when this event is fired
        /// by the component, invoking the addOnXXX method.
        /// </summary>
        public override void AddEventHandler(object component, Delegate value)
        {
            FillMethods();

            if (component != null)
            {
                ISite?site = GetSite(component);
                IComponentChangeService?changeService = null;

                // Announce that we are about to change this component
                if (site != null)
                {
                    changeService = (IComponentChangeService?)site.GetService(typeof(IComponentChangeService));
                }

                if (changeService != null)
                {
                    try
                    {
                        changeService.OnComponentChanging(component, this);
                    }
                    catch (CheckoutException coEx)
                    {
                        if (coEx == CheckoutException.Canceled)
                        {
                            return;
                        }
                        throw;
                    }
                    changeService.OnComponentChanging(component, this);
                }

                bool shadowed = false;

                if (site != null && site.DesignMode)
                {
                    // Events are final, so just check the class
                    if (EventType != value.GetType())
                    {
                        throw new ArgumentException(SR.Format(SR.ErrorInvalidEventHandler, Name));
                    }
                    IDictionaryService?dict = (IDictionaryService?)site.GetService(typeof(IDictionaryService));
                    if (dict != null)
                    {
                        Delegate?eventdesc = (Delegate?)dict.GetValue(this);
                        eventdesc = Delegate.Combine(eventdesc, value);
                        dict.SetValue(this, eventdesc);
                        shadowed = true;
                    }
                }

                if (!shadowed)
                {
                    _addMethod !.Invoke(component, new[] { value });
                }

                // Now notify the change service that the change was successful.
                changeService?.OnComponentChanged(component, this, null, value);
            }
        }
Пример #2
0
 public ModelBindingCommandHandler(
     Delegate handlerDelegate,
     IReadOnlyList <ParameterDescriptor> parameterDescriptors)
 {
     _handlerDelegate      = handlerDelegate ?? throw new ArgumentNullException(nameof(handlerDelegate));
     _parameterDescriptors = parameterDescriptors ?? throw new ArgumentNullException(nameof(parameterDescriptors));
 }
 public ModelBindingCommandHandler(
     Delegate handlerDelegate,
     IMethodDescriptor methodDescriptor)
 {
     _handlerDelegate  = handlerDelegate ?? throw new ArgumentNullException(nameof(handlerDelegate));
     _methodDescriptor = methodDescriptor ?? throw new ArgumentNullException(nameof(methodDescriptor));
 }
Пример #4
0
        private object SetRepeatingTypeParent(TagMapLeaf leaf, TagMapParent parent, FixMessageContext fixMessageContext, object targetObject)
        {
            int index = GetAdvancedIndex(GetKey(leaf.Current), parent, fixMessageContext, out bool isAdvanced);

            if (isAdvanced)
            {
                object?childObject = Activator.CreateInstance(parent.InnerType);
                if (childObject is null)
                {
                    throw new InvalidOperationException();
                }
                Type typeOfParent = parent.InnerType;
                if (_delegateFactoryCache == null)
                {
                    var methodInfo        = typeof(BaseSetter).GetMethod("GetEnumeratedILSetterAction", BindingFlags.NonPublic | BindingFlags.Instance);
                    var generatedDelegate = (Delegate?)methodInfo?.MakeGenericMethod(typeOfParent).Invoke(this, new[] { parent.Current });
                    _delegateFactoryCache = generatedDelegate ?? throw new InvalidOperationException();
                }
                _delegateFactoryCache.DynamicInvoke(targetObject, childObject, index);
                return(childObject);
            }

            targetObject = (parent.Current.GetValue(targetObject) as IEnumerable <object>).ElementAt(index);
            return(targetObject);
        }
        protected override Expression VisitLambda <T>(Expression <T> node)
        {
            string methodName;

            Type type = node.Type;

            if (type.IsFunc())
            {
                methodName = "Func";
            }
            else if (type.IsAction())
            {
                methodName = "Action";
            }
            else if (type.IsPredicate())
            {
                methodName = "Predicate";
            }
            else
            {
                throw new ExpressionExecutionException(string.Format("No wrapper method available for delegate type '{0}'", type.Name));
            }

            var executor = new ExpressionReflectionExecutor(node);

            Type[]     genericArguments = type.GenericTypeArguments;
            MethodInfo?methodInfo       = this.FindMethod(methodName, genericArguments);
            Delegate?  @delegate        = methodInfo?.CreateDelegate(type, executor);

            return(this.VisitConstant(Expression.Constant(@delegate)));
        }
Пример #6
0
        static partial void TryCompileInDynamicAssembly(Type resultType, Expression expression,
                                                        ref Delegate?compiledLambda)
        {
            // HACK: Prevent "JIT Compiler encountered an internal limitation" exception while running in
            // the debugger with VS2013 (See work item 20904).
            if (Debugger.IsAttached)
            {
                return;
            }

            if (Interlocked.Read(ref dynamicClassCounter) >= DynamicAssemblyCompilationThreshold)
            {
                // Stop doing dynamic assembly compilation.
                return;
            }

            compiledLambda = null;

            if (!ExpressionNeedsAccessToInternals(expression))
            {
                try
                {
                    var @delegate = CompileInDynamicAssembly(resultType, expression);

                    // Test the creation. Since we're using a dynamically created assembly, we can't create
                    // every delegate we can create using expression.Compile(), so we need to test this.
                    JitCompileDelegate(@delegate);

                    compiledLambda = @delegate;
                }
                catch
                {
                }
            }
        }
Пример #7
0
        internal void OnQueueCompleted()
        {
            if (this.IsCompleted)
            {
                // Note this code may execute more than once, as multiple queue completion
                // notifications come in.
                this.JoinableTaskContext.OnJoinableTaskCompleted(this);

                foreach (var collection in this.dependencyParents)
                {
                    JoinableTaskDependencyGraph.RemoveDependency(collection, this);
                }

                if (this.mainThreadJobSyncContext != null)
                {
                    this.mainThreadJobSyncContext.OnCompleted();
                }

                if (this.threadPoolJobSyncContext != null)
                {
                    this.threadPoolJobSyncContext.OnCompleted();
                }

                this.nestingFactories = default(ListOfOftenOne <JoinableTaskFactory>);
                this.initialDelegate  = null;
                this.state           |= JoinableTaskFlags.CompleteFinalized;
            }
        }
Пример #8
0
        [MethodImpl(MethodImplOptions.AggressiveInlining)] // otherwise an unnecessary long-lived stack frame in many threads
        private void StartCallbackWorker()
        {
            if (culture != null)
            {
                CultureInfo.CurrentCulture = culture;
                culture = null;
            }

            if (ui_culture != null)
            {
                CultureInfo.CurrentUICulture = ui_culture;
                ui_culture = null;
            }

            if (m_start is ThreadStart del)
            {
                m_start = null;
                del();
            }
            else
            {
                Debug.Assert(m_start is ParameterizedThreadStart);
                var    pdel = (ParameterizedThreadStart)m_start !;
                object?arg  = m_start_arg;
                m_start     = null;
                m_start_arg = null;
                pdel(arg);
            }
        }
        /// <summary>
        /// Invokes any event handlers that are hooked to the specified event.
        /// </summary>
        /// <param name="handler">The event.  Null is allowed.</param>
        /// <param name="sender">The value to pass as the sender of the event.</param>
        /// <param name="e">Event arguments to include.</param>
        public static void Raise(this Delegate?handler, object sender, EventArgs e)
        {
            Requires.NotNull(sender, nameof(sender));
            Requires.NotNull(e, nameof(e));

            handler?.DynamicInvoke(sender, e);
        }
Пример #10
0
 public LiteralCommandNode(string literal, IReadOnlyCollection <ICommandNode> children, Delegate?run = null, ICommandNode?redirect = null)
 {
     _literal = literal;
     Children = children;
     Run      = run;
     Redirect = redirect;
 }
Пример #11
0
        /// <summary>
        /// Adds a field with the specified properties to this graph type.
        /// </summary>
        /// <typeparam name="TGraphType">The .NET type of the graph type of this field.</typeparam>
        /// <param name="name">The name of the field.</param>
        /// <param name="description">The description of the field.</param>
        /// <param name="arguments">A list of arguments for the field.</param>
        /// <param name="resolve">A field resolver delegate. Only applicable to fields of output graph types. If not specified, <see cref="NameFieldResolver"/> will be used.</param>
        /// <param name="deprecationReason">The deprecation reason for the field. Applicable only for output graph types.</param>
        /// <returns>The newly added <see cref="FieldType"/> instance.</returns>
        public FieldType FieldDelegate <TGraphType>(
            string name,
            string?description       = null,
            QueryArguments?arguments = null,
            Delegate?resolve         = null,
            string?deprecationReason = null)
            where TGraphType : IGraphType
        {
            IFieldResolver?resolver = null;

            if (resolve != null)
            {
                // create an instance expression that points to the instance represented by the delegate
                // for instance, if the delegate represents obj.MyMethod,
                // then the lambda would be: _ => obj
                var param  = Expression.Parameter(typeof(IResolveFieldContext), "context");
                var body   = Expression.Constant(resolve.Target, resolve.Method.DeclaringType !);
                var lambda = Expression.Lambda(body, param);
                resolver = AutoRegisteringHelper.BuildFieldResolver(resolve.Method, null, null, lambda);
            }

            return(AddField(new FieldType
            {
                Name = name,
                Description = description,
                DeprecationReason = deprecationReason,
                Type = typeof(TGraphType),
                Arguments = arguments,
                Resolver = resolver,
            }));
        }
Пример #12
0
 public bool Equals(Delegate?leftDelegate, Delegate?rightDelegate)
 {
     return(ReferenceEquals(leftDelegate, rightDelegate) ||
            (leftDelegate is not null &&
             rightDelegate is not null &&
             ReferenceEquals(leftDelegate.Target, rightDelegate.Target)));
 }
Пример #13
0
        public bool Equals(Delegate? @delegate)
        {
            var invokeMethod = @delegate?.Method;

            if (invokeMethod is null)
            {
                return(false);
            }
            if (invokeMethod.ReturnType != this.ReturnType)
            {
                return(false);
            }
            var methodParamTypes = invokeMethod.GetParameterTypes();

            if (methodParamTypes.Length != this.ParameterTypes.Length)
            {
                return(false);
            }
            for (var i = 0; i < this.ParameterTypes.Length; i++)
            {
                if (methodParamTypes[i] != this.ParameterTypes[i])
                {
                    return(false);
                }
            }
            return(true);
        }
Пример #14
0
 /// <summary>
 /// Initializes a new instance of the <see cref="EventHandlerItem{TElement}"/> class
 /// with the specified element name, element, event name, event handler, and
 /// a value that indicates whether to register the handler such that
 /// it is invoked even when the event is marked handled in its event data.
 /// </summary>
 /// <param name="elementName">The name of the element that raises the event.</param>
 /// <param name="element">The element that raises the event.</param>
 /// <param name="eventName">The name of the event.</param>
 /// <param name="handler">The handler of the event.</param>
 /// <param name="handledEventsToo">
 /// <c>true</c> to register the handler such that it is invoked even when the
 /// event is marked handled in its event data; <c>false</c> to register the
 /// handler with the default condition that it will not be invoked if the event
 /// is already marked handled.
 /// </param>
 protected EventHandlerItem(string elementName, TElement?element, string eventName, Delegate?handler, bool handledEventsToo)
 {
     this.elementName      = elementName;
     this.element          = element;
     this.eventName        = eventName;
     this.handler          = handler;
     this.handledEventsToo = handledEventsToo;
 }
Пример #15
0
 private static Delegate GetSetDuration_JHandler()
 {
     if (cb_setDuration_J == null)
     {
         cb_setDuration_J = JNINativeWrapper.CreateDelegate(new Func <IntPtr, IntPtr, long, IntPtr> (n_SetDuration_J));
     }
     return(cb_setDuration_J);
 }
        private Delegate CompilePropertyInjectorLambda(LambdaExpression expression)
        {
            Delegate?compiledDelegate = null;

            this.TryCompileLambdaInDynamicAssembly(expression, ref compiledDelegate);

            return(compiledDelegate ?? expression.Compile());
        }
Пример #17
0
        private static Delegate GetDelegateForFunctionPointerInternal(IntPtr ptr, Type t)
        {
            RuntimeType rttype = (RuntimeType)t;
            Delegate?   res    = null;

            GetDelegateForFunctionPointerInternal(new QCallTypeHandle(ref rttype), ptr, ObjectHandleOnStack.Create(ref res));
            return(res !);
        }
Пример #18
0
 /// <summary>
 /// Removes a <c>INotifyCollectionChanged.CollectionChanged</c> event handler from the specified value. Does nothing if <typeparamref name="T"/> does not implement <c>INotifyCollectionChanged</c> or if <paramref name="value"/> is <c>null</c>.
 /// </summary>
 /// <param name="value">The value being observed. May be <c>null</c>.</param>
 /// <param name="handler">The delegate to be unsubscribed.</param>
 public static void RemoveEventHandler(T value, Delegate?handler)
 {
     if (!ImplementsINotifyCollectionChanged || value == null)
     {
         return;
     }
     _collectionChangedEvent !.RemoveEventHandler(value, handler);
 }
#pragma warning disable 0169
        static Delegate GetOnServiceAdded_ILandroid_bluetooth_BluetoothGattService_Handler_ext()
        {
            if (cb_onServiceAdded_ILandroid_bluetooth_BluetoothGattService_ext == null)
            {
                cb_onServiceAdded_ILandroid_bluetooth_BluetoothGattService_ext = JNINativeWrapper.CreateDelegate((Action <IntPtr, IntPtr, int, IntPtr>)n_OnServiceAdded_ILandroid_bluetooth_BluetoothGattService_ext);
            }
            return(cb_onServiceAdded_ILandroid_bluetooth_BluetoothGattService_ext);
        }
Пример #20
0
        public static Delegate?Combine(Delegate?a, Delegate?b)    // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761
        {
            if (a is null)
            {
                return(b);
            }

            return(a.CombineImpl(b));
        }
Пример #21
0
        public static Delegate?Combine(Delegate?a, Delegate?b)
        {
            if (a is null)
            {
                return(b);
            }

            return(a.CombineImpl(b));
        }
Пример #22
0
        public void RemoveHandler(object key, Delegate?value)
        {
            ListEntry?e = Find(key);

            if (e != null)
            {
                e._handler = Delegate.Remove(e._handler, value);
            }
        }
Пример #23
0
 public ArgumentCommandNode(TParser parser, string name, IReadOnlyCollection <ICommandNode> children, TParserProperties?parserProperties = null, Delegate?run = null, ICommandNode?redirect = null)
 {
     _parser           = parser;
     _parserProperties = parserProperties ?? _parser.DefaultProperties;
     Name     = name;
     Children = children;
     Run      = run;
     Redirect = redirect;
 }
Пример #24
0
 private object?GetPropertyValue()
 {
     EnsureDispose();
     if (Source == null)
     {
         return(null);
     }
     return((_getAccessor ?? (_getAccessor = AccessorCache.LookupGet(Source.GetType(), PropertyName)))
            .DynamicInvoke(Source));
 }
Пример #25
0
        public void RemoveEventListener(string name, Delegate?listener, EventListenerOptions?options = null)
        {
            if (listener == null)
            {
                return;
            }
            var jsfunc = Runtime.GetJSOwnedObjectHandle(listener);

            RemoveEventListener(name, jsfunc, options);
        }
Пример #26
0
        partial void TryCompileLambdaInDynamicAssembly(LambdaExpression expression, ref Delegate?compiledDelegate)
        {
            compiledDelegate = null;

            if (this.container.Options.EnableDynamicAssemblyCompilation &&
                !CompilationHelpers.ExpressionNeedsAccessToInternals(expression))
            {
                compiledDelegate = CompileLambdaInDynamicAssemblyWithFallback(expression);
            }
        }
Пример #27
0
    public TypeConditionPair(LambdaExpression condition, Delegate?inMemoryCondition)
    {
        if (condition == null)
        {
            throw new ArgumentNullException("lambda");
        }

        this.Condition         = condition;
        this.InMemoryCondition = inMemoryCondition;
    }
Пример #28
0
        public override object Set(ReadOnlySpan <char> valueChars, TagMapLeaf mappingDetails, FixMessageContext fixMessageContext, object targetObject)
        {
            if (mappingDetails.TypeConverterName is null)
            {
                return(targetObject);
            }
            if (_typeConverter is null)
            {
                Type?typeOfConverter = Type.GetType(mappingDetails.TypeConverterName);
                if (typeOfConverter == null)
                {
                    throw new ArgumentException("Invalid TypeConverterName");
                }
                _typeConverter = (TypeConverter?)Activator.CreateInstance(typeOfConverter);
                if (_typeConverter == null)
                {
                    throw new ArgumentException("Invalid TypeConverterConstructor for");
                }
            }
            if (!_typeConverter.CanConvertFrom(typeof(char[])))
            {
                return(targetObject);
            }
            var tempCharsArray = ArrayPool <char> .Shared.Rent(valueChars.Length);

            try
            {
                valueChars.CopyTo(tempCharsArray.AsSpan());
                object converted     = _typeConverter.ConvertFrom(tempCharsArray);
                var    convertedType = converted.GetType();
                if (_delegateFactory == null)
                {
                    string methodGeneratingMethodName = mappingDetails.IsEnumerable ? "GetEnumeratedILSetterAction" : "GetILSetterAction";

                    var methodInfo        = typeof(BaseSetter).GetMethod(methodGeneratingMethodName, BindingFlags.NonPublic | BindingFlags.Instance);
                    var generatedDelegate = (Delegate?)methodInfo?.MakeGenericMethod(convertedType).Invoke(this, new[] { mappingDetails.Current });
                    _delegateFactory = generatedDelegate ?? throw new ArgumentNullException();
                }
                if (mappingDetails.IsEnumerable)
                {
                    int index = GetAdvancedIndex(mappingDetails, fixMessageContext);
                    _delegateFactory.DynamicInvoke(targetObject, converted, index);
                }
                else
                {
                    _delegateFactory.DynamicInvoke(targetObject, converted);
                }
            }
            finally
            {
                ArrayPool <char> .Shared.Return(tempCharsArray, true);
            }

            return(targetObject);
        }
Пример #29
0
        /// <summary>
        /// This will remove the delegate value from the event chain so that
        /// it no longer gets events from this component.
        /// </summary>
        public override void RemoveEventHandler(object component, Delegate value)
        {
            FillMethods();

            if (component != null)
            {
                ISite?site = GetSite(component);
                IComponentChangeService?changeService = null;

                // Announce that we are about to change this component
                if (site != null)
                {
                    changeService = (IComponentChangeService?)site.GetService(typeof(IComponentChangeService));
                }

                if (changeService != null)
                {
                    try
                    {
                        changeService.OnComponentChanging(component, this);
                    }
                    catch (CheckoutException coEx)
                    {
                        if (coEx == CheckoutException.Canceled)
                        {
                            return;
                        }
                        throw;
                    }
                    changeService.OnComponentChanging(component, this);
                }

                bool shadowed = false;

                if (site != null && site.DesignMode)
                {
                    IDictionaryService?dict = (IDictionaryService?)site.GetService(typeof(IDictionaryService));
                    if (dict != null)
                    {
                        Delegate?del = (Delegate?)dict.GetValue(this);
                        del = Delegate.Remove(del, value);
                        dict.SetValue(this, del);
                        shadowed = true;
                    }
                }

                if (!shadowed)
                {
                    _removeMethod !.Invoke(component, new[] { value });
                }

                // Now notify the change service that the change was successful.
                changeService?.OnComponentChanged(component, this, null, value);
            }
        }
Пример #30
0
 public static IServiceCollection TryAddMutationEndpoint <TGraphType>(
     this IServiceCollection services,
     string name,
     string?description       = null,
     QueryArguments?arguments = null,
     Delegate?resolve         = null)
     where TGraphType : IGraphType
 {
     resolve ??= new Func <object?>(() => null);
     return(services.TryAddMutationEndpoint(new MutationEndpoint(name, description, typeof(TGraphType), resolve, arguments)));
 }