Пример #1
0
        public void Activate_UsesPassedInViewDataDictionaryInstance_IfPassedInTypeMatches()
        {
            // Arrange
            var typeActivator   = new TypeActivator();
            var activator       = new RazorPageActivator(typeActivator);
            var instance        = new TestRazorPage();
            var myService       = new MyService();
            var helper          = Mock.Of <IHtmlHelper <object> >();
            var serviceProvider = new Mock <IServiceProvider>();

            serviceProvider.Setup(p => p.GetService(typeof(MyService)))
            .Returns(myService);
            serviceProvider.Setup(p => p.GetService(typeof(IHtmlHelper <object>)))
            .Returns(helper);
            var httpContext = new Mock <HttpContext>();

            httpContext.SetupGet(c => c.RequestServices)
            .Returns(serviceProvider.Object);
            var routeContext  = new RouteContext(httpContext.Object);
            var actionContext = new ActionContext(routeContext, new ActionDescriptor());
            var viewData      = new ViewDataDictionary <MyModel>(Mock.Of <IModelMetadataProvider>())
            {
                Model = new MyModel()
            };
            var viewContext = new ViewContext(actionContext,
                                              Mock.Of <IView>(),
                                              viewData,
                                              TextWriter.Null);

            // Act
            activator.Activate(instance, viewContext);

            // Assert
            Assert.Same(viewData, viewContext.ViewData);
        }
Пример #2
0
        public static ISelectListDataSource GetDataSource(this ModelMetadata modelMetadata)
        {
            ISelectListDataSource dataSource = null;

            if (modelMetadata is BzwayModelMetadata)
            {
                var dataSourceAttribute = ((BzwayModelMetadata)modelMetadata).DataSourceAttribute;
                if (dataSourceAttribute != null)
                {
                    dataSource = (ISelectListDataSource)TypeActivator.CreateInstance(dataSourceAttribute.DataSourceType);
                }
                if (dataSource == null)
                {
                    dataSource = ((BzwayModelMetadata)modelMetadata).DataSource;
                }
            }
            else
            {
            }
            if (dataSource == null)
            {
                return(new EmptySelectListDataSource());
            }
            else
            {
                return(dataSource);
            }
        }
Пример #3
0
        /// <summary>
        /// Returns the handler instance from the dependency resolver if there is one registered
        /// else returns the activator that calls the default constructor for the give handlerType.
        /// </summary>
        /// <param name="request">
        /// The request.
        /// </param>
        /// <param name="descriptor">
        /// The handler descriptor.
        /// </param>
        /// <param name="activator">
        /// The activator.
        /// </param>
        /// <returns>
        /// The handler.
        /// </returns>
        private THandler GetInstanceOrActivator(HandlerRequest request, HandlerDescriptor descriptor, out Func <THandler> activator)
        {
            Contract.Requires(request != null);
            Contract.Requires(descriptor != null);

            // If dependency resolver returns handler object then use it.
            THandler instance = (THandler)request.GetDependencyScope().GetService(descriptor.HandlerType);

            if (instance != null)
            {
                activator = null;
                return(instance);
            }

            switch (descriptor.Lifetime)
            {
            case HandlerLifetime.Singleton:
                activator = this.CreateSingletonActivator(descriptor.HandlerType);
                return(null);

            case HandlerLifetime.PerRequest:
                activator = CreatePerRequestActivator(request, descriptor);
                return(null);

            case HandlerLifetime.Transient:
                activator = TypeActivator.Create <THandler>(descriptor.HandlerType);
                return(null);

            default:
                throw Error.InvalidEnumArgument("descriptor", (int)descriptor.Lifetime, typeof(HandlerLifetime));
            }
        }
Пример #4
0
        internal static IHandlerResultConverter GetResultConverter(Type type)
        {
            if (type != null && type.IsGenericParameter)
            {
                // This can happen if somebody declares an action method as:
                // public T Get<T>() { }
                throw Error.InvalidOperation(Resources.CommandHandlerDescriptor_NoConverterForGenericParamterTypeExists, type);
            }

            if (type == null || type == typeof(void))
            {
                return(VoidResultConverter);
            }

            if (typeof(HandlerResponse).IsAssignableFrom(type))
            {
                return(ResponseMessageResultConverter);
            }

            if (typeof(ICommandHandlerResult).IsAssignableFrom(type))
            {
                return(null);
            }

            Type valueConverterType = typeof(ValueResultConverter <>).MakeGenericType(type);

            return(TypeActivator.Create <IHandlerResultConverter>(valueConverterType).Invoke());
        }
