Ejemplo n.º 1
0
        public static Boolean IsType(this Sitecore.Mvc.Presentation.RenderingModel model, params Type[] types)
        {
            var isValid = false;

            // Get Type from regular objects and Castle Proxy Objects
            var modelType = ProxyUtil.GetUnproxiedType(model);

            foreach (var type in types)
            {
                if (type.IsAssignableFrom(modelType))
                {
                    isValid = true;
                    break;
                }
            }

            if (!isValid)
            {
                Request.Items.Set <String>(
                    ErrMsgKey,
                    String.Format(
                        "This rendering requires type {0}. (attempted type {1})",
                        String.Join(", ", types.Select(t => t.Name).ToList()),
                        model.GetType().ToString()
                        )
                    );
            }


            return(isValid);
        }
        protected override IEnumerable <ConsumerExecutorDescriptor> FindConsumersFromInterfaceTypes(IServiceProvider provider)
        {
            var executorDescriptorList = new List <ConsumerExecutorDescriptor>();

            using (var scoped = provider.CreateScope())
            {
                var scopedProvider   = scoped.ServiceProvider;
                var consumerServices = scopedProvider.GetServices <ICapSubscribe>();
                foreach (var service in consumerServices)
                {
                    var serviceType = service.GetType();
                    // Castle dynamic proxy...
                    TypeInfo typeInfo = ProxyServices.IsDynamicProxy(serviceType) ? ProxyUtil.GetUnproxiedType(service).GetTypeInfo()
                        : serviceType.GetTypeInfo();

                    if (!typeof(ICapSubscribe).GetTypeInfo().IsAssignableFrom(typeInfo))
                    {
                        continue;
                    }

                    executorDescriptorList.AddRange(GetTopicAttributesDescription(typeInfo));
                }

                return(executorDescriptorList);
            }
        }
        public static int Compare(object item1, object item2)
        {
            int order1, order2;
            var attrib2 = Cache.GetOrAdd(ProxyUtil.GetUnproxiedType(item2), Get);

            if (attrib2 != null)
            {
                order2 = attrib2.Order;
            }
            else
            {
                return(-1);
            }

            var attrib1 = Cache.GetOrAdd(ProxyUtil.GetUnproxiedType(item1), Get);

            if (attrib1 != null)
            {
                order1 = attrib1.Order;
            }
            else
            {
                return(1);
            }

            return(order1 - order2);
        }
Ejemplo n.º 4
0
        public override bool ReleaseCore(Burden burden)
        {
            var genericType = ProxyUtil.GetUnproxiedType(burden.Instance);
            var handler     = type2SubHandler.GetOrThrow(genericType);

            return(handler.Release(burden));
        }
Ejemplo n.º 5
0
            public List <Type> GetEvents(object instance)
            {
                List <Type> result;

                _typesToEvents.TryGetValue(ProxyUtil.GetUnproxiedType(instance), out result);
                return(result);
            }
Ejemplo n.º 6
0
        public override bool ReleaseCore(Burden burden)
        {
            var genericType = ProxyUtil.GetUnproxiedType(burden.Instance);

            var handler = GetSubHandler(CreationContext.CreateEmpty(), genericType);

            return(handler.Release(burden));
        }
Ejemplo n.º 7
0
        protected IValidator GetValidator <T, R>() where T : IValidator <R>
        {
            var mediatR = _container.GetChildContainer("Improving.MediatR");

            using (mediatR.BeginScope())
            {
                return(mediatR.ResolveAll <IValidator <R> >()
                       .First(v => ProxyUtil.GetUnproxiedType(v).IsAssignableFrom(typeof(T))));
            }
        }
Ejemplo n.º 8
0
        private IEnumerable <Type> GetUnproxiedTypes(object instance)
        {
            var type = ProxyUtil.GetUnproxiedType(instance);

            if (ProxyUtil.IsProxyType(type))
            {
                return(type.GetInterfaces());
            }

            return(new[] { type });
        }
Ejemplo n.º 9
0
        public void GetMethodsTest()
        {
            var demo    = _container.Resolve <DemoClass>();
            var methods = ProxyUtil.GetUnproxiedType(demo)
                          .GetMethods(BindingFlags.Public | BindingFlags.Instance)
                          .Where(method => method.DeclaringType != typeof(object))
                          .ToArray();

            Assert.Single(methods);
            Assert.Equal(nameof(DemoClass.HelloWorld), methods.Single().Name);
        }
