public override IYamlSerializable TryCreate(SerializerContext context, ITypeDescriptor typeDescriptor)
        {
            if (CanVisit(typeDescriptor.Type))
                return this;

            return null;
        }
Ejemplo n.º 2
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ObjectContext"/> struct.
 /// </summary>
 /// <param name="serializerContext">The serializer context.</param>
 /// <param name="instance">The instance.</param>
 /// <param name="descriptor">The descriptor.</param>
 public ObjectContext(SerializerContext serializerContext, object instance, ITypeDescriptor descriptor) : this()
 {
     SerializerContext = serializerContext;
     Instance = instance;
     Descriptor = descriptor;
     Properties = new PropertyContainer();
 }
Ejemplo n.º 3
0
 protected ContentBase(ITypeDescriptor descriptor, bool isPrimitive, IReference reference)
 {
     if (descriptor == null) throw new ArgumentNullException(nameof(descriptor));
     Reference = reference;
     Descriptor = descriptor;
     IsPrimitive = isPrimitive;
 }
 /// <inheritdoc/>
 public override void VisitCollectionItem(IEnumerable collection, CollectionDescriptor descriptor, int index, object item, ITypeDescriptor itemDescriptor)
 {
     if (CurrentPath.Match(MemberPath))
         VisitAssetMember(item, itemDescriptor);
     else
         base.VisitCollectionItem(collection, descriptor, index, item, itemDescriptor);
 }
 public FlexiPlainTextSerializationContext(
     IFlexiPlainTextSerializer serializer,
     ITypeDescriptor typeDescriptor,
     TypeResolver typeResolver,
     Func<Type, CreateInstanceContext, object> createInstanceWith = null)
     : base(serializer, typeDescriptor, typeResolver, createInstanceWith)
 { }
 /// <inheritdoc/>
 public override void VisitArrayItem(Array array, ArrayDescriptor descriptor, int index, object item, ITypeDescriptor itemDescriptor)
 {
     if (CurrentPath.Match(MemberPath))
         VisitAssetMember(item, itemDescriptor);
     else
         base.VisitArrayItem(array, descriptor, index, item, itemDescriptor);
 }
Ejemplo n.º 7
0
        /// <summary>
        /// Retrieves the value itself or the value of one of its item, depending on the given <see cref="Index"/>.
        /// </summary>
        /// <param name="value">The value on which this method applies.</param>
        /// <param name="index">The index of the item to retrieve. If <see cref="Index.Empty"/> is passed, this method will return the value itself.</param>
        /// <param name="descriptor">The descriptor of the type of <paramref name="value"/>.</param>
        /// <returns>The value itself or the value of one of its item.</returns>
        public static object Retrieve(object value, Index index, ITypeDescriptor descriptor)
        {
            if (index.IsEmpty)
                return value;

            if (value == null) throw new ArgumentNullException(nameof(value));

            var collectionDescriptor = descriptor as CollectionDescriptor;
            if (collectionDescriptor != null)
            {
                return collectionDescriptor.GetValue(value, index.Int);
            }
            var dictionaryDescriptor = descriptor as DictionaryDescriptor;
            if (dictionaryDescriptor != null)
            {
                return dictionaryDescriptor.GetValue(value, index.Value);
            }

            // Try with the concrete type descriptor
            var objectDescriptor = TypeDescriptorFactory.Default.Find(value.GetType());
            if (objectDescriptor != descriptor)
            {
                return Retrieve(value, index, objectDescriptor);
            }

            throw new NotSupportedException("Unable to retrieve the value at the given index, this collection is unsupported");
        }
        /// <inheritdoc/>
        protected override object TransformForSerialization(ITypeDescriptor descriptor, object collection)
        {
            var dictionaryDescriptor = (DictionaryDescriptor)descriptor;
            var instance = CreatEmptyContainer(descriptor);

            CollectionItemIdentifiers identifier;
            if (!CollectionItemIdHelper.TryGetCollectionItemIds(collection, out identifier))
            {
                identifier = new CollectionItemIdentifiers();
            }
            var keyWithIdType = typeof(KeyWithId<>).MakeGenericType(dictionaryDescriptor.KeyType);
            foreach (var item in dictionaryDescriptor.GetEnumerator(collection))
            {
                ItemId id;
                if (!identifier.TryGet(item.Key, out id))
                {
                    id = ItemId.New();
                    identifier.Add(item.Key, id);
                }
                var keyWithId = Activator.CreateInstance(keyWithIdType, id, item.Key);
                instance.Add(keyWithId, item.Value);
            }

            return instance;
        }