Пример #5
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ViewModelDialog{TEntity}"/> class.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="commonServices">The common services.</param>
        /// <param name="logger">The logger factory.</param>
        /// <param name="automaticValidation"></param>
        protected ViewModelDialog(
            IContext context,
            IBaseCommonServices commonServices,
            ILogger logger,
            bool automaticValidation = false)
            : base(context, commonServices, logger, automaticValidation)
        {
            Validator = new Action <IObservableClass>(arg =>
            {
                if (arg is ViewModelDialog <TEntity> vm &&
                    vm.SelectedItem is IObservableClass selectedItem)
                {
                    if (!selectedItem.Validate())
                    {
                        foreach (var error in selectedItem.Errors)
                        {
                            vm.Properties[nameof(vm.SelectedItem)].Errors.Add(error);
                        }
                    }
                }
            });

            SelectedItem = TypeActivator.CreateInstance <TEntity>();
            IsNew        = true;

            Submit_Command = new Command <TEntity>(async e => await SubmitAsync(e));
        }
        public void ForeverFrameTransportDisablesRequestBuffering()
        {
            var qs = new Dictionary <string, string> {
                { "frameId", "1" }
            };
            var context = new TestContext("/", qs);
            var sp      = ServiceProviderHelper.CreateServiceProvider();
            var ta      = new TypeActivator();

            var ms        = new MemoryStream();
            var buffering = new Mock <IHttpBufferingFeature>();

            context.MockHttpContext.Setup(m => m.GetFeature <IHttpBufferingFeature>())
            .Returns(buffering.Object);
            context.MockResponse.SetupAllProperties();
            context.MockResponse.Setup(m => m.Body).Returns(ms);

            var fft = ta.CreateInstance <ForeverFrameTransport>(sp, context.MockHttpContext.Object);

            fft.ConnectionId = "1";
            var connection = new Mock <ITransportConnection>();

            fft.InitializeResponse(connection.Object).Wait();

            buffering.Verify(m => m.DisableRequestBuffering(), Times.Once());
        }
Пример #7
0
        public void Activate_DeterminesModelTypeFromProperty()
        {
            // Arrange
            var typeActivator   = new TypeActivator();
            var activator       = new RazorPageActivator(typeActivator);
            var instance        = new DoesNotDeriveFromRazorPageOfTButHasModelProperty();
            var myService       = new MyService();
            var helper          = Mock.Of <IHtmlHelper <object> >();
            var serviceProvider = new Mock <IServiceProvider>();

            serviceProvider.Setup(p => p.GetService(typeof(MyService)))
            .Returns(myService);
            serviceProvider.Setup(p => p.GetService(typeof(IHtmlHelper <object>)))
            .Returns(helper);
            var httpContext = new Mock <HttpContext>();

            httpContext.SetupGet(c => c.RequestServices)
            .Returns(serviceProvider.Object);
            var routeContext  = new RouteContext(httpContext.Object);
            var actionContext = new ActionContext(routeContext, new ActionDescriptor());
            var viewData      = new ViewDataDictionary(Mock.Of <IModelMetadataProvider>());
            var viewContext   = new ViewContext(actionContext,
                                                Mock.Of <IView>(),
                                                viewData,
                                                TextWriter.Null);

            // Act
            activator.Activate(instance, viewContext);

            // Assert
            Assert.IsType <ViewDataDictionary <string> >(viewContext.ViewData);
        }
