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 }); }
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); } }
/// <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(); } }
[InlineData(typeof(List <int>))] // class public void CreateType(Type expectedInstanceType) { var actualValue = TypeActivator.CreateInstance(expectedInstanceType); Assert.NotNull(actualValue); Assert.IsAssignableFrom(expectedInstanceType, actualValue); }
public void CreateInstanceWithArgs2() { var expected = new string('c', 10); var actual = (string)TypeActivator.CreateInstance(typeof(string), 'c', 10); Assert.Equal(expected, actual); }
/// <summary> /// Maps to list. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="datareader">The datareader.</param> /// <returns>List<T>.</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); }
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); }
/// <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)); }
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 } })); }
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()); }
public void CreateInstanceWithTypeCast() { var expectedStream = new MemoryStream(); var writer = (StreamWriter)TypeActivator.CreateInstance(typeof(StreamWriter), expectedStream); Assert.Equal(expectedStream, writer.BaseStream); }
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); }
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; } }
public void EnsureHubThrowsWhenCantResolve() { var sp = ServiceProviderHelper.CreateServiceProvider(); var ta = new TypeActivator(); var hubManager = ta.CreateInstance <DefaultHubManager>(sp); Assert.Throws <InvalidOperationException>(() => hubManager.EnsureHub("__ELLO__")); }
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); }
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); }
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 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"); }
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); }
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); }
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)); }
public PriceCalculator() { var modules = new List <IPriceCalculationModule>(); foreach (var type in PriceCalculationModules.Modules) { modules.Add((IPriceCalculationModule)TypeActivator.CreateInstance(type)); } _modules = modules; }
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); }
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); }