Beispiel #1
0
        public override void UpdateNode(INodePresenter node)
        {
            if (DictionaryDescriptor.IsDictionary(node.Type))
            {
                if (node.Type.IsGenericType)
                {
                    var genericArguments = node.Type.GetGenericArguments();
                    node.AttachedProperties.Add(DictionaryNodeKeyType, genericArguments[0]);
                }
                else
                {
                    foreach (var typeInterface in node.Type.GetInterfaces())
                    {
                        if (!typeInterface.IsGenericType || typeInterface.GetGenericTypeDefinition() != typeof(IDictionary <,>))
                        {
                            continue;
                        }

                        var genericArguments = typeInterface.GetGenericArguments();
                        node.AttachedProperties.Add(DictionaryNodeKeyType, genericArguments[0]);
                        break;
                    }
                }
            }
        }
Beispiel #2
0
        private static bool ConvertForDictionary(DictionaryDescriptor dictionaryDescriptor, ref object data)
        {
            object convertedDictionary;

            if (DictionaryDescriptor.IsDictionary(data.GetType()))
            {
                if (!TryConvertDictionaryData(data, dictionaryDescriptor, out convertedDictionary))
                {
                    return(false);
                }
            }
            else
            {
                var dataType = data.GetType();
                var key      = dataType.GetMember("Key").OfType <PropertyInfo>().FirstOrDefault()?.GetValue(data);
                if (key == null || !TypeConverterHelper.TryConvert(key, dictionaryDescriptor.KeyType, out key))
                {
                    return(false);
                }

                var value = dataType.GetMember("Value").OfType <PropertyInfo>().FirstOrDefault()?.GetValue(data);
                if (value == null || !TypeConverterHelper.TryConvert(value, dictionaryDescriptor.ValueType, out value))
                {
                    return(false);
                }

                convertedDictionary = Activator.CreateInstance(dictionaryDescriptor.Type, true);
                dictionaryDescriptor.SetValue(convertedDictionary, key, value);
            }
            data = convertedDictionary;
            return(true);
        }
		public static DictionaryAdapterMeta GetAdapterMeta(this DictionaryAdapterMeta source, Type type)
		{
			var descriptor = new DictionaryDescriptor(GetSharedBehaviors(source));
			descriptor.AddInitializers    (source.Initializers);
			descriptor.AddMetaInitializers(source.MetaInitializers);

			return source.Factory.GetAdapterMeta(type, descriptor);
		}	
Beispiel #4
0
            public override void VisitDictionaryKeyValue(object dictionaryObj, DictionaryDescriptor descriptor, object key, ITypeDescriptor keyDescriptor, object value, ITypeDescriptor valueDescriptor)
            {
                base.VisitDictionaryKeyValue(dictionaryObj, descriptor, key, keyDescriptor, value, valueDescriptor);
                var assetReference    = value as AssetReference;
                var assetBase         = value as AssetBase;
                var attachedReference = value != null?AttachedReferenceManager.GetAttachedReference(value) : null;

                if (assetReference != null)
                {
                    AddLink(assetReference,
                            (guid, location) =>
                    {
                        var newValue = AssetReference.New(descriptor.ValueType, guid.HasValue ? guid.Value : assetReference.Id, location);
                        descriptor.SetValue(dictionaryObj, key, newValue);
                        return(newValue);
                    });
                }
                else if (assetBase != null)
                {
                    AddLink(assetBase,
                            (guid, location) =>
                    {
                        var newValue = new AssetBase(location, assetBase.Asset);
                        descriptor.SetValue(dictionaryObj, key, newValue);
                        return(newValue);
                    });
                }
                else if (attachedReference != null)
                {
                    AddLink(new AttachedContentReference(attachedReference),
                            (guid, location) =>
                    {
                        object newValue = guid.HasValue && guid.Value != Guid.Empty ? AttachedReferenceManager.CreateSerializableVersion(descriptor.ValueType, guid.Value, location) : null;
                        descriptor.SetValue(dictionaryObj, key, newValue);
                        return(newValue);
                    });
                }
                else if (value is UFile)
                {
                    AddLink(value,
                            (guid, location) =>
                    {
                        var newValue = new UFile(location);
                        descriptor.SetValue(dictionaryObj, key, newValue);
                        return(newValue);
                    });
                }
                else if (value is UDirectory)
                {
                    AddLink(value,
                            (guid, location) =>
                    {
                        var newValue = new UDirectory(location);
                        descriptor.SetValue(dictionaryObj, key, newValue);
                        return(newValue);
                    });
                }
            }
Beispiel #5
0
        public static DictionaryAdapterMeta GetAdapterMeta(this DictionaryAdapterMeta source, Type type)
        {
            var descriptor = new DictionaryDescriptor(GetSharedBehaviors(source));

            descriptor.AddInitializers(source.Initializers);
            descriptor.AddMetaInitializers(source.MetaInitializers);

            return(source.Factory.GetAdapterMeta(type, descriptor));
        }
        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);
        }
		public static object CreateChildAdapter(this IDictionaryAdapter parent, Type type, XmlAdapter adapter, IDictionary dictionary)
		{
			if (null == dictionary)
				dictionary = new Hashtable();

			var descriptor = new DictionaryDescriptor(GetSharedBehaviors(parent.Meta));
		    parent.This.Descriptor.CopyBehaviors(descriptor);
		    descriptor.AddBehavior(adapter);

		    return parent.This.Factory.GetAdapter(type, dictionary, descriptor);
		}