Ejemplo n.º 9
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ObjectContext"/> struct.
 /// </summary>
 /// <param name="serializerContext">The serializer context.</param>
 /// <param name="instance">The instance.</param>
 /// <param name="descriptor">The descriptor.</param>
 public ObjectContext(SerializerContext serializerContext, object instance, ITypeDescriptor descriptor)
     : this()
 {
     SerializerContext = serializerContext;
     Instance = instance;
     Descriptor = descriptor;
 }
Ejemplo n.º 10
0
 public ObjectContent(object value, ITypeDescriptor descriptor, bool isPrimitive, IReference reference)
     : base(descriptor, isPrimitive, reference)
 {
     if (reference is ObjectReference)
         throw new ArgumentException($"An {nameof(ObjectContent)} cannot contain an {nameof(ObjectReference)}");
     this.value = value;
 }
Ejemplo n.º 11
0
        public Unbinder(ITypeDescriptor typeDescriptor,
		                ITypeSimplicityEvaluator typeSimplicityEvaluator,
		                IValueUnbinder valueUnbinder)
        {
            _typeDescriptor = typeDescriptor;
            _typeSimplicityEvaluator = typeSimplicityEvaluator;
            _valueUnbinder = valueUnbinder;
        }
        public override void VisitDictionaryKeyValue(object dictionary, DictionaryDescriptor descriptor, object key, ITypeDescriptor keyDescriptor, object value, ITypeDescriptor valueDescriptor)
        {
            // TODO: CurrentPath is valid only for value, not key
            //if (ProcessObject(key, keyDescriptor.Type)) key = null;
            if (ProcessObject(value, valueDescriptor.Type)) return;

            Visit(value, valueDescriptor);
            //base.VisitDictionaryKeyValue(dictionary, descriptor, key, keyDescriptor, value, valueDescriptor);
        }
Ejemplo n.º 13
0
 protected override IDataContextStack CreateDataContextTypeStack(ITypeDescriptor viewModelType, ITypeDescriptor wrapperType = null, IDataContextStack parentDataContextStack = null)
 {
     var dataContextTypeStack = new DataContextStack(ResolvedTypeDescriptor.ToSystemType(viewModelType), parentDataContextStack as DataContextStack);
     if (wrapperType != null)
     {
         dataContextTypeStack.RootControlType = ResolvedTypeDescriptor.ToSystemType(wrapperType);
     }
     return dataContextTypeStack;
 }
Ejemplo n.º 14
0
 protected ContentBase(ITypeDescriptor descriptor, bool isPrimitive, IReference reference)
 {
     if (descriptor == null) throw new ArgumentNullException("descriptor");
     this.reference = reference;
     Descriptor = descriptor;
     IsPrimitive = isPrimitive;
     SerializeFlags = ViewModelContentSerializeFlags.SerializeValue;
     ShouldProcessReference = true;
 }
Ejemplo n.º 15
0
 void InitFromItemDescriptor(ITypeDescriptor descriptor)
 {
     if (descriptor == _itemDescriptor && _name != null) return;
     _itemDescriptor = descriptor;
     if ((descriptor.Name?.Length ?? 0) == 0) return;
     _itemType = _itemDescriptor.GetPreferedType();
     Sealed = _itemDescriptor.Sealed;
     Name = $"List<{_itemDescriptor.Name}>";
 }
 public FlexiXmlSerializationContext(
     IFlexiSerializer serializer, 
     ITypeDescriptor typeDescriptor, 
     TypeResolver typeResolver,
     FlexiXmlSerializationOptions options,
     Func<Type, CreateInstanceContext, object> createInstanceWith = null)
     : base(serializer, typeDescriptor, typeResolver, createInstanceWith)
 {
     this.Options = options;
 }
 /// <inheritdoc/>
 public override IYamlSerializable TryCreate(SerializerContext context, ITypeDescriptor typeDescriptor)
 {
     if (typeDescriptor is CollectionDescriptor)
     {
         var dataStyle = typeDescriptor.Type.GetCustomAttribute<DataStyleAttribute>();
         if (dataStyle == null || dataStyle.Style != DataStyle.Compact)
             return this;
     }
     return null;
 }
 public SerializationContext(
     IFlexiSerializer serializer,
     ITypeDescriptor typeDescriptor,
     TypeResolver typeResolver,
     Func<Type, CreateInstanceContext, object> createInstanceWith = null)
 {
     this.Serializer = serializer;
     this.TypeDescriptor = typeDescriptor;
     this.TypeResolver = typeResolver;
     this.CustomCreateInstanceWith = createInstanceWith;
 }
