// this has been through red and green phase, it has yet to see it's refactor phase
 public Type Close(Type conversionPatternType, Type sourceType, Type targetType)
 {
     var @interface = conversionPatternType.GetInterface(typeof (IConversionPattern<,>));
     if (@interface == null)
     {
         throw new ArgumentException(string.Format("Type {0} doesn't implement {1} and therefore is invalid for this operation.", conversionPatternType, typeof (IConversionPattern<,>)));
     }
     var arguments = @interface.GetGenericArguments();
     var interfaceSourceType = arguments[0];
     var interfaceTargetType = arguments[1];
     if (conversionPatternType.IsGenericType == false)
     {
         if (sourceType.Is(interfaceSourceType) && targetType.Is(interfaceTargetType))
         {
             return conversionPatternType;
         }
         return null;
     }
     var openClassArguments = conversionPatternType.GetGenericArguments();
     var parameters = new Type[openClassArguments.Length];
     if (TryAddParameters(sourceType, interfaceSourceType, parameters, openClassArguments) == false)
     {
         return null;
     }
     if (TryAddParameters(targetType, interfaceTargetType, parameters, openClassArguments) == false)
     {
         return null;
     }
     if (parameters.Any(p => p == null))
     {
         return null;
     }
     return conversionPatternType.MakeGenericType(parameters);
 }
        public IBindingScope To(Type concreteType)
        {
            Assert.IsNotNull(concreteType);
            Assert.IsTrue(concreteType.IsConcrete());
            Assert.IsTrue(concreteType.Is(ContractType));

            return ToMethod(c => c.Container.Instantiator
                .Instantiate(new InjectionContext { Container = c.Container, DeclaringType = concreteType }));
        }
 public override bool CanConvert(Type objectType)
 {
     // Type should not be a User or Device since these have their specific serializers.
     // This serializer should be used for any other type that inherits from article.
     if (objectType != typeof(User) && objectType != typeof(Device))
         return objectType.Is<Article>();
     else 
         return false;
 }
示例#4
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="jobType">The type of the class that implements the job</param>
        /// <param name="builder">The trigger builder</param>
        public JobConfiguration(
            Type jobType,
            Func<TriggerBuilder> builder)
        {
            jobType.Is<IJob>();
            builder.NotNull(nameof(builder));

            JobType = jobType;
            TriggerBuilder = builder;
        }
        public IBindingScope ToFactory(Type factoryType)
        {
            Assert.IsNotNull(factoryType);
            Assert.IsTrue(factoryType.Is<IInjectionFactory>());

            Container.Binder.Bind(factoryType).ToSelf().AsSingleton();

            return ToMethod(c => ((IInjectionFactory)c.Container.Resolver
                .Resolve(new InjectionContext { Container = c.Container, ContractType = factoryType }))
                .Create(c));
        }
		public IInterceptor[] SelectInterceptors(Type type, MethodInfo method, IInterceptor[] interceptors)
		{
			if (type.Is<ICatalog>())
			{
				if (method.Name == "AddItem")
				{
					return interceptors;
				}
			}
			return null;
		}