Beispiel #8
0
 public override void VisitDictionary(object dictionary, DictionaryDescriptor descriptor)
 {
     if (ShouldGenerateItemIdCollection(dictionary))
     {
         var itemIds = CollectionItemIdHelper.GetCollectionItemIds(dictionary);
         foreach (var element in descriptor.GetEnumerator(dictionary))
         {
             itemIds.Add(element.Key, ItemId.New());
         }
     }
 }
 /// <inheritdoc/>
 public override void VisitDictionary(object dictionary, DictionaryDescriptor descriptor)
 {
     if (!IsPrimitiveType(descriptor.KeyType))
     {
         return; // unsupported dictionary, skip this (don't crash loading the project though, geez!)
     }
     // Don't visit items unless they are primitive or enumerable (collections within collections)
     if (IsCollection(descriptor.ValueType))
     {
         base.VisitDictionary(dictionary, descriptor);
     }
 }
Beispiel #10
0
        public override void VisitDictionaryKeyValue(object dictionary, DictionaryDescriptor descriptor, object key, ITypeDescriptor keyDescriptor, object value, ITypeDescriptor valueDescriptor)
        {
            var node = stackItems.Peek();
            // TODO modify DataVisitorBase to allow only IDictionary?
            var newNode = new DataVisitDictionaryItem(key, keyDescriptor, value, valueDescriptor);

            AddItem(node, newNode);

            stackItems.Push(newNode);
            base.VisitDictionaryKeyValue(dictionary, descriptor, key, keyDescriptor, value, valueDescriptor);
            stackItems.Pop();
        }
            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);
            }
        /// <inheritdoc/>
        public override void VisitDictionary(object dictionary, DictionaryDescriptor descriptor)
        {
            if (!IsPrimitiveType(descriptor.KeyType))
            {
                throw new InvalidOperationException("The type of dictionary key must be a primary type.");
            }

            // Don't visit items unless they are primitive or enumerable (collections within collections)
            if (IsPrimitiveType(descriptor.ValueType, false) || IsEnumerable(descriptor.ValueType))
            {
                base.VisitDictionary(dictionary, descriptor);
            }
        }
 public override void VisitDictionary(object dictionary, DictionaryDescriptor descriptor)
 {
     CollectionItemIdentifiers itemIds;
     if (inNonIdentifiableType == 0 && !CollectionItemIdHelper.TryGetCollectionItemIds(dictionary, out itemIds))
     {
         itemIds = CollectionItemIdHelper.GetCollectionItemIds(dictionary);
         foreach (var element in descriptor.GetEnumerator(dictionary))
         {
             itemIds.Add(element.Key, ItemId.New());
         }
     }
     base.VisitDictionary(dictionary, descriptor);
 }
 /// <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);
     }
 }
            public override void VisitDictionaryKeyValue(object dictionaryObj, DictionaryDescriptor descriptor, object key, ITypeDescriptor keyDescriptor, object value, ITypeDescriptor valueDescriptor)
            {
                base.VisitDictionaryKeyValue(dictionaryObj, descriptor, key, keyDescriptor, value, valueDescriptor);
                var assetReference = value as AssetReference;

                if (assetReference != null)
                {
                    AddLink(assetReference,
                            (guid, location) =>
                    {
                        var newValue = AssetReference.New(descriptor.ValueType, guid.HasValue ? guid.Value : assetReference.Id, location);
                        descriptor.SetValue(dictionaryObj, key, newValue);
                        return(newValue);
                    });
                }
                else
                {
                    var assetBase = value as AssetBase;
                    if (assetBase != null)
                    {
                        AddLink(assetBase,
                                (guid, location) =>
                        {
                            var newValue = new AssetBase(location, assetBase.Asset);
                            descriptor.SetValue(dictionaryObj, key, newValue);
                            return(newValue);
                        });
                    }
                    else if (value is UFile)
                    {
                        AddLink(value,
                                (guid, location) =>
                        {
                            var newValue = new UFile(location);
                            descriptor.SetValue(dictionaryObj, key, newValue);
                            return(newValue);
                        });
                    }
                    else if (value is UDirectory)
                    {
                        AddLink(value,
                                (guid, location) =>
                        {
                            var newValue = new UDirectory(location);
                            descriptor.SetValue(dictionaryObj, key, newValue);
                            return(newValue);
                        });
                    }
                }
            }
 /// <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);
     }
 }
Beispiel #17
0
        public static object CreateChildAdapter(this IDictionaryAdapter parent, Type type, XmlAdapter adapter, IDictionary dictionary)
        {
            if (null == dictionary)
            {
                dictionary = new Hashtable();
            }

            var descriptor = new DictionaryDescriptor(GetSharedBehaviors(parent.Meta));

            parent.This.Descriptor.CopyBehaviors(descriptor);
            descriptor.AddBehavior(adapter);

            return(parent.This.Factory.GetAdapter(type, dictionary, descriptor));
        }
        public override void VisitDictionary(object dictionary, DictionaryDescriptor descriptor)
        {
            CollectionItemIdentifiers itemIds;

            if (inNonIdentifiableType == 0 && !CollectionItemIdHelper.TryGetCollectionItemIds(dictionary, out itemIds))
            {
                itemIds = CollectionItemIdHelper.GetCollectionItemIds(dictionary);
                foreach (var element in descriptor.GetEnumerator(dictionary))
                {
                    itemIds.Add(element.Key, ItemId.New());
                }
            }
            base.VisitDictionary(dictionary, descriptor);
        }
        /// <summary>
        /// Initialize the tests.
        /// </summary>
        public virtual void Initialize()
        {
            TypeFactory = new TypeDescriptorFactory();
            var myClassDesc = TypeFactory.Find(typeof(MyClass));
            var myStructDesc = TypeFactory.Find(typeof(MyStruct));
            ListClassDesc = (CollectionDescriptor)TypeFactory.Find(typeof(List<MyClass>));
            MapClassDesc = (DictionaryDescriptor)TypeFactory.Find(typeof(Dictionary<string, MyClass>));

            MemberValue = myClassDesc.Members.FirstOrDefault(member => member.Name == "Value");
            MemberSub = myClassDesc.Members.FirstOrDefault(member => member.Name == "Sub");
            MemberStruct = myClassDesc.Members.FirstOrDefault(member => member.Name == "Struct");
            MemberSubs = myClassDesc.Members.FirstOrDefault(member => member.Name == "Subs");
            MemberMaps = myClassDesc.Members.FirstOrDefault(member => member.Name == "Maps");
            MemberX = myStructDesc.Members.FirstOrDefault(member => member.Name == "X");
            MemberClass = myStructDesc.Members.FirstOrDefault(member => member.Name == "Class");
        }