Ejemplo n.º 19
0
 void InitFromKeyValueDescriptors(ITypeDescriptor keyDescriptor, ITypeDescriptor valueDescriptor)
 {
     if (_keyDescriptor == keyDescriptor && _valueDescriptor == valueDescriptor && _name != null) return;
     _keyDescriptor = keyDescriptor;
     _valueDescriptor = valueDescriptor;
     if ((_keyDescriptor.Name?.Length ?? 0) == 0 || (_valueDescriptor.Name?.Length ?? 0) == 0) return;
     _keyType = _keyDescriptor.GetPreferedType();
     _valueType = _valueDescriptor.GetPreferedType();
     Sealed = _keyDescriptor.Sealed && _valueDescriptor.Sealed;
     Name = $"Dictionary<{_keyDescriptor.Name}, {_valueDescriptor.Name}>";
 }
Ejemplo n.º 20
0
        /// <inheritdoc/>
        public override bool CanAttach(ITypeDescriptor typeDescriptor, MemberDescriptorBase memberDescriptor)
        {
            var type = typeDescriptor.GetInnerCollectionType();
            var isNullableStruct = type.IsNullable() && Nullable.GetUnderlyingType(type).IsStruct();
            var isAbstractOrClass = type.IsAbstract || type.IsClass;
            //var isCollection = (typeDescriptor is CollectionDescriptor) || (typeDescriptor is DictionaryDescriptor);

            //var result = isNullableStruct || (isAbstractOrClass && !isCollection);
            var result = isNullableStruct || isAbstractOrClass;
            return result;
        }
Ejemplo n.º 21
0
        /// <inheritdoc/>
        public override bool CanAttach(ITypeDescriptor typeDescriptor, MemberDescriptorBase memberDescriptor)
        {
            if (memberDescriptor != null)
            {
                var attrib = TypeDescriptorFactory.Default.AttributeRegistry.GetAttribute<MemberCollectionAttribute>(memberDescriptor.MemberInfo);
                if (attrib != null && attrib.ReadOnly)
                    return false;
            }

            var collectionDescriptor = typeDescriptor as CollectionDescriptor;
            return collectionDescriptor != null && collectionDescriptor.HasInsert;
        }
Ejemplo n.º 22
0
        /// <inheritdoc/>
        public override bool CanAttach(ITypeDescriptor descriptor, MemberDescriptorBase memberDescriptor)
        {
            if (memberDescriptor != null)
            {
                var attrib = TypeDescriptorFactory.Default.AttributeRegistry.GetAttribute<MemberCollectionAttribute>(memberDescriptor.MemberInfo);
                if (attrib != null && attrib.ReadOnly)
                    return false;
            }

            var dictionaryDescriptor = descriptor as DictionaryDescriptor;
            return dictionaryDescriptor != null && dictionaryDescriptor.KeyType == typeof(string);
        }
Ejemplo n.º 23
0
 public IAbstractBinding BuildBinding(BindingParserOptions bindingOptions, DothtmlBindingNode node, IDataContextStack dataContext, Exception parsingError, ITypeDescriptor resultType, object customData)
 {
     return new ResolvedBinding()
     {
         BindingType = bindingOptions.BindingType,
         Value = node.Value,
         Expression = (Expression)customData,
         DataContextTypeStack = (DataContextStack)dataContext,
         ParsingError = parsingError,
         BindingNode = node,
         ResultType = resultType
     };
 }