Ejemplo n.º 10
0
        private void Validate()
        {
            var currentUrl = this.webDriver.Url;

            if (PageUtil.IsValid(ProxyUtil.GetUnproxiedType(this), currentUrl))
            {
                return;
            }

            var validators = this.GetType().GetCustomAttributes(true).OfType <IPageUrlValidator>().ToArray();
            var message    = validators.Select(x => x.GetErrorMessage(currentUrl)).Join(" Or ");

            throw new PageValidationException(message, this);
        }
Ejemplo n.º 11
0
        internal void Configure(object executable)
        {
            var targettype = ProxyUtil.GetUnproxiedType(executable);

            Executable = new Executable().LoadFromObject(targettype);
            if (executable is IExecutableConfigurator execonfig)
            {
                Executable.ConfigureWith(execonfig);
            }
            if (executable is IExecutionConfigurator executionconfig)
            {
                Executable.ConfigureWith(executionconfig);
            }
        }
        public Task <TResponse> Handle(TRequest request)
        {
            var index = -1;
            Func <TRequest, Task <TResponse> > next = null;

            next = req =>
            {
                ++index;
                return(index < _middleware.Length
                     ? _middleware[index].Apply(request, next)
                     : _inner.Handle(request));
            };

            Env.Use(new PipelineContext(ProxyUtil.GetUnproxiedType(_inner)));

            return(next(request));
        }
Ejemplo n.º 13
0
 public void DynamicProxyWithoutInterfaceTest()
 {
     try
     {
         var demo = _container.Resolve <DemoClassWithoutInterface>();
         Assert.Empty(LoggingInterceptor.Calls);
         demo.HelloWorld();
         Assert.Single(LoggingInterceptor.Calls);
         Assert.Equal(nameof(DemoClassWithoutInterface.HelloWorld), LoggingInterceptor.Calls.Single());
         var type = demo.GetType();
         Assert.NotEqual(typeof(DemoClassWithoutInterface), type);
         Assert.Equal(typeof(DemoClassWithoutInterface), ProxyUtil.GetUnproxiedType(demo));
     }
     finally
     {
         LoggingInterceptor.Calls.Clear();
     }
 }
Ejemplo n.º 14
0
        public void Intercept(IInvocation invocation)
        {
            ContentTypeBase docType = (ContentTypeBase)invocation.InvocationTarget;

            string propertyName = invocation.Method.GetPropertyName();

            if (invocation.Method.IsGetter())
            {
                if (docType[propertyName] == null)
                {
                    // Type typeDocType = DocumentTypeManager.GetDocumentTypeType(docType.Source.NodeTypeAlias);
                    var typeDocType = ProxyUtil.GetUnproxiedType(docType);

                    PropertyInfo propInfo = typeDocType.GetProperty(propertyName);

                    object value = null;
                    try
                    {
                        value = ContentHelper.GetPropertyValueOrMixin(docType, propInfo);
                        docType[propertyName] = value;
                    }
                    catch (Exception exc)
                    {
                        throw new Exception(string.Format("Cannot set the value of a document type property {0}.{1} (document type: {2}) to value: '{3}' (value type: {4}). Error: {5}",
                                                          typeDocType.Name, propInfo.Name, propInfo.PropertyType.FullName,
                                                          value, value != null ? value.GetType().FullName : "", exc.Message));
                    }
                }

                invocation.ReturnValue = docType[propertyName];
                if (invocation.ReturnValue == null && invocation.Method.ReturnType == typeof(bool))
                {
                    invocation.ReturnValue = false;
                }
            }
            else
            {
                docType[propertyName] = invocation.Arguments[0];
            }
        }
    private void Validate()
    {
        var type = ProxyUtil.GetUnproxiedType(this);

        // No public constructors.
        if (type.GetConstructors().Length != 0)
        {
            throw new InvalidOperationException(
                      "Public constructors not supported in derived types."
                      );
        }
        // No non-virtual properties.
        foreach (var property in type.GetProperties())
        {
            // We're only interested in getters.
            var method = property.GetGetMethod();
            if (method != null && !method.IsVirtual)
            {
                throw new InvalidOperationException(
                          "Only virtual properties are supported."
                          );
            }
        }
    }