Beispiel #20
0
        internal static NodeIndex?GenerateGenericKey(object dictionary, ITypeDescriptor descriptor, object baseValue)
        {
            // TODO: use a dialog service and popup a message when the given key is invalid
            DictionaryDescriptor dictionaryDescriptor = descriptor as DictionaryDescriptor;
            Type   keyType = dictionaryDescriptor.KeyType;
            object key     = keyType.Default();

            key = TypeDescriptor.GetConverter(keyType).ConvertFrom(baseValue);

            if (!dictionaryDescriptor.ContainsKey(dictionary, key))
            {
                return(new NodeIndex(key));
            }

            return(null);
        }
Beispiel #21
0
            public override void VisitDictionaryKeyValue(object dictionaryObj, DictionaryDescriptor descriptor, object key, ITypeDescriptor keyDescriptor, object value, ITypeDescriptor valueDescriptor)
            {
                base.VisitDictionaryKeyValue(dictionaryObj, descriptor, key, keyDescriptor, value, valueDescriptor);
                var assetReference    = value as AssetReference;
                var attachedReference = AttachedReferenceManager.GetAttachedReference(value);

                if (assetReference != null)
                {
                    AddLink(assetReference,
                            (guid, location) =>
                    {
                        var newValue = AssetReference.New(guid ?? assetReference.Id, location);
                        descriptor.SetValue(dictionaryObj, key, newValue);
                        return(newValue);
                    });
                }
                else if (attachedReference != null)
                {
                    AddLink(attachedReference,
                            (guid, location) =>
                    {
                        object newValue = guid.HasValue && guid.Value != AssetId.Empty ? AttachedReferenceManager.CreateProxyObject(descriptor.ValueType, guid.Value, location) : null;
                        descriptor.SetValue(dictionaryObj, key, newValue);
                        return(newValue);
                    });
                }
                else if (value is UFile)
                {
                    AddLink(value,
                            (guid, location) =>
                    {
                        var newValue = new UFile(location);
                        descriptor.SetValue(dictionaryObj, key, newValue);
                        return(newValue);
                    });
                }
                else if (value is UDirectory)
                {
                    AddLink(value,
                            (guid, location) =>
                    {
                        var newValue = new UDirectory(location);
                        descriptor.SetValue(dictionaryObj, key, newValue);
                        return(newValue);
                    });
                }
            }
Beispiel #22
0
        /// <summary>
        /// Initialize the tests.
        /// </summary>
        public virtual void Initialize()
        {
            TypeFactory = new TypeDescriptorFactory();
            var myClassDesc  = TypeFactory.Find(typeof(MyClass));
            var myStructDesc = TypeFactory.Find(typeof(MyStruct));

            ListClassDesc = (CollectionDescriptor)TypeFactory.Find(typeof(List <MyClass>));
            MapClassDesc  = (DictionaryDescriptor)TypeFactory.Find(typeof(Dictionary <string, MyClass>));

            MemberValue  = (IMemberDescriptor)myClassDesc.Members.FirstOrDefault(member => member.Name == "Value");
            MemberSub    = (IMemberDescriptor)myClassDesc.Members.FirstOrDefault(member => member.Name == "Sub");
            MemberStruct = (IMemberDescriptor)myClassDesc.Members.FirstOrDefault(member => member.Name == "Struct");
            MemberSubs   = (IMemberDescriptor)myClassDesc.Members.FirstOrDefault(member => member.Name == "Subs");
            MemberMaps   = (IMemberDescriptor)myClassDesc.Members.FirstOrDefault(member => member.Name == "Maps");
            MemberX      = (IMemberDescriptor)myStructDesc.Members.FirstOrDefault(member => member.Name == "X");
            MemberClass  = (IMemberDescriptor)myStructDesc.Members.FirstOrDefault(member => member.Name == "Class");
        }
Beispiel #23
0
        private Diff3Node DiffNodeWithUniformType(DataVisitNode baseNode, DataVisitNode asset1Node, DataVisitNode asset2Node)
        {
            var baseNodeDesc   = GetNodeDescription(baseNode);
            var asset1NodeDesc = GetNodeDescription(asset1Node);
            var asset2NodeDesc = GetNodeDescription(asset2Node);

            var node = baseNode ?? asset1Node ?? asset2Node;
            var type = baseNodeDesc.Type ?? asset1NodeDesc.Type ?? asset2NodeDesc.Type;

            var diff3 = new Diff3Node(baseNode, asset1Node, asset2Node)
            {
                InstanceType = type
            };

            if (type == null)
            {
                // All nodes are null. This should only happen as part of a temporary diff in DiffNode()
                diff3.ChangeType = Diff3ChangeType.None;
            }
            else if (IsComparableType(node.HasMembers, type))
            {
                DiffValue(diff3, ref baseNodeDesc, ref asset1NodeDesc, ref asset2NodeDesc);
            }
            else
            {
                DiffMembers(diff3, baseNode, asset1Node, asset2Node);

                if (DictionaryDescriptor.IsDictionary(type))
                {
                    DiffDictionary(diff3, baseNode, asset1Node, asset2Node);
                }
                else if (CollectionDescriptor.IsCollection(type))
                {
                    DiffCollection(diff3, baseNode, asset1Node, asset2Node);
                }
                else if (type.IsArray)
                {
                    DiffArray(diff3, baseNode, asset1Node, asset2Node);
                }
            }

            return(diff3);
        }
