/// <summary>
 ///
 /// </summary>
 /// <param name="binding"></param>
 /// <param name="instance"></param>
 public void Remember(IBinding binding, object instance)
 {
     lock (cache)
     {
         cache[binding] = instance;
     }
 }
		/*----------------------------------------------------------------------------------------*/
		/// <summary>
		/// Executed to build the activation plan.
		/// </summary>
		/// <param name="binding">The binding that points at the type whose activation plan is being released.</param>
		/// <param name="type">The type whose activation plan is being manipulated.</param>
		/// <param name="plan">The activation plan that is being manipulated.</param>
		/// <returns>
		/// A value indicating whether to proceed or interrupt the strategy chain.
		/// </returns>
		public override StrategyResult Build(IBinding binding, Type type, IActivationPlan plan)
		{
			EventInfo[] events = type.GetEvents(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

			foreach (EventInfo evt in events)
			{
#if !MONO
				PublishAttribute[] attributes = evt.GetAllAttributes<PublishAttribute>();
#else
				PublishAttribute[] attributes = ExtensionsForICustomAttributeProvider.GetAllAttributes<PublishAttribute>(evt);
#endif

				foreach (PublishAttribute attribute in attributes)
					plan.Directives.Add(new PublicationDirective(attribute.Channel, evt));
			}

			MethodInfo[] methods = type.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
			var injectorFactory = binding.Components.Get<IInjectorFactory>();

			foreach (MethodInfo method in methods)
			{
#if !MONO
				SubscribeAttribute[] attributes = method.GetAllAttributes<SubscribeAttribute>();
#else
				SubscribeAttribute[] attributes = ExtensionsForICustomAttributeProvider.GetAllAttributes<SubscribeAttribute>(method);
#endif
                foreach (SubscribeAttribute attribute in attributes)
				{
					IMethodInjector injector = injectorFactory.GetInjector(method);
					plan.Directives.Add(new SubscriptionDirective(attribute.Channel, injector, attribute.Thread));
				}
			}

			return StrategyResult.Proceed;
		}
        public void Display( IBinding binding )
        {
            if( binding == null ) return;

            if( Window == null )
            {
                Window = new CKWindow();
            }
            Binding = binding;

            Rect r = Binding.GetWindowArea();
            if( r != Rect.Empty )
            {
                Window.Dispatcher.BeginInvoke( new Action( () =>
                {
                    Window.Opacity = .8;
                    Window.Background = new System.Windows.Media.SolidColorBrush( System.Windows.Media.Color.FromRgb( 152, 120, 152 ) );
                    Window.ResizeMode = ResizeMode.NoResize;
                    Window.WindowStyle = WindowStyle.None;
                    Window.ShowInTaskbar = false;
                    Window.Show();
                    Window.Left = r.Left;
                    Window.Top = r.Top;
                    Window.Width = r.Width;
                    Window.Height = r.Height;
                    Window.Topmost = true;
                } ) );
            }
        }
Example #4
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="kernel"></param>
 /// <param name="binding"></param>
 /// <param name="metadata"></param>
 /// <param name="instance"></param>
 public void Inject(IKernel kernel, IBinding binding, TypeMetadata metadata, object instance)
 {
     for (var i = 0; i < Injectors.Count; i++)
     {
         Injectors[i].Inject(kernel, binding, metadata, instance);
     }
 }
		/*----------------------------------------------------------------------------------------*/
		#region Public Methods
		/// <summary>
		/// Creates an injection directive for the specified constructor.
		/// </summary>
		/// <param name="binding">The binding.</param>
		/// <param name="constructor">The constructor to create the directive for.</param>
		/// <returns>The created directive.</returns>
		public ConstructorInjectionDirective Create(IBinding binding, ConstructorInfo constructor)
		{
			var directive = new ConstructorInjectionDirective(constructor);
			CreateArgumentsForMethod(binding, constructor).Each(directive.Arguments.Add);

			return directive;
		}
		/*----------------------------------------------------------------------------------------*/
		/// <summary>
		/// Creates an injection directive for the specified property.
		/// </summary>
		/// <param name="binding">The binding.</param>
		/// <param name="property">The property to create the directive for.</param>
		/// <returns>The created directive.</returns>
		public PropertyInjectionDirective Create(IBinding binding, PropertyInfo property)
		{
			var directive = new PropertyInjectionDirective(property);
			directive.Argument = CreateArgument(binding, new PropertyTarget(property));

			return directive;
		}
 internal ScopeTimeoutBinding(IBinding prev, Func<object> scopeObj, int timeout) : base(prev)
 {
     cachedObjs = new ConcurrentDictionary<object, ObjGetter>(10, 10);
     this.timeout = timeout;
     Condition = this;
     scopeObjGetter = scopeObj;
 }
 private bool IsServiceAssemblyBinding(IBinding b)
 {
     var haskey = HasAssemblyKey(b);
     if (!haskey) return false;
     var satisfies = b.Metadata.Get<string>("assembly") == _serviceAssembly;
     return satisfies;
 }
		/*----------------------------------------------------------------------------------------*/
		/// <summary>
		/// Executed to build the activation plan.
		/// </summary>
		/// <param name="binding">The binding that points at the type whose activation plan is being released.</param>
		/// <param name="type">The type whose activation plan is being manipulated.</param>
		/// <param name="plan">The activation plan that is being manipulated.</param>
		/// <returns>
		/// A value indicating whether to proceed or interrupt the strategy chain.
		/// </returns>
		public override StrategyResult Build(IBinding binding, Type type, IActivationPlan plan)
		{
			if (binding.Behavior != null)
			{
				// If the binding declares a behavior, it overrides any behavior that would be read
				// via reflection.
				plan.Behavior = binding.Behavior;
			}
			else
			{
				IBehavior behavior;
				var attribute = type.GetOneAttribute<BehaviorAttribute>();

				if (attribute != null)
				{
					// If a behavior attribute was defined on the implementation type, ask it to create
					// the appropriate behavior.
					behavior = attribute.CreateBehavior();
				}
				else
				{
					// If no behavior attribute was defined, create a behavior as defined by the kernel's options.
					behavior = Activator.CreateInstance(Kernel.Options.DefaultBehaviorType) as IBehavior;
				}

				behavior.Kernel = Kernel;
				plan.Behavior = behavior;
			}

			return StrategyResult.Proceed;
		}
        /// <inheritdoc />
        public int Compare(IBinding x, IBinding y)
        {
            if (x == y)
            {
                return 0;
            }

            // Each function represents a level of precedence.
            var funcs = new List<Func<IBinding, bool>>
                            {
                                b => b != null,       // null bindings should never happen, but just in case
                                b => b.IsConditional, // conditional bindings > unconditional
                                b => !b.Service.GetTypeInfo().ContainsGenericParameters, // closed generics > open generics
                                b => !b.IsImplicit,   // explicit bindings > implicit
                            };

            var q = from func in funcs
                    let xVal = func(x)
                    where xVal != func(y)
                    select xVal ? 1 : -1;

            // returns the value of the first function that represents a difference
            // between the bindings, or else returns 0 (equal)
            return q.FirstOrDefault();
        }
 public void UpdateValueConverter(IBinding binding, string repositoryGroup, UATypeInfo sourceEncoding)
 {
     Assert.IsNotNull(binding);
     binding.Parameter = "Conversion parameter";
     binding.Converter = new IVC();
     binding.Culture = CultureInfo.InvariantCulture;
 }
        private bool IsScopeAllowed(IRequest request, IBinding binding, IBinding parentBinding)
        {
            var scope = binding.GetScope(CreateContext(request, binding));
            var parentScope = parentBinding.GetScope(CreateContext(request, parentBinding));

            var haveSameScope = scope == parentScope;
            if (haveSameScope)
                return true;

            var isChildSingletonScoped = scope == this;
            if (isChildSingletonScoped)
                return true;

            var isChildTransientScoped = scope == null;
            var isChildPerRequestScoped = scope != null && scope.GetType().Name == "HttpContext";

            var isParentSingletonScoped = parentScope == this;
            if (isParentSingletonScoped)
                return AllowTransientScopeInSingletonScope && isChildTransientScoped;

            var isParentThreadScoped = parentScope is Thread;
            if (isParentThreadScoped)
                return AllowTransientScopeInThreadScope && isChildTransientScoped;

            var isParentAController = parentBinding.Service.Name.EndsWith("Controller");
            var isParentTransientScoped = parentScope == null;
            if (isParentTransientScoped)
                return AllowPerRequestScopeInTransientScopedController && isParentAController && isChildPerRequestScoped;

            return AllowTransientScopeInCustomScope && isChildTransientScoped;
        }
		/*----------------------------------------------------------------------------------------*/
		/// <summary>
		/// Creates an injection directive for the specified method.
		/// </summary>
		/// <param name="binding">The binding.</param>
		/// <param name="method">The method to create the directive for.</param>
		/// <returns>The created directive.</returns>
		public MethodInjectionDirective Create(IBinding binding, MethodInfo method)
		{
			var directive = new MethodInjectionDirective(method);
			CreateArgumentsForMethod(binding, method).Each(directive.Arguments.Add);

			return directive;
		}
Example #14
0
        /// <summary>
        /// Registers the specified binding.
        /// </summary>
        /// <param name="binding">The binding to add.</param>
        public override void AddBinding(IBinding binding)
        {
            Ensure.ArgumentNotNull(binding, "binding");

            Kernel.AddBinding(binding);
            Bindings.Add(binding);
        }
 private void HandleBinding(object instance, IBinding binding)
 {
     if (!(AssignBinding(instance, binding) || ApplyBinding(instance, binding)))
     {
         throw new InvalidOperationException(
             $"Cannot assign to '{_xamlMember.Name}' on '{instance.GetType()}");
     }
 }
 /// <summary>
 ///
 /// </summary>
 /// <param name="binding"></param>
 /// <returns></returns>
 public object TryGet(IBinding binding)
 {
     lock (cache)
     {
         object instance;
         return cache.TryGetValue(binding, out instance) ? instance : null;
     }
 }
Example #17
0
        public CommandAutomation(IComponentContext context, CommandAutomationSettings settings)
        {
            Guard.NotNull(() => context, context);
            Guard.NotNull(() => settings, settings);

            // CommandAutomationSettings validates the cast is valid.
            this.command = context.Resolve<IBindingFactory>().CreateBinding<ICommand>(context, settings.Binding);
        }
Example #18
0
 protected static Mock<IContext> CreateContextMock(object scope, IBinding binding, params Type[] genericArguments)
 {
     var contextMock = new Mock<IContext>();
     contextMock.SetupGet(context => context.Binding).Returns(binding);
     contextMock.Setup(context => context.GetScope()).Returns(scope);
     contextMock.SetupGet(context => context.GenericArguments).Returns(genericArguments);
     contextMock.SetupGet(context => context.HasInferredGenericArguments).Returns(genericArguments != null && genericArguments.Length > 0);
     return contextMock;
 }
        public BoundCollectionChangedEventArgs(string propertyName, NotifyCollectionChangedEventArgs sourceEventArgs, IBinding binding, object[] PreviousCollectionContent)
        {
            Argument.NotNull(() => sourceEventArgs);

            this.PropertyName = propertyName;
            this.SourceEventArgs = sourceEventArgs;
            this.Binding = binding;
            this.PreviousCollectionContent = PreviousCollectionContent;
        }
Example #20
0
        protected override void AddBindingDependency(IBinding binding)
        {
            if (binding == null)
                return;

            if (_dependencies.Contains(binding))
                return;
            _dependencies.Add(binding);
        }
Example #21
0
 public static void AddBinding(Type targetType, string methodName, IBinding binding)
 {
     Dictionary<string, IBinding> bindings;
       if (!Cache.TryGetValue(targetType, out bindings))
       {
     bindings = new Dictionary<string, IBinding>();
     Cache.Add(targetType, bindings);
       }
       bindings[methodName] = binding;
 }
        public void Add(IBinding binding)
        {
            IList<IBinding> bindings;
            if (!_bindingDict.TryGetValue(binding.SourceType, out bindings)) {
                bindings = new List<IBinding>();
                _bindingDict.Add(binding.SourceType, bindings);
            }

            if (!binding.Multiple) bindings.Clear();
            bindings.Add(binding);
        }
Example #23
0
 private static void SetBinding(
     object instance,
     MutableMember member, 
     PerspexProperty property, 
     IBinding binding)
 {
     if (!(AssignBinding(instance, member, binding) || ApplyBinding(instance, property, binding)))
     {
         throw new InvalidOperationException(
             $"Cannot assign to '{member.Name}' on '{instance.GetType()}");
     }
 }
Example #24
0
        public object InvokeBinding(IBinding binding, IContextManager contextManager, object[] arguments, ITestTracer testTracer, out TimeSpan duration)
        {
            MethodInfo methodInfo;
            Delegate bindingAction;
            EnsureReflectionInfo(binding, out methodInfo, out bindingAction);

            try
            {
                object result;
                Stopwatch stopwatch = new Stopwatch();
                using (CreateCultureInfoScope(contextManager))
                {
                    stopwatch.Start();
                    object[] invokeArgs = new object[arguments == null ? 1 : arguments.Length + 1];
                    if (arguments != null)
                        Array.Copy(arguments, 0, invokeArgs, 1, arguments.Length);
                    invokeArgs[0] = contextManager;
                    result = bindingAction.DynamicInvoke(invokeArgs);

                    if (result is Task)
                    {
                        ((Task) result).Wait();
                    }

                    stopwatch.Stop();
                }

                if (runtimeConfiguration.TraceTimings && stopwatch.Elapsed >= runtimeConfiguration.MinTracedDuration)
                {
                    testTracer.TraceDuration(stopwatch.Elapsed, binding.Method, arguments);
                }

                duration = stopwatch.Elapsed;
                return result;
            }
            catch (ArgumentException ex)
            {
                throw errorProvider.GetCallError(binding.Method, ex);
            }
            catch (TargetInvocationException invEx)
            {
                var ex = invEx.InnerException;
                ex = ex.PreserveStackTrace(errorProvider.GetMethodText(binding.Method));
                throw ex;
            }
            catch (AggregateException agEx)  //from Task.Wait();
            {
                var ex = agEx.InnerExceptions.First();
                ex = ex.PreserveStackTrace(errorProvider.GetMethodText(binding.Method));
                throw ex;
            }
        }
 public void AddBinding(IBinding binding)
 {
     // always put bindings at the beginning so most recent bindings will be returned first
     List<IBinding> bindings;
     if (_bindings.TryGetValue(binding.ServiceType, out bindings))
     {
         bindings.Insert(0, binding);
     }
     else
     {
         _bindings[binding.ServiceType] = new List<IBinding> {binding};
     }
 }
		/*----------------------------------------------------------------------------------------*/
		#region Public Methods
		/// <summary>
		/// Registers a new binding.
		/// </summary>
		/// <param name="binding">The binding to register.</param>
		public void Add(IBinding binding)
		{
			Ensure.ArgumentNotNull(binding, "binding");
			Ensure.NotDisposed(this);

			lock (_bindings)
			{
				if (Logger.IsDebugEnabled)
					Logger.Debug("Adding {0}", Format.Binding(binding));

				_bindings.Add(binding.Service, binding);
			}
		}
        private bool AssignBinding(object instance, IBinding binding)
        {
            var property = instance.GetType()
                .GetRuntimeProperties()
                .FirstOrDefault(x => x.Name == _xamlMember.Name);

            if (property?.GetCustomAttribute<AssignBindingAttribute>() != null)
            {
                property.SetValue(instance, binding);
                return true;
            }

            return false;
        }
Example #28
0
        private void EnsureReflectionInfo(IBinding binding, out MethodInfo methodInfo, out Delegate bindingAction)
        {
            var methodBinding = binding as MethodBinding;
            if (methodBinding == null)
                throw new SpecFlowException("The binding method cannot be used for reflection: " + binding);

            methodInfo = methodBinding.Method.AssertMethodInfo();

            if (methodBinding.cachedBindingDelegate == null)
            {
                methodBinding.cachedBindingDelegate = CreateMethodDelegate(methodInfo);
            }

            bindingAction = methodBinding.cachedBindingDelegate;
        }
		/*----------------------------------------------------------------------------------------*/
		/// <summary>
		/// Executed to build the activation plan.
		/// </summary>
		/// <param name="binding">The binding that points at the type whose activation plan is being released.</param>
		/// <param name="type">The type whose activation plan is being manipulated.</param>
		/// <param name="plan">The activation plan that is being manipulated.</param>
		/// <returns>
		/// A value indicating whether to proceed or interrupt the strategy chain.
		/// </returns>
		public override StrategyResult Build(IBinding binding, Type type, IActivationPlan plan)
		{
			// Get the list of candidate constructors.
			ConstructorInfo[] candidates = type.GetConstructors(Kernel.Options.GetBindingFlags());
			ConstructorInfo injectionConstructor = binding.Components.MemberSelector.SelectConstructor(binding, plan, candidates);

			// If an injection constructor was found, create an injection directive for it.
			if (injectionConstructor != null)
			{
				ConstructorInjectionDirective directive = binding.Components.DirectiveFactory.Create(binding, injectionConstructor);
				plan.Directives.Add(directive);
			}

			return StrategyResult.Proceed;
		}
Example #30
0
        public void Inject(IKernel kernel, IBinding binding, TypeMetadata metadata, object instance)
        {
            if (metadata.TargetProperties.Count == 0)
            {
                return;
            }

            for (var i = 0; i < metadata.TargetProperties.Count; i++)
            {
                var property = metadata.TargetProperties[i];
                var parameter = binding.GetPropertyValue(property.Accessor.Name);
                var value = parameter != null ? parameter.Resolve(kernel) : kernel.Resolve(property.Accessor.Type, property.Constraint);
                property.Accessor.SetValue(instance, value);
            }
        }
Example #31
0
        /**
         * This method places individual Bindings into the bindings Dictionary
         * as part of the resolving process. Note that while some Bindings
         * may store multiple keys, each key takes a unique position in the
         * bindings Dictionary.
         *
         * Conflicts in the course of fluent binding are expected, but GetBinding
         * will throw an error if there are any unresolved conflicts.
         */
        virtual public void ResolveBinding(IBinding binding, object key)
        {
            //Check for existing conflicts
            if (conflicts.ContainsKey(key))             //does the current key have any conflicts?
            {
                Dictionary <IBinding, object> inConflict = conflicts [key];
                if (inConflict.ContainsKey(binding))                 //Am I on the conflict list?
                {
                    object conflictName = inConflict[binding];
                    if (isConflictCleared(inConflict, binding))                     //Am I now out of conflict?
                    {
                        clearConflict(key, conflictName, inConflict);               //remove all from conflict list.
                    }
                    else
                    {
                        return;                         //still in conflict
                    }
                }
            }

            //Check for and assign new conflicts
            object bindingName = (binding.name == null) ? BindingConst.NULLOID : binding.name;
            Dictionary <object, IBinding> dict;

            if ((bindings.ContainsKey(key)))
            {
                dict = bindings [key];
                //Will my registration create a new conflict?
                if (dict.ContainsKey(bindingName))
                {
                    //If the existing binding is not this binding, and the existing binding is not weak
                    //If it IS weak, we will proceed normally and overwrite the binding in the dictionary
                    IBinding existingBinding = dict[bindingName];
                    //if (existingBinding != binding && !existingBinding.isWeak)
                    //SDM2014-01-20: as part of cross-context implicit bindings fix, attempts by a weak binding to replace a non-weak binding are ignored instead of being
                    if (existingBinding != binding)
                    {
                        if (!existingBinding.isWeak && !binding.isWeak)
                        {
                            //register both conflictees
                            registerNameConflict(key, binding, dict[bindingName]);
                            return;
                        }

                        if (existingBinding.isWeak && (!binding.isWeak || existingBinding.value == null || existingBinding.value is System.Type))
                        {
                            //SDM2014-01-20: (in relation to the cross-context implicit bindings fix)
                            // 1) if the previous binding is weak and the new binding is not weak, then the new binding replaces the previous;
                            // 2) but if the new binding is also weak, then it only replaces the previous weak binding if the previous binding
                            // has not already been instantiated:

                            //Remove the previous binding.
                            dict.Remove(bindingName);
                        }
                    }
                }
            }
            else
            {
                dict           = new Dictionary <object, IBinding>();
                bindings [key] = dict;
            }

            //Remove nulloid bindings
            if (dict.ContainsKey(BindingConst.NULLOID) && dict[BindingConst.NULLOID].Equals(binding))
            {
                dict.Remove(BindingConst.NULLOID);
            }

            //Add (or override) our new binding!
            if (!dict.ContainsKey(bindingName))
            {
                dict.Add(bindingName, binding);
            }
        }
Example #32
0
 public virtual void Initialize(IBinding binding)
 {
 }
Example #33
0
 /// <summary>
 /// Creates a context for the specified request and binding.
 /// </summary>
 /// <param name="request">The request.</param>
 /// <param name="binding">The binding.</param>
 /// <returns>The created context.</returns>
 protected virtual IContext CreateContext(IRequest request, IBinding binding)
 {
     return(new Context(this, this.settings, request, binding, this.cache, this.planner, this.pipeline, this.exceptionFormatter));
 }
Example #34
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="kernel"></param>
 /// <param name="binding"></param>
 /// <returns></returns>
 public object Create(IKernel kernel, IBinding binding)
 {
     return(value);
 }
 public static TControl SetBinding <TControl, TProperty>(this TControl control, Expression <Func <TControl, TProperty> > prop, IBinding binding)
     where TControl : DotvvmBindableObject
 {
     control.SetBinding(control.GetDotvvmProperty(prop), binding);
     return(control);
 }
Example #36
0
 protected virtual void AddBindingDependency(IBinding binding)
 {
 }
Example #37
0
 public Collection FindCollection(string path, IBinding binding)
 {
     return(Find <Collection>(this, path, binding));
 }
Example #38
0
 public Property <int> FindEnumProperty(string path, IBinding binding)
 {
     return(Find <Property <int> >(this, path, binding));
 }
Example #39
0
        public Delegate FindCommand(string path, IBinding binding)
        {
            var result = Find <CommandContext>(this, path, binding);

            return(result == null ? null : result.GetValue());
        }
 internal void To(IBindingKey key, IBinding biding)
 {
     biding.CheckRequiremets(key, Name);
     m_bindings[key] = biding;
 }
Example #41
0
 public bool Remove(IBinding binding)
 {
     return(binding != null && dictionary.Remove(binding.BindingType, binding));
 }
Example #42
0
 public void RemoveBinding(IBinding binding)
 {
     throw new NotImplementedException();
 }
Example #43
0
 /// <summary>
 /// Registers the specified binding.
 /// </summary>
 /// <param name="binding">The binding to add.</param>
 public abstract void AddBinding(IBinding binding);
Example #44
0
        private static T Find <T>(object node, string path, IBinding binding)
            where T : class
        {
            if (node == null)
            {
                return(default(T));
            }

            var pointPos = path.IndexOf('.');

            if (pointPos < 0)
            {
                var c = node as Context;
                if (c == null)
                {
                    return(default(T));
                }

                var t = c.GetBindingTarget(path);
                if (t == null)
                {
                    return(default(T));
                }
                return(t as T);
            }

            var nodePropertyName = path.Substring(0, pointPos);
            var pathRest         = path.Substring(pointPos + 1);

            var context = node as Context;

            if (context != null)
            {
                context.AddBindingDependency(binding);
            }

            int collectionItemIndex;

            if (int.TryParse(nodePropertyName, out collectionItemIndex) && node is Collection)
            {
                var collection = (Collection)node;
                var varSubNode = collection.GetItemPlaceholder(collectionItemIndex);
                varSubNode.AddBindingDependency(binding);

                var valueSubNode = varSubNode.BaseValue;
                return((valueSubNode == null) ? default(T) : Find <T>(valueSubNode, pathRest, binding));
            }

            var subNode = context.GetBindingTarget(nodePropertyName);

            var subVarContext = subNode as VariableContext;

            if (subVarContext != null)
            {
                subVarContext.AddBindingDependency(binding);

                var subVarContextValue = subVarContext.BaseValue;
                return((subVarContextValue == null) ? default(T) : Find <T>(subVarContextValue, pathRest, binding));
            }

            return((subNode == null) ? default(T) : Find <T>(subNode, pathRest, binding));
        }
Example #45
0
 public BindingBuilder(IBinding binding)
 {
     _binding = binding;
 }
 internal void To <T>(IBinding binding)
 {
     To(new BindingKey(typeof(T)), binding);
 }
Example #47
0
 /// <summary>
 /// Unregisters the specified binding.
 /// </summary>
 /// <param name="binding">The binding to remove.</param>
 public override void RemoveBinding(IBinding binding)
 {
     this.kernelConfiguration.RemoveBinding(binding);
     this.isDirty = true;
 }
Example #48
0
 public WrapperBinding(IBinding inner, Wrapper parent)
 {
     _inner  = inner;
     _parent = parent;
 }
Example #49
0
        private object ResolveSingleUnique(IRequest request, bool handleMissingBindings)
        {
            var      bindings         = this.GetBindingsCore(request.Service);
            IBinding satisfiedBinding = null;

            for (var i = 0; i < bindings.Length; i++)
            {
                var binding = bindings[i];

                if (!this.SatifiesRequest(request, binding))
                {
                    continue;
                }

                if (satisfiedBinding != null)
                {
                    if (this.bindingPrecedenceComparer.Compare(satisfiedBinding, binding) == 0)
                    {
                        if (request.IsOptional && !request.ForceUnique)
                        {
                            return(null);
                        }

                        var formattedBindings = new List <string>
                        {
                            satisfiedBinding.Format(this.CreateContext(request, satisfiedBinding)),
                            binding.Format(this.CreateContext(request, binding)),
                        };

                        for (i++; i < bindings.Length; i++)
                        {
                            if (!this.SatifiesRequest(request, bindings[i]))
                            {
                                continue;
                            }

                            formattedBindings.Add(bindings[i].Format(this.CreateContext(request, bindings[i])));
                        }

                        throw new ActivationException(ExceptionFormatter.CouldNotUniquelyResolveBinding(
                                                          request,
                                                          formattedBindings.ToArray()));
                    }
                    else
                    {
                        break;
                    }
                }

                satisfiedBinding = binding;
            }

            if (satisfiedBinding != null)
            {
                return(this.CreateContext(request, satisfiedBinding).Resolve());
            }

            var collection = this.ResolveCollection(request);

            if (collection != null)
            {
                return(collection);
            }

            if (handleMissingBindings && this.HandleMissingBinding(request))
            {
                return(this.ResolveSingle(request, false));
            }

            if (request.IsOptional)
            {
                return(null);
            }

            throw new ActivationException(this.exceptionFormatter.CouldNotResolveBinding(request));
        }
Example #50
0
        /// <summary>
        /// Consumes an individual JSON element and returns the Binding that element represents
        /// </summary>
        /// <returns>The Binding represented the provided JSON</returns>
        /// <param name="item">A Dictionary of definitions for the individual binding parameters</param>
        /// <param name="testBinding">An example binding for the current Binder. This method uses the
        /// binding constraints of the example to raise errors if asked to parse illegally</param>
        virtual protected IBinding ConsumeItem(Dictionary <string, object> item, IBinding testBinding)
        {
            int bindConstraints = (testBinding.keyConstraint == BindingConstraintType.ONE) ? 0 : 1;

            bindConstraints |= (testBinding.valueConstraint == BindingConstraintType.ONE) ? 0 : 2;
            IBinding      binding = null;
            List <object> keyList;
            List <object> valueList;

            if (item != null)
            {
                item = ConformRuntimeItem(item);
                // Check that Bind exists
                if (!item.ContainsKey("Bind"))
                {
                    throw new BinderException("Attempted to consume a binding without a bind key.", BinderExceptionType.RUNTIME_NO_BIND);
                }
                else
                {
                    keyList = conformRuntimeToList(item ["Bind"]);
                }
                // Check that key counts match the binding constraint
                if (keyList.Count > 1 && (bindConstraints & 1) == 0)
                {
                    throw new BinderException("Binder " + this.ToString() + " supports only a single binding key. A runtime binding key including " + keyList [0].ToString() + " is trying to add more.", BinderExceptionType.RUNTIME_TOO_MANY_KEYS);
                }

                if (!item.ContainsKey("To"))
                {
                    valueList = keyList;
                }
                else
                {
                    valueList = conformRuntimeToList(item ["To"]);
                }
                // Check that value counts match the binding constraint
                if (valueList.Count > 1 && (bindConstraints & 2) == 0)
                {
                    throw new BinderException("Binder " + this.ToString() + " supports only a single binding value. A runtime binding value including " + valueList [0].ToString() + " is trying to add more.", BinderExceptionType.RUNTIME_TOO_MANY_VALUES);
                }

                // Check Whitelist if it exists
                if (bindingWhitelist != null)
                {
                    bindingWhitelist.ForEach(val => UnityEngine.Debug.LogFormat("Whitelist value: {0}, type: {1}.", val.ToString(), val.GetType().Name));
                    foreach (object value in valueList)
                    {
                        if (bindingWhitelist.IndexOf(value.ToString()) == -1)
                        {
                            throw new BinderException("Value " + value.ToString() + " not found on whitelist for " + this.ToString() + ".", BinderExceptionType.RUNTIME_FAILED_WHITELIST_CHECK);
                        }
                    }
                }

                binding = performKeyValueBindings(keyList, valueList);

                // Optionally look for ToName
                if (item.ContainsKey("ToName"))
                {
                    binding = binding.ToName(item ["ToName"]);
                }

                // Add runtime options
                if (item.ContainsKey("Options"))
                {
                    List <object> optionsList = conformRuntimeToList(item ["Options"]);
                    addRuntimeOptions(binding, optionsList);
                }
            }
            return(binding);
        }
Example #51
0
 /// <summary>
 /// Returns a value incating whether a given <see cref="IBinding"/> matches the request.
 /// </summary>
 /// <param name="request">The request/.</param>
 /// <param name="binding">The <see cref="IBinding"/>.</param>
 /// <returns>
 /// <see langword="true"/> if the <see cref="IBinding"/> matches the request; otherwise, <see langword="false"/>.
 /// </returns>
 protected virtual bool SatifiesRequest(IRequest request, IBinding binding)
 {
     return(binding.Matches(request) && request.Matches(binding));
 }
Example #52
0
 public abstract object Handle(IBinding binding, Type type, string name);
Example #53
0
 private bool IsImplicitQueueBinding(IBinding binding)
 {
     return(IsDefaultExchange(binding.Exchange) && binding.Destination.Equals(binding.RoutingKey));
 }
Example #54
0
        internal async Task IndexMethodAsyncCore(MethodInfo method, IFunctionIndexCollector index, CancellationToken cancellationToken)
        {
            Debug.Assert(method != null);
            bool hasNoAutomaticTriggerAttribute = method.GetCustomAttribute <NoAutomaticTriggerAttribute>() != null;

            ITriggerBinding             triggerBinding   = null;
            ParameterInfo               triggerParameter = null;
            IEnumerable <ParameterInfo> parameters       = method.GetParameters();

            foreach (ParameterInfo parameter in parameters)
            {
                ITriggerBinding possibleTriggerBinding = await _triggerBindingProvider.TryCreateAsync(new TriggerBindingProviderContext(parameter, cancellationToken));

                if (possibleTriggerBinding != null)
                {
                    if (triggerBinding == null)
                    {
                        triggerBinding   = possibleTriggerBinding;
                        triggerParameter = parameter;
                    }
                    else
                    {
                        throw new InvalidOperationException("More than one trigger per function is not allowed.");
                    }
                }
            }

            Dictionary <string, IBinding>      nonTriggerBindings = new Dictionary <string, IBinding>();
            IReadOnlyDictionary <string, Type> bindingDataContract;

            if (triggerBinding != null)
            {
                bindingDataContract = triggerBinding.BindingDataContract;
            }
            else
            {
                bindingDataContract = null;
            }

            bool      hasParameterBindingAttribute  = false;
            Exception invalidInvokeBindingException = null;

            ReturnParameterInfo returnParameter = null;
            bool triggerHasReturnBinding        = false;

            if (TypeUtility.TryGetReturnType(method, out Type methodReturnType))
            {
                if (bindingDataContract != null && bindingDataContract.TryGetValue(ReturnParamName, out Type triggerReturnType))
                {
                    // The trigger will handle the return value.
                    triggerHasReturnBinding = true;
                }

                // We treat binding to the return type the same as binding to an 'out T' parameter.
                // An explicit return binding takes precedence over an implicit trigger binding.
                returnParameter = new ReturnParameterInfo(method, methodReturnType);
                parameters      = parameters.Concat(new ParameterInfo[] { returnParameter });
            }

            foreach (ParameterInfo parameter in parameters)
            {
                if (parameter == triggerParameter)
                {
                    continue;
                }

                IBinding binding = await _bindingProvider.TryCreateAsync(new BindingProviderContext(parameter, bindingDataContract, cancellationToken));

                if (binding == null)
                {
                    if (parameter == returnParameter)
                    {
                        if (triggerHasReturnBinding)
                        {
                            // Ok. Skip and let trigger own the return binding.
                            continue;
                        }
                        else
                        {
                            // If the method has a return value, then we must have a binding to it.
                            // This is similar to the error we used to throw.
                            invalidInvokeBindingException = new InvalidOperationException("Functions must return Task or void, have a binding attribute for the return value, or be triggered by a binding that natively supports return values.");
                        }
                    }

                    if (triggerBinding != null && !hasNoAutomaticTriggerAttribute)
                    {
                        throw new InvalidOperationException(
                                  string.Format(Constants.UnableToBindParameterFormat,
                                                parameter.Name, parameter.ParameterType.Name, Constants.ExtensionInitializationMessage));
                    }
                    else
                    {
                        // Host.Call-only parameter
                        binding = InvokeBinding.Create(parameter.Name, parameter.ParameterType);
                        if (binding == null && invalidInvokeBindingException == null)
                        {
                            // This function might not have any attribute, in which case we shouldn't throw an
                            // exception when we can't bind it. Instead, save this exception for later once we determine
                            // whether or not it is an SDK function.
                            invalidInvokeBindingException = new InvalidOperationException(
                                string.Format(Constants.UnableToBindParameterFormat,
                                              parameter.Name, parameter.ParameterType.Name, Constants.ExtensionInitializationMessage));
                        }
                    }
                }
                else if (!hasParameterBindingAttribute)
                {
                    hasParameterBindingAttribute = binding.FromAttribute;
                }

                nonTriggerBindings.Add(parameter.Name, binding);
            }

            // Only index functions with some kind of attribute on them. Three ways that could happen:
            // 1. There's an attribute on a trigger parameter (all triggers come from attributes).
            // 2. There's an attribute on a non-trigger parameter (some non-trigger bindings come from attributes).
            if (triggerBinding == null && !hasParameterBindingAttribute)
            {
                // 3. There's an attribute on the method itself (NoAutomaticTrigger).
                if (method.GetCustomAttribute <NoAutomaticTriggerAttribute>() == null)
                {
                    return;
                }
            }

            if (TypeUtility.IsAsyncVoid(method))
            {
                string msg = $"Function '{method.Name}' is async but does not return a Task. Your function may not run correctly.";
                _trace.Warning(msg);
                _logger?.LogWarning(msg);
            }

            if (invalidInvokeBindingException != null)
            {
                throw invalidInvokeBindingException;
            }

            // Validation: prevent multiple ConsoleOutputs
            if (nonTriggerBindings.OfType <TraceWriterBinding>().Count() > 1)
            {
                throw new InvalidOperationException("Can't have multiple TraceWriter/TextWriter parameters in a single function.");
            }

            string              triggerParameterName = triggerParameter != null ? triggerParameter.Name : null;
            FunctionDescriptor  functionDescriptor   = CreateFunctionDescriptor(method, triggerParameterName, triggerBinding, nonTriggerBindings);
            IFunctionInvoker    invoker = FunctionInvokerFactory.Create(method, _activator);
            IFunctionDefinition functionDefinition;

            if (triggerBinding != null)
            {
                Type triggerValueType = triggerBinding.TriggerValueType;
                var  methodInfo       = typeof(FunctionIndexer).GetMethod("CreateTriggeredFunctionDefinition", BindingFlags.Instance | BindingFlags.NonPublic).MakeGenericMethod(triggerValueType);
                functionDefinition = (FunctionDefinition)methodInfo.Invoke(this, new object[] { triggerBinding, triggerParameterName, functionDescriptor, nonTriggerBindings, invoker });

                if (hasNoAutomaticTriggerAttribute && functionDefinition != null)
                {
                    functionDefinition = new FunctionDefinition(functionDescriptor, functionDefinition.InstanceFactory, listenerFactory: null);
                }
            }
            else
            {
                IFunctionInstanceFactory instanceFactory = new FunctionInstanceFactory(new FunctionBinding(functionDescriptor, nonTriggerBindings, _singletonManager), invoker, functionDescriptor);
                functionDefinition = new FunctionDefinition(functionDescriptor, instanceFactory, listenerFactory: null);
            }

            index.Add(functionDefinition, functionDescriptor, method);
        }
Example #55
0
        public virtual object ComputeProperty(Type type, IBinding binding)
        {
            if (type == typeof(BindingCompilationService))
            {
                return(this);
            }
            if (type.IsAssignableFrom(binding.GetType()))
            {
                return(binding);
            }

            var additionalResolvers = GetAdditionalResolvers(binding);
            var bindingResolvers    = GetResolversForBinding(binding.GetType());

            var resolver = additionalResolvers?.FindResolver(type) ??
                           bindingResolvers.FindResolver(type) ??
                           this.resolvers.FindResolver(type);

            object?getParameterValue(ParameterInfo p) => binding.GetProperty(p.ParameterType, p.HasDefaultValue ? ErrorHandlingMode.ReturnNull : ErrorHandlingMode.ReturnException) ?? p.DefaultValue;

            Exception?checkArguments(object?[] arguments) =>
            arguments.OfType <Exception>().ToArray() is var exceptions && exceptions.Any() ?
            new BindingPropertyException(binding, type, "unresolvable arguments", exceptions) :
            null;

            if (resolver != null)
            {
                var arguments = resolver.Method.GetParameters().Select(getParameterValue).ToArray();
                { if (checkArguments(arguments) is Exception exc)
                  {
                      return(exc);
                  }
                }
                var value = resolver.ExceptionSafeDynamicInvoke(arguments);
                // post process the value
                foreach (var postProcessor in this.resolvers.GetPostProcessors(type)
                         .Concat(bindingResolvers.GetPostProcessors(type)
                                 .Concat(additionalResolvers?.GetPostProcessors(type) ?? Enumerable.Empty <Delegate>())))
                {
                    var method = postProcessor.Method;
                    arguments = new[] { value }.Concat(method.GetParameters().Skip(1).Select(getParameterValue)).ToArray();
                    if (checkArguments(arguments) is Exception exc)
                    {
                        return(exc);
                    }
                    value = postProcessor.ExceptionSafeDynamicInvoke(arguments) ?? value;
                }
                return(value ?? new BindingPropertyException(binding, type, "resolver returned null"));
            }
            if (typeof(Delegate).IsAssignableFrom(type))
            {
                var result = ComputeProperty(typeof(Expression <>).MakeGenericType(type), binding);
                if (result is LambdaExpression lambda)
                {
                    return(expressionCompiler.Compile(lambda));
                }
                else
                {
                    return(result);
                }
            }
            else
            {
                return(new BindingPropertyException(binding, type, "resolver not found")); // don't throw the exception, since it creates noise for debugger
            }
        }
Example #56
0
        private ReadCommandOperation <AggregateResult> CreateOperation(IChannel channel, IBinding binding)
        {
            var databaseNamespace = _collectionNamespace == null ? _databaseNamespace : _collectionNamespace.DatabaseNamespace;
            var command           = CreateCommand(channel.ConnectionDescription, binding.Session);
            var serializer        = new AggregateResultDeserializer(_resultSerializer);

            return(new ReadCommandOperation <AggregateResult>(databaseNamespace, command, serializer, MessageEncoderSettings));
        }
Example #57
0
 public override void InitializeBinding(IBinding binding, IEnumerable <BindingCompilationRequirementsAttribute>?bindingRequirements = null)
 {
     // no-op
 }
Example #58
0
 /// <summary>
 /// Unregisters the specified binding.
 /// </summary>
 /// <param name="binding">The binding to remove.</param>
 public abstract void RemoveBinding(IBinding binding);
Example #59
0
 public static IServiceCollection AddRabbitBinding(this IServiceCollection services, IBinding binding)
 {
     services.RegisterService(binding.ServiceName, typeof(IBinding));
     services.AddSingleton <IBinding>(binding);
     return(services);
 }
Example #60
0
 /// <summary>
 /// Sets the binding to a specified property.
 /// </summary>
 public void SetBinding(DotvvmProperty property, IBinding binding)
 {
     SetValueRaw(property, binding);
 }