Ejemplo n.º 24
0
        private static object GenerateStringKey(object value, ITypeDescriptor descriptor, object baseValue)
        {
            // TODO: use a dialog service and popup a message when the given key is invalid
            string baseName = GenerateBaseName(baseValue);
            int i = 1;

            var dictionary = (DictionaryDescriptor)descriptor;
            while (dictionary.ContainsKey(value, baseName))
            {
                baseName = (baseValue != null ? baseValue.ToString() : "Key") + " " + ++i;
            }

            return baseName;
        }
        internal static Index GenerateStringKey(object value, ITypeDescriptor descriptor, string baseValue)
        {
            // TODO: use a dialog service and popup a message when the given key is invalid
            var baseName = GenerateBaseName(baseValue);
            var i = 1;

            var dictionary = (DictionaryDescriptor)descriptor;
            while (dictionary.ContainsKey(value, baseName))
            {
                baseName = (baseValue ?? "Key") + " " + ++i;
            }

            return new Index(baseName);
        }
Ejemplo n.º 26
0
 /// <inheritdoc/>
 public override bool CanAttach(ITypeDescriptor typeDescriptor, MemberDescriptorBase memberDescriptor)
 {
     if (memberDescriptor != null)
     {
         var attrib = TypeDescriptorFactory.Default.AttributeRegistry.GetAttribute<MemberCollectionAttribute>(memberDescriptor.MemberInfo);
         if (attrib != null && attrib.ReadOnly)
             return false;
     }
     
     var dictionaryDescriptor = typeDescriptor as DictionaryDescriptor;
     if (dictionaryDescriptor == null)
         return false;
     return !dictionaryDescriptor.KeyType.IsClass || dictionaryDescriptor.KeyType == typeof(string) || dictionaryDescriptor.KeyType.GetConstructor(new Type[0]) != null;
 }
 /// <inheritdoc/>
 public override void VisitDictionaryKeyValue(object dictionary, DictionaryDescriptor descriptor, object key, ITypeDescriptor keyDescriptor, object value, ITypeDescriptor valueDescriptor)
 {
     if (CurrentPath.Match(MemberPath))
     {
         var keyValueType = typeof(KeyValuePair<,>).MakeGenericType(keyDescriptor.Type, valueDescriptor.Type);
         var keyValueDescriptor = TypeDescriptorFactory.Find(keyValueType);
         var keyValuePair = Activator.CreateInstance(keyValueType, key, value);
         VisitAssetMember(keyValuePair, keyValueDescriptor);
     }
     else
     {
         base.VisitDictionaryKeyValue(dictionary, descriptor, key, keyDescriptor, value, valueDescriptor);
     }
 }
Ejemplo n.º 28
0
        /// <inheritdoc/>
        public override bool CanAttach(ITypeDescriptor typeDescriptor, MemberDescriptorBase memberDescriptor)
        {
            if (memberDescriptor != null)
            {
                var attrib = TypeDescriptorFactory.Default.AttributeRegistry.GetAttribute<MemberCollectionAttribute>(memberDescriptor.MemberInfo);
                if (attrib?.ReadOnly == true)
                    return false;
            }
            
            var collectionDescriptor = typeDescriptor as CollectionDescriptor;
            if (collectionDescriptor == null)
                return false;

            var elementType = collectionDescriptor.ElementType;
            return collectionDescriptor.HasAdd && (CanConstruct(elementType) || CanAddNull(elementType) || IsReferenceType(elementType));
        }
        public NamingConventionTypeDescriptor(ITypeDescriptor innerTypeDescriptor, INamingConvention namingConvention)
        {
            if (innerTypeDescriptor == null)
            {
                throw new ArgumentNullException("innerTypeDescriptor");
            }

            this.innerTypeDescriptor = innerTypeDescriptor;

            if (namingConvention == null)
            {
                throw new ArgumentNullException("namingConvention");
            }

            this.namingConvention = namingConvention;
        }
Ejemplo n.º 30
0
        /// <inheritdoc/>
        public override bool CanAttach(ITypeDescriptor typeDescriptor, MemberDescriptorBase memberDescriptor)
        {
            if (memberDescriptor != null)
            {
                var attrib = TypeDescriptorFactory.Default.AttributeRegistry.GetAttribute<MemberCollectionAttribute>(memberDescriptor.MemberInfo);
                if (attrib != null && attrib.ReadOnly)
                    return false;
            }
            
            var collectionDescriptor = typeDescriptor as CollectionDescriptor;
            if (collectionDescriptor == null)
                return false;

            var elementType = collectionDescriptor.ElementType;
            return collectionDescriptor.HasAdd && (!elementType.IsClass || elementType.GetConstructor(Type.EmptyTypes) != null || elementType.IsAbstract || elementType.IsNullable() || elementType == typeof(string));
        }