Ejemplo n.º 16
0
 /// <summary>
 /// Default constructor.
 /// </summary>
 /// <param name="entry">The object instance.</param>
 public StoreKey(EntityEntry entry)
 {
     ModelType  = ProxyUtil.GetUnproxiedType(entry.Entity).Name;
     EntityKeys = entry.GetKeyValues();
 }
 /// <summary>
 /// Checks if the change tracker is already tracking the object instance.
 /// </summary>
 /// <typeparam name="T">The type of the object.</typeparam>
 /// <param name="ctx">The database context instance.</param>
 /// <param name="entity">The entity instance.</param>
 /// <param name="checkTemp">By default will only check object with already applied values.</param>
 /// <returns>If the object is already being tracked returns true.</returns>
 public bool IsTracking <T>(DbContext ctx, T entity, bool checkTemp = false) where T : class, ITrackableEntity
 {
     return(IsTracking(new StoreKey(ProxyUtil.GetUnproxiedType(entity).Name, ctx.GetKeyValues <T>(entity))));
 }
 /// <summary>
 /// Get Un Prox Type if ths instance is proxy
 /// </summary>
 /// <returns></returns>
 public Type GetUnProxyType()
 {
     return(ProxyUtil.GetUnproxiedType(this));
 }
Ejemplo n.º 19
0
        /// <summary>
        /// 动态注入打了value标签的值
        /// </summary>
        /// <typeparam name="TReflectionActivatorData"></typeparam>
        /// <typeparam name="TSingleRegistrationStyle"></typeparam>
        /// <param name="component"></param>
        /// <param name="registrar"></param>
        protected virtual void RegisterComponentValues <TReflectionActivatorData, TSingleRegistrationStyle>(ComponentModel component,
                                                                                                            IRegistrationBuilder <object, TReflectionActivatorData, TSingleRegistrationStyle> registrar)
            where TReflectionActivatorData : ReflectionActivatorData
            where TSingleRegistrationStyle : SingleRegistrationStyle
        {
            if (component == null)
            {
                throw new ArgumentNullException(nameof(component));
            }

            if (registrar == null)
            {
                throw new ArgumentNullException(nameof(registrar));
            }

            component.ValuePropertyInfoList = (from p in component.CurrentType.GetAllProperties()
                                               let va = p.GetCustomAttribute <Value>()
                                                        where va != null
                                                        select new Tuple <PropertyInfo, Value>(p, va)).ToList();

            component.ValueFieldInfoList = (from p in component.CurrentType.GetAllFields()
                                            let va = p.GetCustomAttribute <Value>()
                                                     where va != null
                                                     select new Tuple <FieldInfo, Value>(p, va)).ToList();

            if (!component.ValueFieldInfoList.Any() && !component.ValuePropertyInfoList.Any())
            {
                return;
            }

            //创建对象之后调用
            registrar.OnActivated(e =>
            {
                var instance = e.Instance;
                if (instance == null)
                {
                    return;
                }
                Type instanceType   = instance.GetType();
                object RealInstance = instance;
                if (ProxyUtil.IsProxy(instance))
                {
                    RealInstance = ProxyUtil.GetUnproxiedInstance(instance);
                    instanceType = ProxyUtil.GetUnproxiedType(instance);
                }

                if (RealInstance == null)
                {
                    return;
                }
                var componentModelCacheSingleton = e.Context.Resolve <ComponentModelCacheSingleton>();
                if (!componentModelCacheSingleton.ComponentModelCache.TryGetValue(instanceType, out ComponentModel model))
                {
                    return;
                }
                foreach (var field in model.ValueFieldInfoList)
                {
                    var value = field.Item2.ResolveFiled(field.Item1, e.Context);
                    if (value == null)
                    {
                        continue;
                    }
                    try
                    {
                        field.Item1.GetReflector().SetValue(RealInstance, value);
                    }
                    catch (Exception ex)
                    {
                        throw new DependencyResolutionException($"Value set error,can not resolve class type:{instanceType.FullName} =====>" +
                                                                $" ,fail resolve field value:{field.Item1.Name} "
                                                                + (!string.IsNullOrEmpty(field.Item2.value) ? $",with value:[{field.Item2.value}]" : ""), ex);
                    }
                }

                foreach (var property in model.ValuePropertyInfoList)
                {
                    var value = property.Item2.ResolveProperty(property.Item1, e.Context);
                    if (value == null)
                    {
                        continue;
                    }
                    try
                    {
                        property.Item1.GetReflector().SetValue(RealInstance, value);
                    }
                    catch (Exception ex)
                    {
                        throw new DependencyResolutionException($"Value set error,can not resolve class type:{instanceType.FullName} =====>" +
                                                                $" ,fail resolve property value:{property.Item1.Name} "
                                                                + (!string.IsNullOrEmpty(property.Item2.value) ? $",with value:[{property.Item2.value}]" : ""),
                                                                ex);
                    }
                }
            });
        }