Beispiel #24
0
        public void TestDictionaryDescriptor()
        {
            var attributeRegistry = new AttributeRegistry();
            var descriptor        = new DictionaryDescriptor(attributeRegistry, typeof(Dictionary <int, string>), false);

            descriptor.Initialize();

            Assert.AreEqual(0, descriptor.Count);
            Assert.True(descriptor.IsPureDictionary);
            Assert.AreEqual(typeof(int), descriptor.KeyType);
            Assert.AreEqual(typeof(string), descriptor.ValueType);

            descriptor = new DictionaryDescriptor(attributeRegistry, typeof(NonPureDictionary), false);
            descriptor.Initialize();
            Assert.AreEqual(1, descriptor.Count);
            Assert.False(descriptor.IsPureDictionary);
            Assert.AreEqual(typeof(float), descriptor.KeyType);
            Assert.AreEqual(typeof(object), descriptor.ValueType);
        }
        /// <inheritdoc/>
        protected override void ExecuteSync(INodePresenter nodePresenter, object parameter, object preExecuteResult)
        {
            var currentValue   = nodePresenter.Value;
            var collectionNode = ((ItemNodePresenter)nodePresenter).OwnerCollection;

            DictionaryDescriptor DictionaryDescriptor = collectionNode.Descriptor as DictionaryDescriptor;
            Type      keyType = DictionaryDescriptor.KeyType;
            NodeIndex?newName = null;

            if (TypeDescriptor.GetConverter(keyType).CanConvertFrom(typeof(string)))
            {
                newName = AddPrimitiveKeyCommand.GenerateGenericKey(collectionNode.Value, collectionNode.Descriptor, parameter);
            }

            if (newName != null)
            {
                collectionNode.RemoveItem(nodePresenter.Value, nodePresenter.Index);

                collectionNode.AddItem(currentValue, newName.Value);
            }
        }
        public void TestDictionaryDescriptor()
        {
            var attributeRegistry = new AttributeRegistry();
            var factory           = new TypeDescriptorFactory(attributeRegistry);
            var descriptor        = new DictionaryDescriptor(factory, typeof(Dictionary <int, string>), false,
                                                             new DefaultNamingConvention());

            descriptor.Initialize(new DefaultKeyComparer());

            Assert.AreEqual(0, descriptor.Count);
            Assert.True(descriptor.IsPureDictionary);
            Assert.AreEqual(typeof(int), descriptor.KeyType);
            Assert.AreEqual(typeof(string), descriptor.ValueType);

            descriptor = new DictionaryDescriptor(factory, typeof(NonPureDictionary), false,
                                                  new DefaultNamingConvention());
            descriptor.Initialize(new DefaultKeyComparer());
            Assert.AreEqual(1, descriptor.Count);
            Assert.False(descriptor.IsPureDictionary);
            Assert.AreEqual(typeof(float), descriptor.KeyType);
            Assert.AreEqual(typeof(object), descriptor.ValueType);
        }
Beispiel #27
0
        private Diff3Node DiffNodeWithUniformType(DataVisitNode baseNode, DataVisitNode asset1Node, DataVisitNode asset2Node)
        {
            var baseNodeDesc   = GetNodeDescription(baseNode);
            var asset1NodeDesc = GetNodeDescription(asset1Node);
            var asset2NodeDesc = GetNodeDescription(asset2Node);

            var node = baseNode ?? asset1Node ?? asset2Node;
            var type = baseNodeDesc.Type ?? asset1NodeDesc.Type ?? asset2NodeDesc.Type;

            var diff3 = new Diff3Node(baseNode, asset1Node, asset2Node)
            {
                InstanceType = type
            };

            if (IsComparableType(node.HasMembers, type))
            {
                DiffValue(diff3, ref baseNodeDesc, ref asset1NodeDesc, ref asset2NodeDesc);
            }
            else
            {
                DiffMembers(diff3, baseNode, asset1Node, asset2Node);

                if (DictionaryDescriptor.IsDictionary(type))
                {
                    DiffDictionary(diff3, baseNode, asset1Node, asset2Node);
                }
                else if (CollectionDescriptor.IsCollection(type))
                {
                    DiffCollection(diff3, baseNode, asset1Node, asset2Node);
                }
                else if (type.IsArray)
                {
                    DiffArray(diff3, baseNode, asset1Node, asset2Node);
                }
            }

            return(diff3);
        }