Ejemplo n.º 31
0
        Func <AbstractBufferedReader, ITypeBinaryDeserializerContext, ITypeSerializersId2LoaderMapping, ITypeDescriptor, object> LoaderFactory(ITypeDescriptor descriptor)
        {
            var loadAsType    = LoadAsType(descriptor);
            var methodBuilder = ILBuilder.Instance.NewMethod <Func <AbstractBufferedReader, ITypeBinaryDeserializerContext, ITypeSerializersId2LoaderMapping, ITypeDescriptor, object> >("DeserializerFor" + descriptor.Name);
            var il            = methodBuilder.Generator;

            if (descriptor.AnyOpNeedsCtx())
            {
                var localCtx = il.DeclareLocal(typeof(ITypeBinaryDeserializerContext), "ctx");
                var haveCtx  = il.DefineLabel();
                il
                .Ldarg(1)
                .Dup()
                .Stloc(localCtx)
                .Brtrue(haveCtx)
                .Ldarg(0)
                .Ldarg(2)
                .Newobj(() => new DeserializerCtx(null, null))
                .Castclass(typeof(ITypeBinaryDeserializerContext))
                .Stloc(localCtx)
                .Mark(haveCtx);
                descriptor.GenerateLoad(il, ilGen => ilGen.Ldarg(0), ilGen => ilGen.Ldloc(localCtx), ilGen => ilGen.Ldarg(3), loadAsType);
            }
            else
            {
                descriptor.GenerateLoad(il, ilGen => ilGen.Ldarg(0), ilGen => ilGen.Ldarg(1), ilGen => ilGen.Ldarg(3), loadAsType);
            }
            if (loadAsType.IsValueType)
            {
                il.Box(loadAsType);
            }
            else if (loadAsType != typeof(object))
            {
                il.Castclass(typeof(object));
            }
            il.Ret();
            return(methodBuilder.Create());
        }
Ejemplo n.º 32
0
        Action <AbstractBufferedWriter, ITypeBinarySerializerContext, object> NewComplexSaver(ITypeDescriptor descriptor)
        {
            var method = ILBuilder.Instance.NewMethod <Action <AbstractBufferedWriter, ITypeBinarySerializerContext, object> >(descriptor.Name + "ComplexSaver");
            var il     = method.Generator;

            descriptor.GenerateSave(il, ilgen => ilgen.Ldarg(0), ilgen => ilgen.Ldarg(1), ilgen =>
            {
                ilgen.Ldarg(2);
                var type = descriptor.GetPreferedType();
                if (type != typeof(object))
                {
                    ilgen.UnboxAny(type);
                }
            }, descriptor.GetPreferedType());
            il.Ret();
            return(method.Create());
        }
Ejemplo n.º 33
0
 public Action <AbstractBufferedWriter, object> GetSimpleSaver(ITypeDescriptor descriptor)
 {
     return(_simpleSavers.GetOrAdd(descriptor, _newSimpleSaverAction));
 }
 public override IEnumerable <BindingExtensionParameter> GetExtensionParameters(ITypeDescriptor dataContext)
 {
     return(base.GetExtensionParameters(dataContext).Concat(new BindingExtensionParameter[] { new CurrentCollectionIndexExtensionParameter(), new BindingCollectionInfoExtensionParameter("_collection") }));
 }
Ejemplo n.º 35
0
 public GenericDefTypeDescriptor(ITypeDescriptor baseType, int numTypeArgs)
 {
     _baseType    = baseType;
     _numTypeArgs = numTypeArgs;
 }
Ejemplo n.º 36
0
        public override IYamlSerializable TryCreate(SerializerContext context, ITypeDescriptor typeDescriptor)
        {
            var type = typeDescriptor.Type;

            return(type == typeof(ScriptCollection) ? this : null);
        }
Ejemplo n.º 37
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DataVisitListItem"/> class.
 /// </summary>
 /// <param name="index">The index.</param>
 /// <param name="item">The item.</param>
 /// <param name="itemDescriptor">The item descriptor.</param>
 /// <exception cref="System.ArgumentNullException">
 /// list
 /// or
 /// descriptor
 /// or
 /// itemDescriptor
 /// </exception>
 public DataVisitListItem(int index, object item, ITypeDescriptor itemDescriptor) : base(item, itemDescriptor)
 {
     this.index = index;
 }