Ejemplo n.º 20
0
        /// <summary>
        /// 属性注入
        /// </summary>
        /// <param name="context">容器</param>
        /// <param name="Parameters">参数</param>
        /// <param name="instance">实例</param>
        /// <param name="allowCircle">是否可以循环</param>
        private void DoAutoWired(IComponentContext context, IEnumerable <Parameter> Parameters, object instance, bool allowCircle)
        {
            if (instance == null)
            {
                return;
            }
            Type   instanceType = instance.GetType();
            object RealInstance = instance;

            if (ProxyUtil.IsProxy(instance))
            {
                RealInstance = ProxyUtil.GetUnproxiedInstance(instance);
                instanceType = ProxyUtil.GetUnproxiedType(instance);
            }

            if (RealInstance == null)
            {
                return;
            }
            var componentModelCacheSingleton = context.Resolve <ComponentModelCacheSingleton>();

            if (!componentModelCacheSingleton.ComponentModelCache.TryGetValue(instanceType, out ComponentModel model))
            {
                return;
            }
            //字段注入
            foreach (var field in model.AutowiredFieldInfoList)
            {
                // ReSharper disable once PossibleMultipleEnumeration
                var obj = field.Item2.ResolveField(field.Item1, context, Parameters, RealInstance, allowCircle);
                if (obj == null)
                {
                    if (field.Item2.Required)
                    {
                        throw new DependencyResolutionException(
                                  $"Autowire error,can not resolve class type:{instanceType.FullName},field name:{field.Item1.Name} "
                                  + (!string.IsNullOrEmpty(field.Item2.Name) ? $",with key:{field.Item2.Name}" : ""));
                    }
                    continue;
                }
                try
                {
                    field.Item1.GetReflector().SetValue(RealInstance, obj);
                }
                catch (Exception ex)
                {
                    throw new DependencyResolutionException(
                              $"Autowire error,can not resolve class type:{instanceType.FullName},field name:{field.Item1.Name} "
                              + (!string.IsNullOrEmpty(field.Item2.Name) ? $",with key:{field.Item2.Name}" : ""), ex);
                }
            }
            //属性注入
            foreach (var property in model.AutowiredPropertyInfoList)
            {
                // ReSharper disable once PossibleMultipleEnumeration
                var obj = property.Item2.ResolveProperty(property.Item1, context, Parameters, RealInstance, allowCircle);
                if (obj == null)
                {
                    if (property.Item2.Required)
                    {
                        throw new DependencyResolutionException(
                                  $"Autowire error,can not resolve class type:{instanceType.FullName},property name:{property.Item1.Name} "
                                  + (!string.IsNullOrEmpty(property.Item2.Name) ? $",with key:{property.Item2.Name}" : ""));
                    }
                    continue;
                }
                try
                {
                    property.Item1.GetReflector().SetValue(RealInstance, obj);
                }
                catch (Exception ex)
                {
                    throw new DependencyResolutionException(
                              $"Autowire error,can not resolve class type:{instanceType.FullName},property name:{property.Item1.Name} "
                              + (!string.IsNullOrEmpty(property.Item2.Name) ? $",with key:{property.Item2.Name}" : ""), ex);
                }
            }
        }