Пример #8
0
        public void ViewEngine_ReturnsInstantiatedListOfViewEngines()
        {
            // Arrange
            var service = Mock.Of <ITestService>();
            var valueProviderFactory = Mock.Of <IValueProviderFactory>();
            var type            = typeof(TestValueProviderFactory);
            var typeActivator   = new TypeActivator();
            var serviceProvider = new Mock <IServiceProvider>();

            serviceProvider.Setup(p => p.GetService(typeof(ITestService)))
            .Returns(service);
            var options = new MvcOptions();

            options.ValueProviderFactories.Add(valueProviderFactory);
            options.ValueProviderFactories.Add(type);
            var accessor = new Mock <IOptions <MvcOptions> >();

            accessor.SetupGet(a => a.Options)
            .Returns(options);
            var provider = new DefaultValueProviderFactoryProvider(accessor.Object,
                                                                   typeActivator,
                                                                   serviceProvider.Object);

            // Act
            var result = provider.ValueProviderFactories;

            // Assert
            Assert.Equal(2, result.Count);
            Assert.Same(valueProviderFactory, result[0]);
            var testValueProviderFactory = Assert.IsType <TestValueProviderFactory>(result[1]);

            Assert.Same(service, testValueProviderFactory.Service);
        }
Пример #9
0
        public void EnsureHubThrowsWhenCantResolve()
        {
            var sp         = ServiceProviderHelper.CreateServiceProvider();
            var ta         = new TypeActivator();
            var hubManager = ta.CreateInstance <DefaultHubManager>(sp);

            Assert.Throws <InvalidOperationException>(() => hubManager.EnsureHub("__ELLO__"));
        }
 private void OnSerialized(StreamingContext context)
 {
     // Always ensure CommerceDataSource is not null, otherwise we are not able to deserialize it in data contract
     if (CommerceDataSource == null)
     {
         CommerceDataSource = TypeActivator.CreateInstance(Type.GetType(CommerceDataSourceType, true)) as ICommerceDataSource;
     }
 }
        private ConstructorDescriptor ActivatorConstructorDescriptor()
        {
            var _constructorInfos   = DescriptorType.GetConstructors();
            var _resolveConstructor = (ConstructorInfo)null;

            foreach (var _constructorInfo in _constructorInfos)
            {
                if (Attribute.IsDefined(_constructorInfo, typeof(ResolveConstructorAttribute)))
                {
                    if (_constructorInfo.IsStatic)
                    {
                        throw new ResolveResourceException(string.Format(RESOLVECONST_MUSTBE_INSTANCE, DescriptorType.FullName), DescriptorType);
                    }
                    if (_resolveConstructor != null)
                    {
                        throw new ResolveResourceException(string.Format(RESOLVECONST_ONLYONCE, DescriptorType.FullName), DescriptorType);
                    }
                    if (DescriptorType.IsAbstract)
                    {
                        throw new ResolveResourceException(string.Format(RESOLVECONST_CANNOTBE_ABSTRACT, DescriptorType.FullName), DescriptorType);
                    }

                    _resolveConstructor = _constructorInfo;
                }
            }

            // else we try to get a public and parameter-less constructor
            if (_resolveConstructor == null)
            {
                _resolveConstructor = DescriptorType.GetConstructor(BindingFlags.Public | BindingFlags.Instance, null, EMPTY_PARAMETERS, null);
                if (_resolveConstructor == null)
                {
                    _resolveConstructor = DescriptorType.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, EMPTY_PARAMETERS, null);
                }
                if (_resolveConstructor == null)
                {
                    throw new ResolveResourceException(string.Format(BUILD_MUSTHAVE_DEFAULTCONST, DescriptorType.FullName), DescriptorType);
                }
            }

            var _constructor = new ConstructorDescriptor();

            _constructor.Constructor = _resolveConstructor;

            var _parameters = _resolveConstructor.GetParameters();

            if (_parameters.Length == 0)
            {
                _constructor.ConstructorDelegate  = TypeActivator.CreateConstructorDelegate(_resolveConstructor);
                _constructor.ParameterDescriptors = Enumerable.Empty <ParameterDescriptor>();
            }
            else
            {
                _constructor.ConstructorParameterDelegate = TypeActivator.CreateConstructorParametersDelegate(_resolveConstructor);
                _constructor.ParameterDescriptors         = ResolveConstructorParametersDescriptor(_parameters);
            }
            return(_constructor);
        }