Ejemplo n.º 38
0
 public ObjectNode([NotNull] INodeBuilder nodeBuilder, object value, Guid guid, [NotNull] ITypeDescriptor descriptor, IReference reference)
     : base(nodeBuilder.SafeArgument(nameof(nodeBuilder)).NodeContainer, guid, descriptor)
 {
     if (reference is ObjectReference)
     {
         throw new ArgumentException($"An {nameof(ObjectNode)} cannot contain an {nameof(ObjectReference)}");
     }
     this.value     = value;
     ItemReferences = reference as ReferenceEnumerable;
 }
Ejemplo n.º 39
0
 /// <inheritdoc/>
 public virtual IYamlSerializable TryCreate(SerializerContext context, ITypeDescriptor typeDescriptor)
 {
     // always accept
     return(this);
 }
Ejemplo n.º 40
0
        public static async Task <EditTemplateViewModel> CreateInstanceAsync(Authentication authentication, ITypeDescriptor descriptor)
        {
            if (authentication == null)
            {
                throw new ArgumentNullException(nameof(authentication));
            }
            if (descriptor == null)
            {
                throw new ArgumentNullException(nameof(descriptor));
            }

            if (descriptor.Target is IType type)
            {
                try
                {
                    await type.Template.BeginEditAsync(authentication);

                    return(await type.Dispatcher.InvokeAsync(() =>
                    {
                        return new EditTemplateViewModel(authentication, type, type.Template);
                    }));
                }
                catch (Exception e)
                {
                    await AppMessageBox.ShowErrorAsync(e);

                    return(null);
                }
            }
            else
            {
                throw new ArgumentException("Invalid Target of Descriptor", nameof(descriptor));
            }
        }
Ejemplo n.º 41
0
        public IList <ITypeDescriptor> GetTypeHierarchy(ITypeDescriptor type)
        {
            var result = new List <ITypeDescriptor>();

            TypeSignature typeSig;

            switch (type)
            {
            // The base type of an array type signature is System.Array, so it needs a special case.
            // Get the type hierarchy of System.Array and then append the original array type sig.
            case ArrayTypeSignature _:
            case SzArrayTypeSignature _:
                result.AddRange(GetTypeHierarchy(_arrayType));
                result.Add(type);
                return(result);

            case ByReferenceTypeSignature byRef:
                result.AddRange(GetTypeHierarchy(byRef.BaseType));
//                    result.Add(byRef);
                return(result);

            // Type specification's Resolve method resolves the underlying element type.
            // We therefore need a special case here, to get the type hierarchy of the embedded signature first.
            case TypeSpecification typeSpec:
                result.AddRange(GetTypeHierarchy(typeSpec.Signature));
                result.Add(typeSpec);
                return(result);

            case GenericParameterSignature genericParam:
                // TODO: Resolve to actual generic parameter type.
                result.Add(_objectType);
                return(result);

            // No type means no hierarchy.
            case null:
                return(Array.Empty <ITypeDescriptor>());

            default:
                typeSig = type.ToTypeSignature();
                break;
            }

            var genericContext = new GenericContext(null, null);

            while (typeSig != null)
            {
                if (typeSig is GenericInstanceTypeSignature genericInstance)
                {
                    genericContext = new GenericContext(genericInstance, null);
                }

                result.Add(typeSig);

                var typeDef = typeSig.ToTypeDefOrRef().Resolve();
                if (typeDef is null)
                {
                    throw new ArgumentException(
                              $"Could not resolve type {typeSig.FullName} in {typeSig.Scope.GetAssembly()}.");
                }

                typeSig = typeDef.IsEnum
                    ? typeDef.GetEnumUnderlyingType()
                    : typeDef.BaseType?.ToTypeSignature().InstantiateGenericTypes(genericContext);
            }

            result.Reverse();
            return(result);
        }