Beispiel #28
0
        /// <inheritdoc/>
        public override void VisitDictionary(object dictionary, DictionaryDescriptor descriptor)
        {
            var containerNode = GetContextNode();

            if (!IsPrimitiveType(descriptor.KeyType))
            {
                throw new QuantumConsistencyException("A dictionary with a primary type for keys", null, "A dictionary [{0}] for keys", descriptor.KeyType.FullName, containerNode);
            }

            // TODO: an access to the count function in DictionaryDescriptor
            var count         = ((IEnumerable)dictionary).Cast <object>().Count();
            var referenceInfo = GetReferenceInfo(descriptor.Type, dictionary);

            if (referenceInfo != null && referenceInfo.EnumerableCount != count)
            {
                throw new QuantumConsistencyException("A node with an EnumerableReference containing [{0}] items", referenceInfo.EnumerableCount.ToStringSafe(), "A node with an EnumerableReference containing [{0}] items", count.ToStringSafe(), containerNode);
            }

            if (IsPrimitiveType(descriptor.ValueType, false) || IsEnumerable(descriptor.ValueType))
            {
                base.VisitDictionary(dictionary, descriptor);
            }
        }
Beispiel #29
0
 private static bool HasCollectionReference(Type type)
 {
     return type.IsArray || CollectionDescriptor.IsCollection(type) || DictionaryDescriptor.IsDictionary(type);
 }
Beispiel #30
0
        private Diff3Node DiffNode(DataVisitNode baseNode, DataVisitNode asset1Node, DataVisitNode asset2Node)
        {
            var diff3 = new Diff3Node(baseNode, asset1Node, asset2Node);

            var baseNodeDesc   = GetNodeDescription(baseNode);
            var asset1NodeDesc = GetNodeDescription(asset1Node);
            var asset2NodeDesc = GetNodeDescription(asset2Node);

            bool hasMembers = false;

            Type type     = null;
            Type nodeType = null;

            if (baseNodeDesc.Type != null)
            {
                type       = baseNodeDesc.Type;
                hasMembers = baseNode.HasMembers;
                nodeType   = baseNode.GetType();
            }

            if (asset1NodeDesc.Type != null)
            {
                if (type == null)
                {
                    type       = asset1NodeDesc.Type;
                    hasMembers = asset1Node.HasMembers;
                    nodeType   = asset1Node.GetType();
                }
                else
                {
                    if (nodeType != asset1Node.GetType())
                    {
                        diff3.ChangeType = Diff3ChangeType.InvalidNodeType;
                        return(diff3);
                    }

                    if (type != asset1NodeDesc.Type)
                    {
                        diff3.ChangeType = Diff3ChangeType.ConflictType;
                        return(diff3);
                    }
                }
            }

            if (asset2NodeDesc.Type != null)
            {
                if (type == null)
                {
                    type       = asset2NodeDesc.Type;
                    hasMembers = asset2Node.HasMembers;
                }
                else
                {
                    if (nodeType != asset2Node.GetType())
                    {
                        diff3.ChangeType = Diff3ChangeType.InvalidNodeType;
                        return(diff3);
                    }

                    if (type != asset2NodeDesc.Type)
                    {
                        diff3.ChangeType = Diff3ChangeType.ConflictType;
                        return(diff3);
                    }
                }
            }

            if (type == null)
            {
                return(diff3);
            }

            diff3.InstanceType = type;

            // A comparable type doesn't have any members, is not a collection or dictionary or array.
            bool isComparableType = !hasMembers && !CollectionDescriptor.IsCollection(type) && !DictionaryDescriptor.IsDictionary(type) && !type.IsArray;

            if (isComparableType)
            {
                DiffValue(diff3, ref baseNodeDesc, ref asset1NodeDesc, ref asset2NodeDesc);
                return(diff3);
            }

            // Diff members
            DiffMembers(diff3, baseNode, asset1Node, asset2Node);

            if (DictionaryDescriptor.IsDictionary(type))
            {
                DiffDictionary(diff3, baseNode, asset1Node, asset2Node);
            }
            else if (CollectionDescriptor.IsCollection(type))
            {
                DiffCollection(diff3, baseNode, asset1Node, asset2Node);
            }
            else if (type.IsArray)
            {
                DiffArray(diff3, baseNode, asset1Node, asset2Node);
            }

            return(diff3);
        }
Beispiel #31
0
        private static bool IsComparableType(bool hasMembers, Type type)
        {
            // A comparable type doesn't have any members, is not a collection or dictionary or array.
            bool isComparableType = !hasMembers && !CollectionDescriptor.IsCollection(type) && !DictionaryDescriptor.IsDictionary(type) && !type.IsArray;

            return(isComparableType);
        }
 public override void VisitDictionaryKeyValue(object dictionaryObj, DictionaryDescriptor descriptor, object key, ITypeDescriptor keyDescriptor, object value, ITypeDescriptor valueDescriptor)
 {
     base.VisitDictionaryKeyValue(dictionaryObj, descriptor, key, keyDescriptor, value, valueDescriptor);
     var assetReference = value as AssetReference;
     var assetBase = value as AssetBase;
     var attachedReference = value != null ? AttachedReferenceManager.GetAttachedReference(value) : null;
     if (assetReference != null)
     {
         AddLink(assetReference,
             (guid, location) =>
             {
                 var newValue = AssetReference.New(descriptor.ValueType, guid.HasValue ? guid.Value : assetReference.Id, location);
                 descriptor.SetValue(dictionaryObj, key, newValue);
                 return newValue;
             });
     }
     else if (assetBase != null)
     {
         AddLink(assetBase,
             (guid, location) =>
             {
                 var newValue = new AssetBase(location, assetBase.Asset);
                 descriptor.SetValue(dictionaryObj, key, newValue);
                 return newValue;
             });
     }
     else if (attachedReference != null)
     {
         AddLink(attachedReference,
             (guid, location) =>
             {
                 object newValue = guid.HasValue && guid.Value != Guid.Empty ? AttachedReferenceManager.CreateSerializableVersion(descriptor.ValueType, guid.Value, location) : null;
                 descriptor.SetValue(dictionaryObj, key, newValue);
                 return newValue;
             });
     }
     else if (value is UFile)
     {
         AddLink(value,
             (guid, location) =>
             {
                 var newValue = new UFile(location);
                 descriptor.SetValue(dictionaryObj, key, newValue);
                 return newValue;
             });
     }
     else if (value is UDirectory)
     {
         AddLink(value,
             (guid, location) =>
             {
                 var newValue = new UDirectory(location);
                 descriptor.SetValue(dictionaryObj, key, newValue);
                 return newValue;
             });
     }
 }
        /// <inheritdoc/>
        public override void VisitDictionary(object dictionary, DictionaryDescriptor descriptor)
        {
            var containerNode = GetContextNode();

            if (!IsPrimitiveType(descriptor.KeyType))
                throw new QuantumConsistencyException("A dictionary with a primary type for keys", null, "A dictionary [{0}] for keys", descriptor.KeyType.FullName, containerNode);

            // TODO: an access to the count function in DictionaryDescriptor
            var count = ((IEnumerable)dictionary).Cast<object>().Count();
            var referenceInfo = GetReferenceInfo(descriptor.Type, dictionary);
            if (referenceInfo != null && referenceInfo.EnumerableCount != count)
                throw new QuantumConsistencyException("A node with an EnumerableReference containing [{0}] items", referenceInfo.EnumerableCount.ToStringSafe(), "A node with an EnumerableReference containing [{0}] items", count.ToStringSafe(), containerNode);

            if (IsPrimitiveType(descriptor.ValueType, false) || IsEnumerable(descriptor.ValueType))
            {
                base.VisitDictionary(dictionary, descriptor);
            }
        }
