コード例 #1
0
        private RuleParameter CreateConditionParameter(
            Type containerType, RuleParameterValueResolver containerResolver, string prefix, PropertyInfo property, ParamAttribute paramAttr)
        {
            var propertyType       = property.PropertyType;
            var valueResolver      = new ChainedRuleParameterValueResolver().Chain(containerResolver, new PropertyBackedRuleParameterValueResolver(property));
            var supportedOperators = GetDefaultOperators(propertyType);
            IRuleParameterValueSource valueSource = null;

            if (paramAttr.ValueSource != null)
            {
                valueSource = TypeActivator.CreateInstance(paramAttr.ValueSource) as IRuleParameterValueSource;
            }
            else if (property.PropertyType.IsEnum)
            {
                propertyType = typeof(String);
                valueSource  = StaticRuleParameterValueSource.FromEnum(property.PropertyType);
            }
            else if (IsNullableEnum(property.PropertyType))
            {
                propertyType = typeof(String);
                valueSource  = StaticRuleParameterValueSource.FromEnum(Nullable.GetUnderlyingType(property.PropertyType));
            }

            var paramName = prefix + (paramAttr.Name ?? property.Name);

            return(new RuleParameter(paramName, propertyType, valueResolver, supportedOperators)
            {
                ValueSource = valueSource
            });
        }
コード例 #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>
        /// Gets the specified type.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <returns></returns>
        public static ICustomTypeDescriptor Get(Type type)
        {
            try
            {
                locker.EnterReadLock();
                var metadataType = hashtable[type] as Type;
                ICustomTypeDescriptor descriptor = null;
                if (metadataType != null)
                {
                    var instance = TypeActivator.CreateInstance(metadataType);
                    if (instance != null)
                    {
                        // Order to get the metadata type instance from DI.
                        metadataType = instance.GetType();
                        descriptor   = new AssociatedMetadataTypeTypeDescriptionProvider(type, metadataType).GetTypeDescriptor(type);
                    }
                }

                return(descriptor);
            }
            finally
            {
                locker.ExitReadLock();
            }
        }
コード例 #4
0
        [InlineData(typeof(List <int>))]   // class
        public void CreateType(Type expectedInstanceType)
        {
            var actualValue = TypeActivator.CreateInstance(expectedInstanceType);

            Assert.NotNull(actualValue);
            Assert.IsAssignableFrom(expectedInstanceType, actualValue);
        }
コード例 #5
0
        public void CreateInstanceWithArgs2()
        {
            var expected = new string('c', 10);
            var actual   = (string)TypeActivator.CreateInstance(typeof(string), 'c', 10);

            Assert.Equal(expected, actual);
        }
コード例 #6
0
        /// <summary>
        /// Maps to list.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="datareader">The datareader.</param>
        /// <returns>List&lt;T&gt;.</returns>
        public static List <T> MapToList <T>(this IDataReader datareader)
        {
            var list = new List <T>();

            while (datareader.Read())
            {
                var fieldNames = Enumerable.Range(0, datareader.FieldCount).Select(i => datareader.GetName(i)).ToArray();
                T   obj        = TypeActivator.CreateInstance <T>();

                foreach (var prop in obj.GetType().GetProperties().EnsureNotNull())
                {
                    if (fieldNames.Contains(prop.Name) && !datareader.IsDBNull(prop.Name))
                    {
                        if (prop.PropertyType.GetTypeInfo().IsEnum)
                        {
                            prop.SetValue(obj, datareader[prop.Name]);
                        }
                        else
                        {
                            prop.SetValue(obj, Convert.ChangeType(datareader[prop.Name], prop.PropertyType), null);
                        }
                    }
                }

                list.Add(obj);
            }

            return(list);
        }