Пример #12
0
        private static Func <THandler> CreateDelegatingActivator(Type handlerType)
        {
            Contract.Requires(handlerType != null);

            Func <THandler> activator = TypeActivator.Create <THandler>(handlerType);
            THandler        instance  = activator();

            return(() => instance);
        }
        public void ResolveInvalidHub()
        {
            var sp            = ServiceProviderHelper.CreateServiceProvider();
            var ta            = new TypeActivator();
            var hubManager    = ta.CreateInstance <DefaultHubManager>(sp);
            var hubDescriptor = hubManager.ResolveHub("____CoreTestHub____");

            Assert.Null(hubDescriptor);
        }
        public void GetInValidHub()
        {
            var sp            = ServiceProviderHelper.CreateServiceProvider();
            var ta            = new TypeActivator();
            var hubManager    = ta.CreateInstance <DefaultHubManager>(sp);
            var hubDescriptor = hubManager.GetHub("__ELLO__");

            Assert.Null(hubDescriptor);
        }
Пример #15
0
        protected override async Task GenerateCode()
        {
            var destinationPath = Path.Combine(ApplicationEnvironment.ApplicationBasePath, Constants.ViewsFolderName,
                                               Constants.SharedViewsFolderName);

            await CopyFolderContentsRecursive(destinationPath, TemplateFolders.First());

            var staticFilesInstaller = TypeActivator.CreateInstance <StaticFilesDependencyInstaller>(ServiceProvider);
            await staticFilesInstaller.Execute();
        }
        public void GetValidHubMethodsWithPredicate()
        {
            var sp                = ServiceProviderHelper.CreateServiceProvider();
            var ta                = new TypeActivator();
            var hubManager        = ta.CreateInstance <DefaultHubManager>(sp);
            var methodDescriptors = hubManager.GetHubMethods("CoreTestHubWithMethod", descriptor => descriptor.Name == "AddNumbers");

            Assert.NotNull(methodDescriptors);
            Assert.Equal(methodDescriptors.First().Name, "AddNumbers");
        }
        public void GetValidHub()
        {
            var sp            = ServiceProviderHelper.CreateServiceProvider();
            var ta            = new TypeActivator();
            var hubManager    = ta.CreateInstance <DefaultHubManager>(sp);
            var hubDescriptor = hubManager.GetHub("CoreTestHub");

            Assert.NotNull(hubDescriptor);
            Assert.False(hubDescriptor.NameSpecified);
        }
        public void ResolveHubsIsNotEmpty()
        {
            var sp            = ServiceProviderHelper.CreateServiceProvider();
            var ta            = new TypeActivator();
            var hubManager    = ta.CreateInstance <DefaultHubManager>(sp);
            var hubDescriptor = hubManager.ResolveHubs();

            Assert.NotNull(hubDescriptor);
            Assert.NotEmpty(hubDescriptor);
        }
        public void CreateInstanceWithArgs3()
        {
            var arr      = new byte[20];
            var expected = new ArraySegment <byte>(arr, 10, 10);
            var actual   = (ArraySegment <byte>)TypeActivator.CreateInstance(typeof(ArraySegment <byte>), arr, 10, 10);

            Assert.Equal(expected.Array, actual.Array);
            Assert.Equal(expected.Offset, actual.Offset);
            Assert.Equal(expected.Count, actual.Count);
        }
        public void GetHubMethodFromInvalidHub()
        {
            var sp         = ServiceProviderHelper.CreateServiceProvider();
            var ta         = new TypeActivator();
            var hubManager = ta.CreateInstance <DefaultHubManager>(sp);
            // There is no ________________CoreTestHubWithMethod________________ name
            var methodDescriptor = hubManager.GetHubMethod("________________CoreTestHubWithMethod________________", "AddNumbers", new IJsonValue[] { null, null });

            Assert.Null(methodDescriptor);
        }
        public void GetInvalidHubMethod()
        {
            var sp         = ServiceProviderHelper.CreateServiceProvider();
            var ta         = new TypeActivator();
            var hubManager = ta.CreateInstance <DefaultHubManager>(sp);
            // The AddNumbers method has 2 parameters, so should not find the method
            var methodDescriptor = hubManager.GetHubMethod("CoreTestHubWithMethod", "AddNumbers", null);

            Assert.Null(methodDescriptor);
        }
        public void GetValidHubsWithValidPredicate()
        {
            var sp             = ServiceProviderHelper.CreateServiceProvider();
            var ta             = new TypeActivator();
            var hubManager     = ta.CreateInstance <DefaultHubManager>(sp);
            var hubDescriptors = hubManager.GetHubs(descriptor => descriptor.Name == "CoreTestHub");

            Assert.NotNull(hubDescriptors);
            Assert.Equal(hubDescriptors.First().Name, "CoreTestHub");
        }