Beispiel #34
0
        /// <summary>
        /// Tries to convert the <paramref name="sourceDictionary"/> to the type described by <paramref name="dictionaryDescriptor"/>.
        /// </summary>
        /// <param name="sourceDictionary"></param>
        /// <param name="dictionaryDescriptor"></param>
        /// <param name="convertedDictionary"></param>
        /// <returns><c>true</c> if the <paramref name="sourceDictionary"/> could be converted to the type described by <paramref name="dictionaryDescriptor"/>; otherwise, <c>false</c>.</returns>
        private static bool TryConvertDictionaryData([NotNull] object sourceDictionary, [NotNull] DictionaryDescriptor dictionaryDescriptor, out object convertedDictionary)
        {
            try
            {
                var sourceDictionaryType = sourceDictionary.GetType();
                // Already same type
                if (dictionaryDescriptor.Type == sourceDictionary.GetType())
                {
                    convertedDictionary = sourceDictionary;
                    return(true);
                }

                convertedDictionary = Activator.CreateInstance(dictionaryDescriptor.Type, true);
                var sourceDictionaryDescriptor = (DictionaryDescriptor)TypeDescriptorFactory.Default.Find(sourceDictionaryType);
                foreach (var k in sourceDictionaryDescriptor.GetKeys(sourceDictionary))
                {
                    var key = k;
                    if (!TypeConverterHelper.TryConvert(key, dictionaryDescriptor.KeyType, out key))
                    {
                        // (optimistic) try to convert the remaining items
                        continue;
                    }
                    var value = sourceDictionaryDescriptor.GetValue(sourceDictionary, k);
                    if (!TypeConverterHelper.TryConvert(value, dictionaryDescriptor.ValueType, out value))
                    {
                        // (optimistic) try to convert the remaining items
                        continue;
                    }
                    dictionaryDescriptor.SetValue(convertedDictionary, key, value);
                }
                return(dictionaryDescriptor.GetKeys(convertedDictionary)?.Count > 0);
            }
            catch (InvalidCastException) { }
            catch (InvalidOperationException) { }
            catch (FormatException) { }
            catch (NotSupportedException) { }
            catch (Exception ex) when(ex.InnerException is InvalidCastException)
            {
            }
            catch (Exception ex) when(ex.InnerException is InvalidOperationException)
            {
            }
            catch (Exception ex) when(ex.InnerException is FormatException)
            {
            }
            catch (Exception ex) when(ex.InnerException is NotSupportedException)
            {
            }

            // Incompatible type and no conversion available
            convertedDictionary = null;
            return(false);
        }
Beispiel #35
0
        private bool IsComparableType(bool hasMembers, Type type)
        {
            // A comparable type doesn't have any members, is not a collection or dictionary or array.
            bool isComparableType = ((UseOverrideMode && type.IsValueType) || !hasMembers) && !CollectionDescriptor.IsCollection(type) && !DictionaryDescriptor.IsDictionary(type) && !type.IsArray;

            return(isComparableType);
        }
Beispiel #36
0
 public override void VisitDictionary(object dictionary, DictionaryDescriptor descriptor)
 {
     Fixup(dictionary);
     base.VisitDictionary(dictionary, descriptor);
 }
Beispiel #37
0
 private static bool HasCollectionReference(Type type)
 {
     return(type.IsArray || ListDescriptor.IsList(type) || DictionaryDescriptor.IsDictionary(type) || SetDescriptor.IsSet(type) || OldCollectionDescriptor.IsCollection(type));
 }
        public override void VisitDictionaryKeyValue(object dictionary, DictionaryDescriptor descriptor, object key, ITypeDescriptor keyDescriptor, object value, ITypeDescriptor valueDescriptor)
        {
            var node = stackItems.Peek();
            // TODO modify DataVisitorBase to allow only IDictionary?
            var newNode = new DataVisitDictionaryItem(key, keyDescriptor, value, valueDescriptor);
            AddItem(node, newNode);

            stackItems.Push(newNode);
            base.VisitDictionaryKeyValue(dictionary, descriptor, key, keyDescriptor, value, valueDescriptor);
            stackItems.Pop();
        }