Ejemplo n.º 42
0
        public ITypeDescriptor GetCommonBaseType(ICollection <ITypeDescriptor> types)
        {
            if (types.Count == 1)
            {
                return(types.First());
            }

            if (IsOnlyIntegral(types))
            {
                return(GetBiggestIntegralType(types));
            }

            // Strategy:
            // Get each type hierarchy, and walk from least specific (System.Object) to most specific type.
            // Break when there is a difference between two type hierarchies. This is a branch in the
            // total type hierarchy graph.

            // TODO: For now we remove interfaces from the list to increase the chance of finding a more specific
            //       common type. This can be improved.

            // Obtain all base types for all types.
            var hierarchies = types
                              .Where(t => !t.Resolve().IsInterface)
                              .Select(GetTypeHierarchy).ToList();

            if (hierarchies.Count == 0)
            {
                return(_objectType);
            }

            ITypeDescriptor commonType = _objectType;

            int currentTypeIndex = 0;

            while (hierarchies.Count > 0)
            {
                ITypeDescriptor nextType = null;

                for (int i = 0; i < hierarchies.Count; i++)
                {
                    var hierarchy = hierarchies[i];
                    if (currentTypeIndex >= hierarchy.Count)
                    {
                        // Hierarchy is out of types. We can safely ignore this hierarchy any further
                        // since up to this point, this hierarchy has been exactly the same as the other hierarchies.
                        hierarchies.RemoveAt(i);
                        i--;
                    }
                    else if (nextType == null)
                    {
                        nextType = hierarchy[currentTypeIndex];
                    }
                    else
                    {
                        // Check if the current hierarchy has branched from the other hierarchies.
                        if (hierarchy[currentTypeIndex].FullName != nextType.FullName)
                        {
                            return(commonType);
                        }
                    }
                }

                if (nextType == null)
                {
                    return(commonType);
                }

                commonType = nextType;
                currentTypeIndex++;
            }

            return(commonType);
        }
Ejemplo n.º 43
0
 public override IYamlSerializable TryCreate(Core.Yaml.Serialization.SerializerContext context, ITypeDescriptor typeDescriptor)
 {
     return(CanVisit(typeDescriptor.Type) ? this : null);
 }
Ejemplo n.º 44
0
 protected override bool CanHandle(ITypeDescriptor descriptor)
 {
     return(descriptor.Kind == TypeKind.ResultType && !descriptor.IsInterface());
 }
Ejemplo n.º 45
0
 public PlaceHolderDescriptor(ITypeDescriptor typeDesc)
 {
     TypeDesc = typeDesc;
 }
Ejemplo n.º 46
0
        protected override void Generate(
            CodeWriter writer,
            ITypeDescriptor typeDescriptor,
            out string fileName)
        {
            NamedTypeDescriptor descriptor =
                typeDescriptor as NamedTypeDescriptor ??
                throw new InvalidOperationException();

            var(classBuilder, constructorBuilder) = CreateClassBuilder();

            fileName = ResultFactoryNameFromTypeName(descriptor.Name);
            classBuilder
            .SetName(fileName)
            .AddImplements($"{TypeNames.IOperationResultDataFactory}<{descriptor.Name}>");

            constructorBuilder
            .SetTypeName(descriptor.Name)
            .SetAccessModifier(AccessModifier.Public);

            AddConstructorAssignedField(
                TypeNames.IEntityStore,
                StoreParamName,
                classBuilder,
                constructorBuilder);

            var createMethod = MethodBuilder.New()
                               .SetAccessModifier(AccessModifier.Public)
                               .SetName("Create")
                               .SetReturnType(descriptor.Name)
                               .AddParameter("dataInfo", b => b.SetType(TypeNames.IOperationResultDataInfo));

            var returnStatement = MethodCallBuilder.New()
                                  .SetPrefix("return new ")
                                  .SetMethodName(descriptor.Name);

            var ifHasCorrectType = IfBuilder.New()
                                   .SetCondition($"dataInfo is {ResultInfoNameFromTypeName(descriptor.Name)} info");

            foreach (PropertyDescriptor property in descriptor.Properties)
            {
                returnStatement.AddArgument(
                    BuildMapMethodCall(
                        "info",
                        property));
            }

            ifHasCorrectType.AddCode(returnStatement);
            createMethod.AddCode(ifHasCorrectType);
            createMethod.AddEmptyLine();
            createMethod.AddCode(
                $"throw new {TypeNames.ArgumentException}(\"" +
                $"{ResultInfoNameFromTypeName(descriptor.Name)} expected.\");");

            classBuilder.AddMethod(createMethod);

            var processed = new HashSet <string>();

            AddRequiredMapMethods(
                "info",
                descriptor,
                classBuilder,
                constructorBuilder,
                processed,
                true);

            CodeFileBuilder
            .New()
            .SetNamespace(descriptor.Namespace)
            .AddType(classBuilder)
            .Build(writer);
        }