Пример #23
0
        public void ShouldNotResolveHubByTypeNameIfAttributeExists()
        {
            var           sp          = ServiceProviderHelper.CreateServiceProvider();
            var           ta          = new TypeActivator();
            var           hubResolver = ta.CreateInstance <ReflectedHubDescriptorProvider>(sp);
            HubDescriptor hub;

            hubResolver.TryGetHub("HubWithAttribute", out hub);

            Assert.Null(hub);
        }
Пример #24
0
        public void ShouldIgnoreCaseWhenDiscoveringHubsUsingManager()
        {
            var sp      = ServiceProviderHelper.CreateServiceProvider();
            var ta      = new TypeActivator();
            var manager = ta.CreateInstance <DefaultHubManager>(sp);
            var hub     = manager.GetHub("hubwithoutattribute");

            Assert.NotNull(hub);
            Assert.Equal(hub.Name, "HubWithoutAttribute");
            Assert.Equal(hub.NameSpecified, false);
        }
Пример #25
0
        private Rule DeserializeAlways(EventSlot slot, XElement element)
        {
            var rule = (AlwaysRule)TypeActivator.CreateInstance(typeof(AlwaysRule));

            foreach (var activityElement in element.Elements("activity"))
            {
                rule.Activities.Add(DeserializeActivity(activityElement));
            }

            return(rule);
        }
Пример #26
0
        public PriceCalculator()
        {
            var modules = new List <IPriceCalculationModule>();

            foreach (var type in PriceCalculationModules.Modules)
            {
                modules.Add((IPriceCalculationModule)TypeActivator.CreateInstance(type));
            }

            _modules = modules;
        }
        public override object ResolveValue(RuleParameter param, object dataContext)
        {
            var referenceResolver = TypeActivator.CreateInstance(_referenceResolverType) as IReferenceResolver;

            if (referenceResolver == null)
            {
                throw new InvalidOperationException("Cannot resolve reference resolver type: " + _referenceResolverType + ".");
            }

            return(referenceResolver.Resolve(_referencingType, dataContext));
        }
Пример #28
0
        public static void TestSet17_Method1()
        {
            //TestSet7
            var container = new Container();

            container.RegisterType <Type>();
            var typeActivator = new TypeActivator();
            var runtimeType   = new RuntimeType(typeActivator, new InjectionAttribute("Build.Tests.TestSet17.Type"), typeof(Type), true);

            runtimeType.SetRuntimeInstance(RuntimeInstance.CreateInstance);
            Assert.Throws <TypeInstantiationException>(() => runtimeType.CreateInstance(new object[] { "Build.Tests.TestSet17.Type" }));
        }
Пример #29
0
        public static void Method1_3()
        {
            //TestSet7
            var container = new Container();

            container.RegisterType <Type>();
            var typeActivator      = new TypeActivator();
            var injectionAttribute = new InjectionAttribute("TestSet17.Type");
            var type = (System.Type)null;

            Assert.Throws <System.ArgumentNullException>(() => new RuntimeType(typeActivator, injectionAttribute, type, true));
        }
        public void GetValidHubsWithInvalidPredicate()
        {
            var sp             = ServiceProviderHelper.CreateServiceProvider();
            var ta             = new TypeActivator();
            var hubManager     = ta.CreateInstance <DefaultHubManager>(sp);
            var hubDescriptors = hubManager.GetHubs(descriptor => descriptor.Name == "CoreTestHub_INVALIDHUB_____");

            // Still have an ienumerable sequence
            Assert.NotNull(hubDescriptors);
            // But there's nothing in the ienumerable
            Assert.Empty(hubDescriptors);
        }