Beispiel #39
0
 public virtual void VisitDictionaryKeyValue(object dictionary, DictionaryDescriptor descriptor, object key, ITypeDescriptor keyDescriptor, object value, ITypeDescriptor valueDescriptor)
 {
     Visit(key, keyDescriptor);
     Visit(value, valueDescriptor);
 }
		public void CanFetchProperties()
		{
			var getter = new CustomGetter();
			var custom = new DictionaryDescriptor().AddGetter(getter);
			factory.GetAdapter(typeof(IPhone), dictionary, custom);

			Assert.AreEqual(1, getter.PropertiesFetched.Count);

			Assert.AreEqual(1, getter.PropertiesFetched.Count);
			Assert.IsTrue(getter.PropertiesFetched.Contains("Number"));
		}
Beispiel #41
0
        public virtual void VisitDictionary(object dictionary, DictionaryDescriptor descriptor)
        {
            foreach (var keyValue in descriptor.GetEnumerator(dictionary))
            {
                var key = keyValue.Key;
                var keyDescriptor = TypeDescriptorFactory.Find(keyValue.Key?.GetType() ?? descriptor.KeyType);
                var value = keyValue.Value;
                var valueDescriptor = TypeDescriptorFactory.Find(keyValue.Value?.GetType() ?? descriptor.ValueType);

                CurrentPath.Push(descriptor, key);
                VisitDictionaryKeyValue(dictionary, descriptor, key, keyDescriptor, value, valueDescriptor);
                CurrentPath.Pop();
            }
        }
Beispiel #42
0
        /// <inheritdoc/>
        public override void VisitDictionary(object dictionary, DictionaryDescriptor descriptor)
        {
            if (!IsPrimitiveType(descriptor.KeyType))
                throw new InvalidOperationException("The type of dictionary key must be a primary type.");

            // Don't visit items unless they are primitive or enumerable (collections within collections)
            if (IsPrimitiveType(descriptor.ValueType, false) || IsCollection(descriptor.ValueType))
            {
                base.VisitDictionary(dictionary, descriptor);
            }
        }