示例#7
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="exceptionMessage">Exception message to be included in the new exception</param>
        /// <param name="exceptionType">Type of the new exception to be created</param>
        public AbstractHandler(
            string exceptionMessage,
            Type exceptionType)
        {
            exceptionMessage.NotNullOrEmpty(nameof(exceptionMessage));
            exceptionType.NotNull(nameof(exceptionType));
            exceptionType.Is<Exception>();

            _exceptionMessage = exceptionMessage;
            ExceptionType = exceptionType;
        }
		/// <summary>
		///   Defines the <see cref = "ITypeConverter" /> to be used to convert the type
		/// </summary>
		/// <param name = "converterType"></param>
		public ConvertibleAttribute(Type converterType)
		{
			if (converterType.Is<ITypeConverter>() == false)
			{
				throw new ArgumentException(
					string.Format("ConverterType {0} does not implement {1} interface", converterType.FullName,
					              typeof(ITypeConverter).FullName), "converterType");
			}

			this.converterType = converterType;
		}
        /// <summary>
        /// Generates the key that should be use to cache/retrieve the content
        /// for the given controllerType and action name
        /// </summary>
        /// <param name="controllerType">The controller type (must be ApiController)</param>
        /// <param name="actionName">The action name</param>
        /// <param name="context">The action context</param>
        /// <returns>The key for the given controller type and action name</returns>
        /// <exception cref="ArgumentException">If controller type is not an ApiController</exception>
        public virtual string Generate(
            Type controllerType,
            string actionName,
            HttpActionContext context)
        {
            controllerType.NotNull(nameof(controllerType));
            controllerType.Is<ApiController>();
            actionName.NotNullOrEmpty(nameof(actionName));
            context.NotNull(nameof(context));

            return "{0}-{1}".AsFormat(controllerType.FullName, actionName);
        }
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="controllerType">The controller type (must be ApiController)</param>
        /// <param name="actionName">The action name</param>
        /// <param name="cacheKeyGeneratorType">The type of the class responsible for generating the keys</param>
        public InvalidateXReferencedOutputCacheAttribute(
            Type controllerType,
            string actionName,
            Type cacheKeyGeneratorType = null)
        {
            controllerType.NotNull(nameof(controllerType));
            controllerType.Is<ApiController>();
            actionName.NotNullOrEmpty(nameof(actionName));

            ActionName = actionName;
            ControllerType = controllerType;
            CacheKeyGeneratorType = cacheKeyGeneratorType ?? typeof(DefaultCacheKeyGenerator);
        }
        public override object GetValue(IContent content, PropertyInfo property, Type collectionItemType)
        {
            // Let's support both Pages and ContentReference collections
            bool returnReferences = collectionItemType.Is<ContentReference>();

            var descendents = ContentLoader.GetDescendents(content.ContentLink);

            var result = returnReferences
                ? descendents.ToList()
                : GetPagesCollection(() => descendents, collectionItemType);

            return result;
        }
		public void AddNodeProcessor(Type type)
		{
			if (type.Is<IXmlNodeProcessor>())
			{
				var processor = type.CreateInstance<IXmlNodeProcessor>();
				foreach(var nodeType in processor.AcceptNodeTypes)
				{
					RegisterProcessor(nodeType, processor);
				}
			}
			else
			{
				throw new XmlProcessorException("{0} does not implement IElementProcessor interface", type.FullName);
			}
		}
示例#13
0
		public static MethodInfo ExtractInvokeMethod(Type service)
		{
			if (!service.Is<MulticastDelegate>())
			{
				return null;
			}

			var invoke = GetInvokeMethod(service);
			if (!HasReturn(invoke))
			{
				return null;
			}

			return invoke;
		}