Ejemplo n.º 21
0
        private object[] GetSagasFor(object message)
        {
            var instances = new List <object>();

            Type orchestratesType = reflection.GetGenericTypeOf(typeof(Orchestrates <>), message);
            Type initiatedByType  = reflection.GetGenericTypeOf(typeof(InitiatedBy <>), message);

            var handlers = serviceLocator.GetAllHandlersFor(orchestratesType)
                           .Union(serviceLocator.GetAllHandlersFor(initiatedByType));

            foreach (IHandler sagaHandler in handlers)
            {
                Type sagaType = sagaHandler.Implementation;

                //first try to execute any saga finders.
                Type sagaFinderType     = reflection.GetGenericTypeOf(typeof(ISagaFinder <,>), sagaType, ProxyUtil.GetUnproxiedType(message));
                var  sagaFinderHandlers = serviceLocator.GetAllHandlersFor(sagaFinderType);
                foreach (var sagaFinderHandler in sagaFinderHandlers)
                {
                    try
                    {
                        var sagaFinder = sagaFinderHandler.Resolve();
                        var saga       = reflection.InvokeSagaFinderFindBy(sagaFinder, message);
                        if (saga != null)
                        {
                            instances.Add(saga);
                        }
                    }
                    finally
                    {
                        serviceLocator.Release(sagaFinderHandler);
                    }
                }

                //we will try to use an ISagaMessage's Correlation id next.
                var sagaMessage = message as ISagaMessage;
                if (sagaMessage == null)
                {
                    continue;
                }

                Type sagaPersisterType = reflection.GetGenericTypeOf(typeof(ISagaPersister <>),
                                                                     sagaType);

                object sagaPersister = serviceLocator.Resolve(sagaPersisterType);
                try
                {
                    object sagas = reflection.InvokeSagaPersisterGet(sagaPersister, sagaMessage.CorrelationId);
                    if (sagas == null)
                    {
                        continue;
                    }
                    instances.Add(sagas);
                }
                finally
                {
                    serviceLocator.Release(sagaPersister);
                }
            }
            return(instances.ToArray());
        }
Ejemplo n.º 22
0
 /// <summary>
 /// Returns the type of the dynamic proxy target object if this is a proxied object, otherwise returns the type of the given object.
 /// </summary>
 public static Type GetUnproxiedType(object obj)
 {
     return(ProxyUtil.GetUnproxiedType(obj));
 }
 /// <summary>
 /// Get the object type without the proxy.
 /// </summary>
 /// <param name="type">The object type.</param>
 /// <returns>Returns the original type.</returns>
 public static Type GetUnproxiedType(this Type type)
 => ProxyUtil.IsProxyType(type) ? ProxyUtil.GetUnproxiedType(type) : type;
Ejemplo n.º 24
0
 public static Type GetUnderlyingType(object value)
 {
     return(ProxyUtil.GetUnproxiedType(value));
 }
Ejemplo n.º 25
0
 public ICollection <Type> GetGenericTypesOfWithBaseTypes(Type type, object msg)
 {
     return(GetGenericTypesOfWithBaseTypes(type, ProxyUtil.GetUnproxiedType(msg)));
 }
Ejemplo n.º 26
0
 public Type GetGenericTypeOf(Type type, object msg)
 {
     return(GetGenericTypeOf(type, ProxyUtil.GetUnproxiedType(msg)));
 }
 public static bool IsDefined(object instance)
 {
     return(Cache.GetOrAdd(ProxyUtil.GetUnproxiedType(instance),
                           t => t.IsDefined(typeof(StopOnFailureAttribute), false)));
 }
Ejemplo n.º 28
0
 private static bool IsUiComponent(object target)
 {
     return(ProxyUtil.GetUnproxiedType(target)
            .Namespace.StartsWith(typeof(ViewModelBase).Namespace));
 }
 /// <summary>
 /// Get the object type without the proxy.
 /// </summary>
 /// <param name="entity">The entity instance.</param>
 /// <returns>Returns the original type of the entity.</returns>
 public static Type GetUnproxiedType(this object entity)
 => ProxyUtil.IsProxy(entity) ? ProxyUtil.GetUnproxiedType(entity) : entity.GetType();