コード例 #7
0
        private Rule DeserializeIfElse(EventSlot slot, XElement element)
        {
            var rule = (IfElseRule)TypeActivator.CreateInstance(typeof(IfElseRule));
            var conditionsElement = element.Element("conditions");

            if (conditionsElement != null)
            {
                foreach (var conditionElement in conditionsElement.Elements())
                {
                    rule.Conditions.Add(DeserializeCondition(conditionElement));
                }
            }

            var thenElement = element.Element("then");

            if (thenElement != null)
            {
                foreach (var ruleElement in thenElement.Elements())
                {
                    rule.Then.Add(DeserializeRule(slot, ruleElement));
                }
            }

            var elseElement = element.Element("else");

            if (elseElement != null)
            {
                foreach (var ruleElement in elseElement.Elements())
                {
                    rule.Else.Add(DeserializeRule(slot, ruleElement));
                }
            }

            return(rule);
        }
コード例 #8
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ViewModelBlade{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 ViewModelBlade(
            IContext context,
            IBaseCommonServices commonServices,
            ILogger logger,
            bool automaticValidation = false)
            : base(context, commonServices, logger, automaticValidation)
        {
            Validator = new Action <IObservableClass>(arg =>
            {
                if (arg is ViewModelBlade <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(async() => await SubmitAsync(SelectedItem));
        }
コード例 #9
0
        public object Resolve(Type referencingType, object referenceKey)
        {
            var repositoryType   = typeof(IRepository <>).MakeGenericType(referencingType);
            var repository       = TypeActivator.CreateInstance(repositoryType);
            var candidateMethods = repository.GetType()
                                   .GetMethods(BindingFlags.Public | BindingFlags.Instance)
                                   .Where(m => m.Name == "Find");

            // 找到 IRepository<T>.Find() 方法并调用
            MethodInfo method = null;

            foreach (var candidate in candidateMethods)
            {
                var parameters = candidate.GetParameters();
                if (parameters.Length == 1 &&
                    parameters[0].ParameterType.IsArray &&
                    parameters[0].ParameterType.GetElementType() == typeof(object))
                {
                    method = candidate;
                    break;
                }
            }

            if (method == null)
            {
                throw new InvalidOperationException("Cannot find 'Find' method on IRepository.");
            }

            return(method.Invoke(repository, new object[] { new object[] { referenceKey } }));
        }
コード例 #10
0
        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());
        }
コード例 #11
0
        public void CreateInstanceWithTypeCast()
        {
            var expectedStream = new MemoryStream();
            var writer         = (StreamWriter)TypeActivator.CreateInstance(typeof(StreamWriter), expectedStream);

            Assert.Equal(expectedStream, writer.BaseStream);
        }
コード例 #12
0
        public void CreateInstanceWithArgs4()
        {
            var expected = Guid.Empty;
            var actual   = (Guid)TypeActivator.CreateInstance(typeof(Guid), 0, (short)0, (short)0, new byte[8]);

            Assert.Equal(expected, actual);
        }
コード例 #13
0
 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;
     }
 }
コード例 #14
0
        public void EnsureHubThrowsWhenCantResolve()
        {
            var sp         = ServiceProviderHelper.CreateServiceProvider();
            var ta         = new TypeActivator();
            var hubManager = ta.CreateInstance <DefaultHubManager>(sp);

            Assert.Throws <InvalidOperationException>(() => hubManager.EnsureHub("__ELLO__"));
        }
コード例 #15
0
        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);
        }
コード例 #16
0
        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);
        }
コード例 #17
0
        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");
        }
コード例 #18
0
        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);
        }
コード例 #19
0
        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);
        }
コード例 #20
0
        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);
        }
コード例 #21
0
        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);
        }
コード例 #22
0
        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);
        }
コード例 #23
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();
        }
コード例 #24
0
        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");
        }
コード例 #25
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);
        }
コード例 #26
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);
        }
コード例 #27
0
        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 PriceCalculator()
        {
            var modules = new List <IPriceCalculationModule>();

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

            _modules = modules;
        }
コード例 #29
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);
        }
コード例 #30
0
        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);
        }