Ejemplo n.º 47
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DataVisitDictionaryItem"/> class.
 /// </summary>
 /// <param name="key">The key.</param>
 /// <param name="keyDescriptor">The key descriptor.</param>
 /// <param name="value">The value.</param>
 /// <param name="valueDescriptor">The value descriptor.</param>
 public DataVisitDictionaryItem(object key, ITypeDescriptor keyDescriptor, object value, ITypeDescriptor valueDescriptor) : base(value, valueDescriptor)
 {
     if (keyDescriptor == null)
     {
         throw new ArgumentNullException("keyDescriptor");
     }
     this.key           = key;
     this.keyDescriptor = keyDescriptor;
 }
        public override IYamlSerializable TryCreate(SerializerContext context, [NotNull] ITypeDescriptor typeDescriptor)
        {
            var type = typeDescriptor.Type;

            return(type == typeof(SettingsDictionary) ? this : null);
        }
 public override ITypeDescriptor?GetChildDataContextType(ITypeDescriptor dataContext, IDataContextStack controlContextStack, IAbstractControl control, IPropertyDescriptor?property = null)
 {
     return(TypeDescriptorUtils.GetCollectionItemType(dataContext));
 }
Ejemplo n.º 50
0
        /// <inheritdoc/>
        public virtual IContent CreateObjectContent(INodeBuilder nodeBuilder, object obj, ITypeDescriptor descriptor, bool isPrimitive)
        {
            var reference = nodeBuilder.CreateReferenceForNode(descriptor.Type, obj) as ReferenceEnumerable;

            return(new ObjectContent(obj, descriptor, isPrimitive, reference));
        }
Ejemplo n.º 51
0
 public Action <object, IDescriptorSerializerLiteContext> GetNewDescriptorSaver(ITypeDescriptor descriptor)
 {
     return(_newDescriptorSavers.GetOrAdd(descriptor, _newDescriptorSaverFactoryAction));
 }
Ejemplo n.º 52
0
 /// <inheritdoc/>
 public virtual IContent CreateBoxedContent(INodeBuilder nodeBuilder, object structure, ITypeDescriptor descriptor, bool isPrimitive)
 {
     return(new BoxedContent(structure, descriptor, isPrimitive));
 }
Ejemplo n.º 53
0
 public Action <AbstractBufferedWriter, ITypeBinarySerializerContext, object> GetComplexSaver(ITypeDescriptor descriptor)
 {
     return(_complexSavers.GetOrAdd(descriptor, _newComplexSaverAction));
 }
Ejemplo n.º 54
0
 public bool Equals(ITypeDescriptor other)
 {
     return(Equals(other, new HashSet <ITypeDescriptor>(ReferenceEqualityComparer <ITypeDescriptor> .Instance)));
 }
Ejemplo n.º 55
0
 public Type LoadAsType(ITypeDescriptor descriptor, Type targetType)
 {
     return(descriptor.GetPreferedType(targetType) ?? NameToType(descriptor.Name) ?? typeof(object));
 }
Ejemplo n.º 56
0
 bool ITypeDescriptor.Equals(ITypeDescriptor other, HashSet <ITypeDescriptor> stack)
 {
     throw new InvalidOperationException();
 }
Ejemplo n.º 57
0
 public Func <AbstractBufferedReader, ITypeBinaryDeserializerContext, ITypeSerializersId2LoaderMapping, ITypeDescriptor, object> GetLoader(ITypeDescriptor descriptor)
 {
     return(_loaders.GetOrAdd(descriptor, _loaderFactoryAction));
 }
Ejemplo n.º 58
0
 bool IEquatable <ITypeDescriptor> .Equals(ITypeDescriptor other)
 {
     throw new InvalidOperationException();
 }
Ejemplo n.º 59
0
 public bool IsIntegralType(ITypeDescriptor type)
 {
     return(_integralTypes.Any(x => type.IsTypeOf(x.Namespace, x.Name)));
 }
Ejemplo n.º 60
0
 public IYamlSerializable TryCreate(SerializerContext context, ITypeDescriptor typeDescriptor)
 {
     return(CanVisit(typeDescriptor.Type) ? this : null);
 }