public void ConstructionOfInvalidTypeThrows() { Assert.Throws <InvalidOperationException>(() => TypeConstruction.Construct <IConstructInterface>()); Assert.Throws <InvalidOperationException>(() => TypeConstruction.Construct <AbstractConstructibleBaseType>()); Assert.Throws <InvalidOperationException>(() => TypeConstruction.Construct <NonConstructibleDerivedType>()); Assert.Throws <InvalidOperationException>(() => TypeConstruction.Construct <ParameterConstructorType>()); }
internal static void ValidateBuildArtifactTypeAndThrow(Type buildArtifactType) { if (buildArtifactType == null) { throw new ArgumentNullException(nameof(buildArtifactType)); } if (buildArtifactType == typeof(object)) { throw new InvalidOperationException("Build artifact type cannot be object."); } if (!buildArtifactType.IsClass) { throw new InvalidOperationException($"Build artifact type {buildArtifactType.FullName} is not a class."); } if (!typeof(IBuildArtifact).IsAssignableFrom(buildArtifactType)) { throw new InvalidOperationException($"Build artifact type {buildArtifactType.FullName} does not derive from {typeof(IBuildArtifact).FullName}."); } if (!TypeConstruction.CanBeConstructed(buildArtifactType)) { throw new InvalidOperationException($"Build artifact type {buildArtifactType.FullName} cannot be constructed because it does not have a default, implicit or registered constructor."); } }
internal static IBuildStep Deserialize(string json) { if (string.IsNullOrEmpty(json)) { return(null); } if (GlobalObjectId.TryParse(json, out var id)) { if (GlobalObjectId.GlobalObjectIdentifierToObjectSlow(id) is BuildPipeline pipeline) { return(pipeline); } } else { var type = Type.GetType(json); if (TypeConstruction.TryConstruct <IBuildStep>(type, out var step)) { return(step); } } return(null); }
public void CanBeConstructedFromGenericMethod_WithNonConstructableType_ReturnsFalse() { Assert.That(TypeConstruction.CanBeConstructed <IConstructInterface>(), Is.False); Assert.That(TypeConstruction.CanBeConstructed <AbstractConstructibleBaseType>(), Is.False); Assert.That(TypeConstruction.CanBeConstructed <NonConstructibleDerivedType>(), Is.False); Assert.That(TypeConstruction.CanBeConstructed <ParameterConstructorType>(), Is.False); }
public CerasMessageSerializer() { CerasBufferPool.Pool = new CerasBuffer(); _serializer = new ThreadLocal <CerasSerializer>(() => { config = new SerializerConfig(); config.Warnings.ExceptionOnStructWithAutoProperties = false; config.OnConfigNewType = (t) => { t.TargetMembers = TargetMember.AllPublic; t.TypeConstruction = TypeConstruction.ByUninitialized(); if (typeof(Exception).IsAssignableFrom(t.Type)) { t.TargetMembers = TargetMember.All; } }; return(new CerasSerializer(config)); }); }
/// <summary> /// Get all optional components from <see cref="BuildConfiguration"/>, that matches <see cref="Type"/>. /// Optional component types not found in <see cref="BuildConfiguration"/> will be set to a new instance of that type. /// </summary> /// <param name="context">The <see cref="BuildContext"/> used by the execution of this <see cref="BuildStep"/>.</param> /// <param name="type">Type of the components.</param> /// <returns>List of optional components.</returns> public IEnumerable <IBuildComponent> GetOptionalComponents(BuildContext context, Type type) { CheckTypeAndThrowIfInvalid <IBuildComponent>(type); if (OptionalComponents == null || !OptionalComponents.Contains(type)) { throw new InvalidOperationException($"Component type '{type.FullName}' is not in the {nameof(OptionalComponents)} list."); } var lookup = new Dictionary <Type, IBuildComponent>(); foreach (var optionalComponentType in OptionalComponents) { if (!type.IsAssignableFrom(optionalComponentType)) { continue; } if (!context.BuildConfiguration.TryGetComponent(optionalComponentType, out var component)) { component = TypeConstruction.Construct <IBuildComponent>(optionalComponentType); } lookup[optionalComponentType] = component; } return(lookup.Values); }
public void ReturnsAnActualInstanceTests() { { var instance = TypeConstruction.Construct <ConstructibleBaseType>(); Assert.That(instance, Is.Not.Null); Assert.That(instance.Value, Is.EqualTo(25.0f)); } { var instance = TypeConstruction.Construct <ConstructibleDerivedType>(); Assert.That(instance, Is.Not.Null); Assert.That(instance.Value, Is.EqualTo(25.0f)); Assert.That(instance.SubValue, Is.EqualTo(50.0f)); } { var instance = TypeConstruction.Construct <ConstructibleDerivedType>(); Assert.That(instance, Is.Not.Null); Assert.That(instance.Value, Is.EqualTo(25.0f)); Assert.That(instance.SubValue, Is.EqualTo(50.0f)); } { var instance = TypeConstruction.Construct <ScriptableObjectType>(); Assert.That(instance, Is.Not.Null); Assert.That(instance, Is.Not.False); } }
public Ceras(bool forNetworking = true) { if (CerasBufferPool.Pool == null) { CerasBufferPool.Pool = new CerasDefaultBufferPool(); } mSerializerConfig = new SerializerConfig { PreserveReferences = false }; mSerializerConfig.Advanced.SealTypesWhenUsingKnownTypes = forNetworking; if (forNetworking) { mSerializerConfig.VersionTolerance.Mode = VersionToleranceMode.Disabled; mSerializerConfig.KnownTypes.AddRange(KnownTypes); mSerializerConfig.KnownTypes.ForEach( knownType => mSerializerConfig.ConfigType(knownType).TypeConstruction = TypeConstruction.ByUninitialized() ); } else { mSerializerConfig.VersionTolerance.Mode = VersionToleranceMode.Standard; } mSerializer = new CerasSerializer(mSerializerConfig); }
static void AssertPropertyIsOfType <TContainer, TValue>(IPropertyBag <TContainer> propertyBag, string propertyName) { var container = TypeConstruction.Construct <TContainer>(typeof(TContainer)); var changeTracker = default(ChangeTracker); var action = new AssertThatPropertyIsOfType <TContainer, TValue>(); Assert.That(propertyBag.FindProperty(propertyName, ref container, ref changeTracker, ref action), Is.True); }
static T CopyComponent <T>(T value) { var result = TypeConstruction.Construct <T>(value.GetType()); PropertyContainer.Construct(ref result, ref value).Dispose(); PropertyContainer.Transfer(ref result, ref value).Dispose(); return(result); }
public static void RegisterTypes() { TypeConversion.Register <SerializedStringView, DirectoryInfo>(view => new DirectoryInfo(view.ToString())); TypeConstruction.SetExplicitConstructionMethod(() => { return(new DirectoryInfo(".")); }); TypeConversion.Register <SerializedStringView, FileInfo>(view => new FileInfo(view.ToString())); TypeConstruction.SetExplicitConstructionMethod(() => { return(new FileInfo(".")); }); }
public void CanBeConstructedFromGenericMethod_WithConstructableType_ReturnsTrue() { Assert.That(TypeConstruction.CanBeConstructed <ConstructibleBaseType>(), Is.True); Assert.That(TypeConstruction.CanBeConstructed <ConstructibleDerivedType>(), Is.True); Assert.That(TypeConstruction.CanBeConstructed <NoConstructorType>(), Is.True); Assert.That(TypeConstruction.CanBeConstructed <ParameterLessConstructorType>(), Is.True); Assert.That(TypeConstruction.CanBeConstructed <ScriptableObjectType>(), Is.True); }
public VisitStatus Visit <TContainer, TValue>(Property <TContainer, TValue> property, ref TContainer container, ref TValue value) { if (!RuntimeTypeInfoCache <TValue> .CanBeNull || null != value) { return(VisitStatus.Unhandled); } if (typeof(UnityEngine.Object).IsAssignableFrom(typeof(TValue))) { return(VisitStatus.Unhandled); } if (!property.IsReadOnly && property.HasAttribute <CreateInstanceOnInspectionAttribute>() && !(property is ICollectionElementProperty)) { var attribute = property.GetAttribute <CreateInstanceOnInspectionAttribute>(); if (null == attribute.Type) { if (TypeConstruction.CanBeConstructed <TValue>()) { value = TypeConstruction.Construct <TValue>(); property.SetValue(ref container, value); return(VisitStatus.Unhandled); } Debug.LogWarning(PropertyChecks.GetNotConstructableWarningMessage(typeof(TValue))); } else { var isAssignable = typeof(TValue).IsAssignableFrom(attribute.Type); var isConstructable = TypeConstruction.GetAllConstructableTypes(typeof(TValue)) .Contains(attribute.Type); if (isAssignable && isConstructable) { value = TypeConstruction.Construct <TValue>(attribute.Type); property.SetValue(ref container, value); return(VisitStatus.Unhandled); } Debug.LogWarning(isAssignable ? PropertyChecks.GetNotConstructableWarningMessage(attribute.Type) : PropertyChecks.GetNotAssignableWarningMessage(attribute.Type, typeof(TValue))); } } Visitor.AddToPath(property); try { var path = Visitor.GetCurrentPath(); var element = new NullElement <TValue>(VisitorContext.Root, property, path); VisitorContext.Parent.contentContainer.Add(element); } finally { Visitor.RemoveFromPath(property); } return(VisitStatus.Stop); }
internal static SearcherDatabase Populate <T>(Func <Type, bool> filter = null, Func <Type, string> nameResolver = null, Func <Type, string> categoryResolver = null) { var list = new List <SearcherItem>(); var dict = new Dictionary <string, SearcherItem>(); var types = TypeCache.GetTypesDerivedFrom <T>(); foreach (var type in types) { if (type.IsGenericType || type.IsAbstract || type.ContainsGenericParameters || type.IsInterface) { continue; } if (!TypeConstruction.CanBeConstructed(type)) { continue; } if (filter != null && !filter(type)) { continue; } try { var typeItem = new TypeSearcherItem(type, nameResolver != null ? nameResolver(type) : string.Empty); var category = categoryResolver != null?categoryResolver(type) : type.Namespace ?? "Global"; if (!string.IsNullOrEmpty(category)) { if (!dict.TryGetValue(category, out var item)) { dict[category] = item = new SearcherItem(category); list.Add(item); } item.AddChild(typeItem); } else { list.Add(typeItem); } } catch (Exception) { // ignored } } foreach (var kvp in dict) { kvp.Value.Children.Sort(CompareByName); } list.Sort(CompareByName); return(new SearcherDatabase(list)); }
bool OnTypeSelected(SearcherItem item) { if (item is TypeSearcherItem typeItem && TypeConstruction.TryConstruct <T>(typeItem.Type, out var instance)) { Target = instance; return(true); } return(false); }
public void CanBeConstructedFromDerivedType_FromNonConstructableDerivedType_ReturnsFalse() { Assert.That(TypeConstruction.CanBeConstructedFromDerivedType <ConstructibleDerivedType>(), Is.False); Assert.That(TypeConstruction.CanBeConstructedFromDerivedType <NonConstructibleDerivedType>(), Is.False); Assert.That(TypeConstruction.CanBeConstructedFromDerivedType <NoConstructorType>(), Is.False); Assert.That(TypeConstruction.CanBeConstructedFromDerivedType <ParameterLessConstructorType>(), Is.False); Assert.That(TypeConstruction.CanBeConstructedFromDerivedType <ParameterConstructorType>(), Is.False); Assert.That(TypeConstruction.CanBeConstructedFromDerivedType <ScriptableObjectType>(), Is.False); }
/// <summary> /// Get the value of a <see cref="Type"/> component if found. /// Otherwise an instance created using <see cref="TypeConstruction"/> utility. /// The container is not modified. /// </summary> /// <param name="type"><see cref="Type"/> of the component.</param> /// <returns>The component value.</returns> public TComponent GetComponentOrDefault(Type type) { CheckComponentTypeAndThrowIfInvalid(type); if (!TryGetComponent(type, out var value)) { return(TypeConstruction.Construct <TComponent>(type)); } return(value); }
internal static TComponent Construct(Type componentType) { if (!TypeConstruction.CanBeConstructed(componentType)) { throw new InvalidOperationException($"Component type {componentType.FullName} cannot be constructed because it does not have a default, implicit or registered constructor."); } return(TypeConstruction.Construct <TComponent>(componentType)); }
public NullElement(PropertyElement root, IProperty property, PropertyPath path) { m_PotentialTypes = new List <Type> { typeof(Null) }; binding = this; m_Root = root; m_Path = path; name = m_Path.ToString(); TypeConstruction.GetAllConstructableTypes <T>(m_PotentialTypes); if (typeof(T).IsArray) { Resources.Templates.NullStringField.Clone(this); this.Q <Label>().text = GuiFactory.GetDisplayName(property); var button = this.Q <Button>(); button.text = $"Null ({GetTypeName(typeof(T))})"; button.clickable.clicked += ReloadWithArrayType; if (property.IsReadOnly) { button.SetEnabledSmart(false); } return; } if (m_PotentialTypes.Count == 2) { Resources.Templates.NullStringField.Clone(this); this.Q <Label>().text = GuiFactory.GetDisplayName(property); var button = this.Q <Button>(); button.text = $"Null ({GetTypeName(typeof(T))})"; button.clickable.clicked += ReloadWithFirstType; if (property.IsReadOnly) { button.SetEnabledSmart(false); } return; } var typeSelector = new PopupField <Type>( GuiFactory.GetDisplayName(property), m_PotentialTypes, typeof(Null), GetTypeName, GetTypeName); typeSelector.RegisterValueChangedCallback(OnCreateItem); if (property.IsReadOnly) { typeSelector.pickingMode = PickingMode.Ignore; typeSelector.Q(className: UssClasses.Unity.BasePopupFieldInput).SetEnabledSmart(false); } Add(typeSelector); }
static void AssertPropertyValueAndTypeIsEqualTo <TContainer>(IPropertyBag <TContainer> propertyBag, string propertyName, object expectedValue) { var container = TypeConstruction.Construct <TContainer>(typeof(TContainer)); var changeTracker = default(ChangeTracker); var action = new AssertThatPropertyValueAndTypeIsEqualTo <TContainer> { ExpectedValue = expectedValue }; Assert.That(propertyBag.FindProperty(propertyName, ref container, ref changeTracker, ref action), Is.True); }
public static IEnumerable <T> ConstructTypesDerivedFrom <T>(bool fromUnityAssembliesOnly = true) { var types = TypeCache.GetTypesDerivedFrom <T>().Where(type => !type.IsAbstract && !type.IsGenericType); if (fromUnityAssembliesOnly) { types = types.Where(type => type.Assembly.GetName().Name.StartsWith("Unity.")); } return(types.Select(type => TypeConstruction.Construct <T>(type))); }
public void Initialization() { var constructor = NormalizingMemberInfoFromExpressionUtility.GetConstructor(() => new DomainAspect()); var result = new TypeConstruction(typeof(DomainAspect)); Assert.That(result.ConstructorInfo, Is.EqualTo(constructor)); Assert.That(result.ConstructorArguments, Is.Empty); Assert.That(result.NamedArguments, Is.Empty); }
/// <summary> /// Set the value of a <see cref="Type"/> component on this container using an instance created using <see cref="TypeConstruction"/> utility. /// </summary> /// <param name="type">Type of the component.</param> public void SetComponent(Type type) { CheckComponentTypeAndThrowIfInvalid(type); if (type.IsInterface || type.IsAbstract) { throw new InvalidOperationException($"{nameof(type)} cannot be interface or abstract."); } SetComponent(type, TypeConstruction.Construct <TComponent>(type)); }
private void AddKnownTypes(SerializerConfig config, string nameSpce) { var packetTypes = Assembly.GetExecutingAssembly().GetTypes().Where(t => t.Namespace == nameSpce).ToList(); foreach (var typ in packetTypes) { config.KnownTypes.Add(typ); mSerializerConfig.ConfigType(typ).TypeConstruction = TypeConstruction.ByUninitialized(); } }
public static T ConstructFromAssemblyQualifiedTypeName <T>(string assemblyQualifiedTypeName) { var type = Type.GetType(assemblyQualifiedTypeName); if (null == type && FormerNameAttribute.TryGetCurrentTypeName(assemblyQualifiedTypeName, out var currentTypeName)) { type = Type.GetType(currentTypeName); } return(TypeConstruction.Construct <T>(type)); }
public void TryToConstructAnInstance_WithAConstructableType_ReturnsTrue() { Assert.That(TypeConstruction.TryConstruct <Types.NoConstructorClass>(out _), Is.True); Assert.That(TypeConstruction.TryConstruct <Types.NoConstructorStruct>(out _), Is.True); Assert.That(TypeConstruction.TryConstruct <Types.DefaultConstructorClass>(out _), Is.True); Assert.That(TypeConstruction.TryConstruct <Types.DefaultAndCustomConstructorClass>(out _), Is.True); Assert.That(TypeConstruction.TryConstruct <Types.CustomConstructorStruct>(out _), Is.True); Assert.That(TypeConstruction.TryConstruct <Types.ChildOfAbstractClassWithNoConstructor>(out _), Is.True); Assert.That(TypeConstruction.TryConstruct <Types.ChildOfAbstractClassWithDefaultConstructor>(out _), Is.True); Assert.That(TypeConstruction.TryConstruct <Types.ChildOfAbstractClassWithPrivateDefaultConstructor>(out _), Is.True); }
/// <summary> /// Get the first build artifact value that is assignable to specified type, or create and set it if not found. /// Multiple build artifact value can be stored per build configuration. /// </summary> /// <typeparam name="T">The build artifact type.</typeparam> /// <returns>The build artifact value.</returns> public T GetOrCreateBuildArtifact <T>() where T : class, IBuildArtifact, new() { var artifact = GetBuildArtifact <T>(); if (artifact == null) { artifact = TypeConstruction.Construct <T>(); SetBuildArtifact(artifact); } return(artifact); }
/// <summary> /// Get value of type <typeparamref name="T"/> if found, otherwise a new instance of type <typeparamref name="T"/> constructed with <see cref="TypeConstruction"/>. /// </summary> /// <typeparam name="T">The value type.</typeparam> /// <returns>The value or new instance of type <typeparamref name="T"/>.</returns> public T GetOrCreateValue <T>() where T : class { var value = GetValue <T>(); if (value == null) { value = TypeConstruction.Construct <T>(); SetValue(value); } return(value); }
public Aspect Build(Type type) { var aspectAttribute = type.GetCustomAttributes <AspectAttribute> (true).SingleOrDefault(); Assertion.IsNotNull(aspectAttribute); var construction = new TypeConstruction(type); var pointcut = _pointcutBuilder.Build(type); return(Build(type, aspectAttribute, construction, pointcut)); }
public void ConstructingAnInstance_WithAConstructableType_ReturnsAnActualInstance() { Assert.That(TypeConstruction.Construct <Types.NoConstructorClass>(), Is.Not.Null); Assert.That(TypeConstruction.Construct <Types.NoConstructorStruct>(), Is.Not.Null); Assert.That(TypeConstruction.Construct <Types.DefaultConstructorClass>(), Is.Not.Null); Assert.That(TypeConstruction.Construct <Types.DefaultAndCustomConstructorClass>(), Is.Not.Null); Assert.That(TypeConstruction.Construct <Types.CustomConstructorStruct>(), Is.Not.Null); Assert.That(TypeConstruction.Construct <Types.ChildOfAbstractClassWithNoConstructor>(), Is.Not.Null); Assert.That(TypeConstruction.Construct <Types.ChildOfAbstractClassWithDefaultConstructor>(), Is.Not.Null); Assert.That(TypeConstruction.Construct <Types.ChildOfAbstractClassWithPrivateDefaultConstructor>(), Is.Not.Null); }