示例#14
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="processorType">The type that implments IProcessor</param>
        public JobAttribute(Type processorType)
        {
            processorType.Is<IProcessor>();

            ProcessorType = processorType;
        }
        void Subscribe( IMessageBroker broker, String key, IHandler h, Type genericHandler, InvocationModel invocationModel )
        {
            /*
             * Qui abbiamo un problema di questo tipo: quando in Castle viene
             * registrato un componente per più di un servizio, ergo per più 
             * interfacce vogliamo venga risolto lo stesso tipo, abbiamo l'inghippo
             * che Castle registra n componenti che risolvono verso lo stesso tipo
             * tante quante sono le interfacce. Quindi l'evento qui registrato viene
             * scatenato n volte e siccome il primo test che noi facciamo è verificare
             * che il servizio sia IMessageHandler se un componente gestisce n messaggi
             * arriviamo qui n volte. Se il componente inoltre richiede la Subscribe
             * automatica per quei messaggi, ha quindi più di un SubscribeToMessageAttribute
             * dobbiamo assicurarci che la subscribe venga fatta una ed una sola volta.
             * per ogni tipo di messaggio.
             */
            var messageType = genericHandler.GetGenericArguments().Single(); // attribute.MessageType;

            logger.Debug
            (
                "\tSubscribing to message: {0}",
                messageType.ToString( "SN" )
            );

            if ( genericHandler.Is<IMessageHandler>() )
            {
                broker.Subscribe( this, messageType, invocationModel, msg =>
                {
                    if ( this.Kernel != null )
                    {
                        var handler = this.Kernel.Resolve( key, h.ComponentModel.Services.First() ) as IMessageHandler;
                        if ( handler != null )
                        {
                            logger.Debug
                            (
                                "Dispatching message {0} to IMessageHandler {1}",
                                msg.GetType().ToString( "SN" ),
                                handler.GetType().ToString( "SN" )
                            );

                            if ( handler.ShouldHandle( msg ) )
                            {
                                handler.Handle( msg );
                            }
                        }
                        else
                        {
                            logger.Debug
                            (
                                "IMessageHandler for {0} is null.",
                                msg.GetType().ToString( "SN" )
                            );
                        }
                    }
                    else
                    {
                        logger.Debug( "Kernel is null." );
                        logger.Debug( "Kernel is null." );
                    }
                } );
            }
            else if ( genericHandler.Is<IHandleMessage>() )
            {
                broker.Subscribe( this, messageType, invocationModel, ( s, msg ) =>
                {
                    if ( this.Kernel != null )
                    {
                        var handler = this.Kernel.Resolve( key, h.ComponentModel.Services.First() ) as IHandleMessage;
                        if ( handler != null )
                        {
                            logger.Debug
                            (
                                "Dispatching message {0} to IHandleMessage {1}",
                                msg.GetType().ToString( "SN" ),
                                handler.GetType().ToString( "SN" )
                            );

                            if ( handler.ShouldHandle( s, msg ) )
                            {
                                handler.Handle( s, msg );
                            }
                        }
                        else
                        {
                            logger.Debug
                            (
                                "IHandleMessage for {0} is null.",
                                msg.GetType().ToString( "SN" )
                            );
                        }
                    }
                    else
                    {
                        logger.Debug( "Kernel is null." );
                    }
                } );
            }
        }
		void Subscribe( IContainer container, IMessageBroker broker, Guid key, Bag bag, Type genericHandler, InvocationModel invocationModel )
		{
			var messageType = genericHandler.GetGenericArguments().Single();

			logger.Debug
			(
				"\tSubscribing to message: {0}",
				messageType.ToString( "SN" )
			);

			if ( genericHandler.Is<IMessageHandler>() )
			{
				broker.Subscribe( this, messageType, invocationModel, msg =>
				{
					var handler = container.Resolve( bag.Services.FirstOrDefault() ) as IMessageHandler;
					if ( handler != null )
					{
						logger.Debug
						(
							"Dispatching message {0} to IMessageHandler {1}",
								msg.GetType().ToString( "SN" ),
								handler.GetType().ToString( "SN" )
						);

						if ( handler.ShouldHandle( msg ) )
						{
							handler.Handle( msg );
						}
					}
					else
					{
						logger.Debug
						(
							"IMessageHandler for {0} is null.",
							msg.GetType().ToString( "SN" )
						);
					}
				} );
			}
			else if ( genericHandler.Is<IHandleMessage>() )
			{
				broker.Subscribe( this, messageType, invocationModel, ( s, msg ) =>
				{
					var handler = container.Resolve( bag.Services.FirstOrDefault() ) as IHandleMessage;
					if ( handler != null )
					{
						logger.Debug
						(
							"Dispatching message {0} to IHandleMessage {1}",
								msg.GetType().ToString( "SN" ),
								handler.GetType().ToString( "SN" )
						);

						if ( handler.ShouldHandle( s, msg ) )
						{
							handler.Handle( s, msg );
						}
					}
					else
					{
						logger.Debug
						(
							"IHandleMessage for {0} is null.",
							msg.GetType().ToString( "SN" )
						);
					}
				} );
			}
		}
 public override bool CanConvert(Type objectType)
 {
     return objectType.Is<APConnection>();
 }
        /// <summary>
        /// Sets up the interfaces used
        /// </summary>
        /// <param name="Type">The object type</param>
        /// <returns>The code used</returns>
        public string SetupInterfaces(Type Type)
        {
            var Builder = new StringBuilder();
            Builder.AppendLine(@"public Session Session0{ get; set; }");
            Builder.AppendLine(@"public IList<string> PropertiesChanged0{ get; set; }");
            if (!Type.Is<INotifyPropertyChanged>())
            {
                Builder.AppendLine(@"private PropertyChangedEventHandler propertyChanged_;
            public event PropertyChangedEventHandler PropertyChanged
            {
            add
            {
            propertyChanged_-=value;
            propertyChanged_+=value;
            }

            remove
            {
            propertyChanged_-=value;
            }
            }");
                Builder.AppendLine(@"private void NotifyPropertyChanged0([CallerMemberName]string propertyName="""")
            {
            var Handler = propertyChanged_;
            if (Handler != null)
            Handler(this, new PropertyChangedEventArgs(propertyName));
            }");
            }
            Builder.AppendLine(SetupFields(Type));
            return Builder.ToString();
        }
示例#19
0
 public override IEnumerable<Handler> this[Type type] { get { return type.Is(Type) ? Handler[type] : new Handler[0]; } }
 public override bool CanConvert(Type objectType)
 {
     return objectType.Is<IObjectUpdateRequest>();
 }
 bool _IsValidType(System.Type type)
 {
     return(type.Is(tType));
 }
		private bool IsInstaller(Type type)
		{
			return type.IsClass &&
			       type.IsAbstract == false &&
			       type.IsGenericTypeDefinition == false &&
			       type.Is<IWindsorInstaller>();
		}
 public PermissionAllowed(Type moduleType, Permission permission)
 {
     if (!moduleType.Is<IPermissionModule>()) throw new ErrorException(CoreResource.Authoriztion_NotPermissionModule);
     _moduleType = moduleType;
     _permission = permission;
 }
        bool TryAddParameters(Type classType, Type interfaceType, Type[] parameters, Type[] openClassArguments)
        {
            if (interfaceType.ContainsGenericParameters == false)
            {
                return classType.Is(interfaceType);
            }

            // for now we only allow that if it's a generic argument of the sourceType
            var index = Array.IndexOf(openClassArguments, interfaceType);
            if (index == -1)
            {
                if (interfaceType.IsGenericType)
                {
                    if (classType.IsGenericType == false)
                    {
                        return false;
                    }
                    var openInterfaceType = interfaceType.GetGenericTypeDefinition();
                    var openClassType = classType.GetGenericTypeDefinition();
                    // we don't support assignable types for now
                    if (openInterfaceType != openClassType)
                    {
                        return false;
                    }
                    var interfaceGenericArguments = interfaceType.GetGenericArguments();
                    var classGenericArguments = classType.GetGenericArguments();
                    for (var i = 0; i < interfaceGenericArguments.Length; i++)
                    {
                        if (interfaceGenericArguments[i].ContainsGenericParameters)
                        {
                            // for now we only allow that if it's a generic argument of the sourceType
                            index = Array.IndexOf(openClassArguments, interfaceGenericArguments[i]);
                            if (index == -1)
                            {
                                return false;
                            }
                            parameters[index] = EnsureMeetsGenericConstraints(classGenericArguments[i], interfaceGenericArguments[i]);
                        }
                    }
                }
                if (interfaceType.IsArray)
                {
                    var classArrayItemType = classType.GetArrayItemType();
                    if (classArrayItemType != null)
                    {
                        var interfaceArrayItemType = interfaceType.GetElementType();
                        // for now we only allow that if it's a generic argument of the sourceType
                        index = Array.IndexOf(openClassArguments, interfaceArrayItemType);
                        if (index == -1)
                        {
                            return false;
                        }
                        parameters[index] = EnsureMeetsGenericConstraints(classArrayItemType, interfaceArrayItemType);
                    }
                }
            }
            else
            {
                parameters[index] = EnsureMeetsGenericConstraints(classType, interfaceType);
            }
            return true;
        }
示例#25
0
 public static bool Is <T>([NotNull] this Type @this) => @this.Is(typeof(T));
示例#26
0
 public void should_fail_to_parse_invalid_string_values_and_return_friendly_message(Type type, object value)
 {
     if (type.Is<string>()) return;
     var messageType = type.GetUnderlyingNullableType();
     messageType = messageType.IsEnum ? typeof(Enum) : messageType;
     Assert.Throws<ValueParseException>(() => new ValueNode(CreateContext(Mode.Deserialize), 
             null, new SimpleValue(type.ToCachedType()), null, null).Value = "yada")
         .FriendlyMessage.ShouldEqual(Options.Create().Deserialization
             .FriendlyParseErrorMessages[messageType].ToFormat("yada"));
 }
		void Subscribe( IMessageBroker broker, String key, RegisterEventArgs h, Type genericHandler, InvocationModel invocationModel )
		{
			var messageType = genericHandler.GetGenericArguments().Single();

			logger.Debug
			(
				"\tSubscribing to message: {0}",
				messageType.ToString( "SN" )
			);

			if ( genericHandler.Is<IMessageHandler>() )
			{
				broker.Subscribe( this, messageType, invocationModel, msg =>
				{
					if ( this.Container != null )
					{
						var handler = this.Container.Resolve( h.TypeFrom, key ) as IMessageHandler;
						if ( handler != null )
						{
							logger.Debug
							(
								"Dispatching message {0} to IMessageHandler {1}",
									msg.GetType().ToString( "SN" ),
									handler.GetType().ToString( "SN" )
							);

							if ( handler.ShouldHandle( msg ) )
							{
								handler.Handle( msg );
							}
						}
						else
						{
							logger.Debug
							(
								"IMessageHandler for {0} is null.",
								msg.GetType().ToString( "SN" )
							);
						}
					}
					else
					{
						logger.Debug( "Kernel is null." );
						logger.Debug( "Kernel is null." );
					}
				} );
			}
			else if ( genericHandler.Is<IHandleMessage>() )
			{
				broker.Subscribe( this, messageType, invocationModel, ( s, msg ) =>
				{
					if ( this.Container != null )
					{
						var handler = this.Container.Resolve( h.TypeFrom, key ) as IHandleMessage;
						if ( handler != null )
						{
							logger.Debug
							(
								"Dispatching message {0} to IHandleMessage {1}",
									msg.GetType().ToString( "SN" ),
									handler.GetType().ToString( "SN" )
							);

							if ( handler.ShouldHandle( s, msg ) )
							{
								handler.Handle( s, msg );
							}
						}
						else
						{
							logger.Debug
							(
								"IHandleMessage for {0} is null.",
								msg.GetType().ToString( "SN" )
							);
						}
					}
					else
					{
						logger.Debug( "Kernel is null." );
					}
				} );
			}
		}
		protected virtual void ValidateLifestyleManager(Type customLifestyleManager)
		{
			if (customLifestyleManager.Is<ILifestyleManager>() == false)
			{
				var message =
					String.Format(
						"The Type '{0}' specified in the componentActivatorType attribute must implement {1}",
						customLifestyleManager.FullName, typeof(ILifestyleManager).FullName);
				throw new InvalidOperationException(message);
			}
		}
 public ICreateInstanceBehavior GetBehavior(string type, Type instanceType)
 {
     if ("device".Equals(type) == true || instanceType.Is<APDevice>() == true)
         return new CreateDeviceBehavior();
     else if ("user".Equals(type) == true || instanceType.Is<APUser>() == true)
         return new CreateUserBehavior();
     else return new CreateObjectBehavior();
 }
 protected override bool CanFullfill(Type type, string name, IContract contract)
 {
     return type.Is<IConfigurationSource>();
 }
		/// <summary>
		///   Validates that the provide type implements IComponentActivator
		/// </summary>
		/// <param name = "customComponentActivator">The custom component activator.</param>
		protected virtual void ValidateComponentActivator(Type customComponentActivator)
		{
			if (customComponentActivator.Is<IComponentActivator>() == false)
			{
				var message =
					String.Format(
						"The Type '{0}' specified in the componentActivatorType attribute must implement Castle.MicroKernel.IComponentActivator",
						customComponentActivator.FullName);
				throw new InvalidOperationException(message);
			}
		}
 public override bool CanConvert(Type objectType)
 {
     return objectType.Is<IJsonObject>();
 }