Beispiel #43
0
        // TODO: replace targetNode & index arguments by a NodeAccessor
        private void Paste([NotNull] IPasteItem pasteResultItem, IGraphNode targetNode, NodeIndex index, bool replace)
        {
            if (pasteResultItem?.Data == null)
            {
                throw new ArgumentNullException(nameof(pasteResultItem));
            }
            if (targetNode == null)
            {
                throw new ArgumentNullException(nameof(targetNode));
            }

            var copiedData           = pasteResultItem.Data;
            var copiedDataType       = copiedData.GetType();
            var copiedDataDescriptor = TypeDescriptorFactory.Default.Find(copiedDataType);
            var memberNode           = targetNode as IMemberNode;

            // We're pasting in a node that is not a collection (nor a dictionary), let's just do a member update
            if (!CollectionDescriptor.IsCollection(targetNode.Type))
            {
                if (CanUpdateMember(memberNode, copiedData))
                {
                    UpdateMember(memberNode, copiedData);
                }
                return;
            }

            // Check if target collection/dictionary is null.
            if (memberNode != null && memberNode.Target == null)
            {
                // Check if the type has a public constructor with no arguments
                if (targetNode.Type.GetConstructor(Type.EmptyTypes) != null)
                {
                    // Instantiate a new collection (based on node type)
                    memberNode.Update(Activator.CreateInstance(targetNode.Type));
                }
            }

            var collectionNode = memberNode != null ? memberNode.Target : (IObjectNode)targetNode;

            // The collection/dictionary is null and we couldn't construct it, let's stop here
            if (collectionNode == null)
            {
                return;
            }

            // We're pasting in a dictionary. In this case the only accepted input is a (compatible) dictionary
            if (copiedDataDescriptor.Category == DescriptorCategory.Dictionary && DictionaryDescriptor.IsDictionary(targetNode.Type))
            {
                var copiedDataDictionaryDescriptor = (DictionaryDescriptor)copiedDataDescriptor;
                var existingKeys = collectionNode.Indices.ToList();
                if (replace)
                {
                    var keys = ((DictionaryDescriptor)collectionNode.Descriptor).GetKeys(collectionNode.Retrieve()).Cast <object>().ToList();
                    if (index.IsEmpty)
                    {
                        // If this operation is a replace of the whole dictionary, let's first clear it
                        foreach (var key in keys)
                        {
                            var itemIndex = new NodeIndex(key);
                            if (CanRemoveItem(collectionNode, itemIndex))
                            {
                                var itemToRemove = targetNode.Retrieve(itemIndex);
                                collectionNode.Remove(itemToRemove, itemIndex);
                            }
                        }
                    }
                    else
                    {
                        // Otherwise, just remove the corresponding item
                        if (CanRemoveItem(collectionNode, index))
                        {
                            var itemToRemove = targetNode.Retrieve(index);
                            collectionNode.Remove(itemToRemove, index);
                        }
                    }
                }
                foreach (var kv in copiedDataDictionaryDescriptor.GetEnumerator(copiedData))
                {
                    var itemIndex = new NodeIndex(kv.Key);
                    if (existingKeys.Contains(itemIndex))
                    {
                        // Replace if the key already exists
                        if (CanReplaceItem(collectionNode, itemIndex, kv.Value))
                        {
                            ReplaceItem(collectionNode, itemIndex, kv.Value);
                        }
                    }
                    else
                    {
                        // Add if the key does not exist
                        if (CanInsertItem(collectionNode, itemIndex, kv.Value))
                        {
                            InsertItem(collectionNode, itemIndex, kv.Value);
                        }
                    }
                }
            }
            else if (targetNode.Descriptor.Category == DescriptorCategory.Collection)
            {
                var targetCollectionDescriptor = (CollectionDescriptor)targetNode.Descriptor;
                if (replace)
                {
                    // No index, we're replacing the whole collection
                    if (index.IsEmpty)
                    {
                        // First clear the collection
                        var count = targetCollectionDescriptor.GetCollectionCount(targetNode.Retrieve());
                        for (var j = count - 1; j >= 0; j--)
                        {
                            var itemIndex = new NodeIndex(j);
                            if (CanRemoveItem(collectionNode, itemIndex))
                            {
                                var itemToRemove = targetNode.Retrieve(itemIndex);
                                collectionNode.Remove(itemToRemove, itemIndex);
                            }
                        }

                        // Then add the new items
                        var i = 0;
                        foreach (var item in EnumerateItems(copiedData, copiedDataDescriptor))
                        {
                            var itemIndex = new NodeIndex(i);
                            if (CanInsertItem(collectionNode, itemIndex, item))
                            {
                                InsertItem(collectionNode, itemIndex, item);
                                i++;
                            }
                        }
                    }
                    else
                    {
                        // We're replacing a single item with a given index...
                        var  startIndex        = index.Int;
                        var  i                 = 0;
                        bool firstItemReplaced = false;
                        foreach (var item in EnumerateItems(copiedData, copiedDataDescriptor))
                        {
                            var itemIndex = new NodeIndex(startIndex + i);
                            if (!firstItemReplaced)
                            {
                                // We replace the first item.
                                if (CanReplaceItem(collectionNode, itemIndex, item))
                                {
                                    ReplaceItem(collectionNode, itemIndex, item);
                                    firstItemReplaced = true;
                                    i++;
                                }
                            }
                            else if (CanInsertItem(collectionNode, itemIndex, item))
                            {
                                // We insert the following items that have no pre-existing counter-part.
                                InsertItem(collectionNode, itemIndex, item);
                                i++;
                            }
                        }
                    }
                }
                else
                {
                    // No index, we're replacing the whole collection
                    if (index.IsEmpty)
                    {
                        // Add the new items
                        var i = targetCollectionDescriptor.GetCollectionCount(targetNode.Retrieve());
                        foreach (var item in EnumerateItems(copiedData, copiedDataDescriptor))
                        {
                            var itemIndex = new NodeIndex(i);
                            if (CanInsertItem(collectionNode, itemIndex, item))
                            {
                                InsertItem(collectionNode, itemIndex, item);
                                i++;
                            }
                        }
                    }
                    else
                    {
                        // Handling non-replacing paste
                        var i = index.Int;
                        foreach (var item in EnumerateItems(copiedData, copiedDataDescriptor))
                        {
                            // We're pasting a collection into the collection, let's add all items at the given index if provided or at the end of the collection.
                            var itemIndex = new NodeIndex(i);
                            if (CanInsertItem(collectionNode, itemIndex, item))
                            {
                                InsertItem(collectionNode, itemIndex, item);
                                i++;
                            }
                        }
                    }
                }
            }
        }
 public override void VisitDictionary(object dictionary, DictionaryDescriptor descriptor)
 {
     Fixup(dictionary);
     base.VisitDictionary(dictionary, descriptor);
 }
Beispiel #45
0
        public virtual void VisitDictionary(object dictionary, DictionaryDescriptor descriptor)
        {
            // Make a copy in case VisitCollectionItem mutates something
            var items = descriptor.GetEnumerator(dictionary).ToList();

            foreach (var keyValue in items)
            {
                var key = keyValue.Key;
                var keyDescriptor = TypeDescriptorFactory.Find(keyValue.Key?.GetType() ?? descriptor.KeyType);
                var value = keyValue.Value;
                var valueDescriptor = TypeDescriptorFactory.Find(keyValue.Value?.GetType() ?? descriptor.ValueType);

                CurrentPath.Push(descriptor, key);
                VisitDictionaryKeyValue(dictionary, descriptor, key, keyDescriptor, value, valueDescriptor);
                CurrentPath.Pop();
            }
        }
        /// <summary>
        /// Creates a type descriptor for the specified type.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <returns>An instance of type descriptor.</returns>
        protected virtual ITypeDescriptor Create(Type type)
        {
            ITypeDescriptor descriptor;
            // The order of the descriptors here is important

            if (PrimitiveDescriptor.IsPrimitive(type))
            {
                descriptor = new PrimitiveDescriptor(attributeRegistry, type);
            }
            else if (DictionaryDescriptor.IsDictionary(type)) // resolve dictionary before collections, as they are also collections
            {
                // IDictionary
                descriptor = new DictionaryDescriptor(attributeRegistry, type, emitDefaultValues);
            }
            else if (CollectionDescriptor.IsCollection(type))
            {
                // ICollection
                descriptor = new CollectionDescriptor(attributeRegistry, type, emitDefaultValues);
            }
            else if (type.IsArray)
            {
                // array[]
                descriptor = new ArrayDescriptor(attributeRegistry, type);
            }
            else if (NullableDescriptor.IsNullable(type))
            {
                descriptor = new NullableDescriptor(attributeRegistry, type);
            }
            else
            {
                // standard object (class or value type)
                descriptor = new ObjectDescriptor(attributeRegistry, type, emitDefaultValues);
            }
            return descriptor;
        }