Пример #1
0
        public void AddPart()
        {
            var currentlyBuilding = new Dictionary <Type, TypeIdentity>();
            var repository        = new PluginRepository();

            Func <Type, TypeIdentity> identityGenerator = TypeIdentityBuilder.IdentityFactory(repository, currentlyBuilding);
            PartDefinition            definition        = new PartDefinition
            {
                Identity = identityGenerator(typeof(ExportOnProperty)),
            };

            var fileInfo = new PluginFileInfo("a", DateTimeOffset.Now);

            repository.AddPart(definition, fileInfo);

            var parts = repository.Parts();

            Assert.AreEqual(1, parts.Count());
            Assert.AreSame(definition, parts.First());
            Assert.AreSame(definition, repository.Part(TypeIdentity.CreateDefinition(typeof(ExportOnProperty))));

            var files = repository.KnownPluginFiles();

            Assert.AreEqual(1, files.Count());
            Assert.AreSame(fileInfo, files.First());
        }
//        private DelayedAction timeout;

        public PartDownloader(PartDefinition definition, jQueryObject container, PartCallback onComplete, bool initializeOnComplete)
        {
            this.definition = definition;
            this.container = container;
            this.onComplete = onComplete;
            this.initializeOnComplete = initializeOnComplete;
        }
Пример #3
0
        public static CustomPartBuilder Create(Type type, PartDefinition definition)
        {
            if (string.IsNullOrEmpty(definition.ReadMethod) || string.IsNullOrEmpty(definition.WriteMethod))
            {
                throw new InvalidOperationException("Custom serialized fields must defined both 'ReadMethod' and 'WriteMethod'");
            }

            const BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;

            var readMethod = definition.Member.DeclaringType.GetMethod(definition.ReadMethod, flags, null, new[] { typeof(IPrimitiveReader) }, null);

            if (readMethod == null)
            {
                throw new InvalidOperationException(string.Format("The read method void {0}({1}) couldn't be found", definition.ReadMethod, typeof(IPrimitiveReader).Name));
            }

            var writeMethod = definition.Member.DeclaringType.GetMethod(definition.WriteMethod, flags, null, new[] { typeof(IPrimitiveWriter) }, null);

            if (writeMethod == null)
            {
                throw new InvalidOperationException(string.Format("The write method void {0}({1}) couldn't be found", definition.ReadMethod, typeof(IPrimitiveReader).Name));
            }

            return(new CustomPartBuilder
            {
                _readMethod = readMethod,
                _writeMethod = writeMethod
            });
        }
Пример #4
0
        public void RemovePluginsWithChildType()
        {
            var currentlyBuilding = new Dictionary <Type, TypeIdentity>();
            var repository        = new PluginRepository();

            Func <Type, TypeIdentity> identityGenerator = TypeIdentityBuilder.IdentityFactory(repository, currentlyBuilding);
            PartDefinition            parentDefinition  = new PartDefinition
            {
                Identity = identityGenerator(typeof(MockExportingInterfaceImplementation)),
            };

            var parentFileInfo = new PluginFileInfo("a", DateTimeOffset.Now);

            repository.AddPart(parentDefinition, parentFileInfo);

            PartDefinition childDefinition = new PartDefinition
            {
                Identity = identityGenerator(typeof(MockChildExportingInterfaceImplementation)),
            };

            var childFileInfo = new PluginFileInfo("b", DateTimeOffset.Now);

            repository.AddPart(childDefinition, childFileInfo);
            Assert.IsTrue(repository.ContainsDefinitionForType(TypeIdentity.CreateDefinition(typeof(MockExportingInterfaceImplementation))));
            Assert.IsTrue(repository.ContainsDefinitionForType(TypeIdentity.CreateDefinition(typeof(MockChildExportingInterfaceImplementation))));
            Assert.IsTrue(
                repository.IsSubTypeOf(
                    TypeIdentity.CreateDefinition(typeof(object)),
                    TypeIdentity.CreateDefinition(typeof(MockChildExportingInterfaceImplementation))));

            repository.RemovePlugins(new string[] { childFileInfo.Path });
            Assert.IsTrue(repository.ContainsDefinitionForType(TypeIdentity.CreateDefinition(typeof(MockExportingInterfaceImplementation))));
            Assert.IsFalse(repository.ContainsDefinitionForType(TypeIdentity.CreateDefinition(typeof(MockChildExportingInterfaceImplementation))));
        }
        public KeyValuePairPartBuilder(Type type, PartDefinition partDefinition, IPartResolver resolver)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }

            if (!type.IsGenericType || type.GetGenericTypeDefinition() != typeof(KeyValuePair <,>))
            {
                throw new ArgumentException("type must be a KeyValuePair<,>", "type");
            }

            if (type.IsGenericTypeDefinition)
            {
                throw new ArgumentException("The type parameters of type are not defined", "type");
            }

            _type = type;
            var typeArgs = _type.GetGenericArguments();

            _keyType      = typeArgs[0];
            _valueType    = typeArgs[1];
            _keyBuilder   = resolver.GetPartBuilder(_keyType, partDefinition, true);
            _valueBuilder = resolver.GetPartBuilder(_valueType, partDefinition, true);
            _ctor         = _type.GetConstructor(new[] { _keyType, _valueType });
            Debug.Assert(_ctor != null, "Couldn't find KeyValuePair constructor");
        }
Пример #6
0
        private IPart GetPart(IItem item, PartDefinition definition)
        {
            if (!_partSeeders.ContainsKey(definition.TypeId))
            {
                return(null);
            }

            return(_partSeeders[definition.TypeId]
                   ?.GetPart(item, definition.RoleId, _factory));
        }
Пример #7
0
 public NullablePartBuilder(Type nullableType, PartDefinition partDefinition, IPartResolver resolver)
 {
     if (nullableType.GetGenericTypeDefinition() != typeof(Nullable <>))
     {
         throw new ArgumentException(string.Format("{0} is not a Nullable<T>", nullableType), "nullableType");
     }
     _type         = nullableType;
     _innerType    = _type.GetGenericArguments()[0];
     _ctor         = _type.GetConstructor(new[] { _innerType });
     _innerBuilder = resolver.GetPartBuilder(_innerType, partDefinition, true);
 }
Пример #8
0
        public void ClassInitialize()
        {
            // Create the part-definition.
            partDefinition = new PartDefinition(
                        "Open.Core.Test.Samples.SamplePart.Create();",
                        "/Content/Scripts/Open.Core.Test.debug.js;  /Content/Scripts/Open.Core.Controls.debug.js;/Content/Scripts/Open.Core.debug.js;",
                        "/Content/Css/Sample.css;    /Open.Core/Css/Core.css"
                        );
            partDefinition.DownloadTimeout = 2;

            // Finish up.
            Write__Properties();
        }
Пример #9
0
        private void ParseItem()
        {
            var itemFileName = Uri.IsWellFormedUriString(_value, UriKind.Absolute) ? _value : $"{_dirName}\\{_value}";

            if (!int.TryParse(GetValue(StreamReader.ReadLine()), out int itemQuant))
            {
                throw new Exception($"{_dirName}\\{FileName}:{_currentLine}: invalid parameter ITEMQUANT");
            }
            if (!int.TryParse(GetValue(StreamReader.ReadLine()), out int rotate))
            {
                throw new Exception($"{_dirName}\\{FileName}:{_currentLine}: invalid parameter ROTATE");
            }
            var rotStep = GetValue(StreamReader.ReadLine());

            if (!int.TryParse(GetValue(StreamReader.ReadLine()), out int reflect))
            {
                throw new Exception($"{_dirName}\\{FileName}:{_currentLine}: invalid parameter REFLECT");
            }

            int id = GetItemId();

            var itemReader  = new NFItemReader(FormatPathForItems(itemFileName));
            var partProfile = itemReader.Read();

            var part = new PartDefinition
            {
                ID = id,
                OriginalPartProfile = partProfile,
                Count           = itemQuant,
                DisableTurn     = rotate == 0,
                OverturnAllowed = reflect == 1
            };

            part.Name = part.OriginalPartProfile.ItemName;
            switch (rotStep)
            {
            case "PI":
                part.AngleStep = 180;
                break;

            case "PI/2":
                part.AngleStep = 90;
                break;

            case "NO":
                part.AngleStep = 360;
                break;
            }
            _task.Parts.Add(part);
        }
Пример #10
0
        public ArrayPartBuilder(Type arrayType, PartDefinition partDefinition, IPartResolver resolver)
        {
            if (!arrayType.IsArray)
            {
                throw new ArgumentException("arrayType is not an array", "arrayType");
            }

            if (arrayType.GetArrayRank() != 1)
            {
                throw new NotSupportedException("Multi-dimensional arrays are not supported by this class.");
            }

            _elementType    = arrayType.GetElementType();
            _elementBuilder = resolver.GetPartBuilder(_elementType, partDefinition, true);
        }
Пример #11
0
        public void RemovePlugins()
        {
            var currentlyBuilding = new Dictionary <Type, TypeIdentity>();
            var repository        = new PluginRepository();

            Func <Type, TypeIdentity> identityGenerator = TypeIdentityBuilder.IdentityFactory(repository, currentlyBuilding);
            PartDefinition            partDefinition    = new PartDefinition
            {
                Identity = identityGenerator(typeof(ExportOnProperty)),
            };

            var partFileInfo = new PluginFileInfo("a", DateTimeOffset.Now);

            repository.AddPart(partDefinition, partFileInfo);

            var groupDefinition = new GroupDefinition("b");
            var groupFileInfo   = new PluginFileInfo("c", DateTimeOffset.Now);

            repository.AddGroup(groupDefinition, groupFileInfo);

            Assert.That(
                repository.KnownPluginFiles(),
                Is.EquivalentTo(
                    new List <PluginFileInfo>
            {
                partFileInfo,
                groupFileInfo,
            }));

            repository.RemovePlugins(
                new List <string>
            {
                partFileInfo.Path
            });

            Assert.That(
                repository.KnownPluginFiles(),
                Is.EquivalentTo(
                    new List <PluginFileInfo>
            {
                groupFileInfo,
            }));
            Assert.AreEqual(0, repository.Parts().Count());
            Assert.AreEqual(1, repository.Groups().Count());
            Assert.IsFalse(repository.ContainsDefinitionForType(typeof(ExportOnProperty).AssemblyQualifiedName));
        }
Пример #12
0
        public IActionResult GetTextLayerPartTypeId(string database)
        {
            ICadmusRepository repository =
                _repositoryProvider.CreateRepository(database);

            foreach (FacetDefinition facet in repository.GetFacetDefinitions())
            {
                PartDefinition partDef = facet.PartDefinitions
                                         .Find(d => d.RoleId?.StartsWith(
                                                   PartBase.FR_PREFIX, StringComparison.Ordinal) == true);
                if (partDef != null)
                {
                    return(Ok(new { partDef.TypeId }));
                }
            }
            return(Ok(new { TypeId = (string)null }));
        }
Пример #13
0
        public EnumPartBuilder(Type type, PartDefinition partDefinition, IPartResolver resolver)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }
            if (!type.IsEnum)
            {
                throw new ArgumentException("type must be an enumeration", "type");
            }

            _type           = type;
            _underlyingType = Enum.GetUnderlyingType(type);
            _innerBuilder   =
                _underlyingType == typeof(int)
                ? new PrimitivePartBuilder(typeof(int), "ReadVarInt32", "WriteVarInt32")
                                : resolver.GetPartBuilder(_underlyingType, partDefinition, true);
        }
Пример #14
0
        /// <summary>
        /// Adds a new part to the repository.
        /// </summary>
        /// <param name="part">The part definition.</param>
        /// <param name="pluginFileInfo">The file info of the assembly which owns the part.</param>
        public void AddPart(PartDefinition part, PluginFileInfo pluginFileInfo)
        {
            lock (m_Lock)
            {
                {
                    Lokad.Enforce.Argument(() => part);
                    Lokad.Enforce.Argument(() => pluginFileInfo);
                    Lokad.Enforce.With <DuplicatePartDefinitionException>(
                        !m_Parts.ContainsKey(part.Identity),
                        Resources.Exceptions_Messages_DuplicatePartDefinition);
                }

                m_Parts.Add(part.Identity, new Tuple <PartDefinition, PluginFileInfo>(part, pluginFileInfo));
                if (!m_PluginFiles.Contains(pluginFileInfo))
                {
                    m_PluginFiles.Add(pluginFileInfo);
                }
            }
        }
Пример #15
0
        public CollectionPartBuilder(Type collectionType, Type elementType, PartDefinition partDefinition, IPartResolver resolver, Type underlyingType)
        {
            if (collectionType == null)
            {
                throw new ArgumentNullException("collectionType");
            }
            if (elementType == null)
            {
                throw new ArgumentNullException("elementType");
            }
            if (partDefinition == null)
            {
                throw new ArgumentNullException("partDefinition");
            }
            if (resolver == null)
            {
                throw new ArgumentNullException("resolver");
            }

            _collectionType = collectionType;
            _elementType    = elementType;
            _innerBuilder   = resolver.GetPartBuilder(_elementType, partDefinition, true);

            if (_innerBuilder == null)
            {
                throw new NotSupportedException(string.Format("Type '{0}' cannot be serialized", elementType));
            }

            var interfaceType = typeof(ICollection <>).MakeGenericType(elementType);

            if (!interfaceType.IsAssignableFrom(collectionType))
            {
                throw new ArgumentException(string.Format(
                                                "collectionType '{0}' is not assignable to '{1}'",
                                                collectionType.Name,
                                                interfaceType.Name),
                                            "collectionType");
            }

            _getCount = _collectionType.GetBestCallableOverride(interfaceType.ResolveProperty("Count").GetGetMethod());
            _add      = _collectionType.GetBestCallableOverride(interfaceType.ResolveMethod("Add", new[] { elementType }));
            _contains = _collectionType.GetBestCallableOverride(interfaceType.ResolveMethod("Contains", elementType));

            const BindingFlags bindingFlags =
                BindingFlags.CreateInstance
                | BindingFlags.Public
                | BindingFlags.NonPublic
                | BindingFlags.Instance;

            _ctor     = underlyingType.GetConstructor(bindingFlags, null, new[] { typeof(int) }, null);
            _ctorType = CtorType.Capacity;
            if (_ctor == null || _ctor.GetParameters()[0].Name != "capacity")
            {
                _ctor     = underlyingType.GetConstructor(bindingFlags, null, Type.EmptyTypes, null);
                _ctorType = CtorType.Default;
            }

            if (_ctor == null)
            {
                throw new ArgumentException("collectionType='" + collectionType.Name + "' does not define .ctor(int capacity) or .ctor()", "collectionType");
            }
        }
Пример #16
0
 public CollectionPartBuilder(Type collectionType, Type elementType, PartDefinition partDefinition, IPartResolver resolver)
     : this(collectionType, elementType, partDefinition, resolver, collectionType)
 {
 }
Пример #17
0
 /// <summary>
 /// Adds a new part to the repository.
 /// </summary>
 /// <param name="part">The part definition.</param>
 /// <param name="pluginFileInfo">The file info of the assembly which owns the part.</param>
 public void AddPart(PartDefinition part, PluginFileInfo pluginFileInfo)
 {
     m_Repository.AddPart(part, pluginFileInfo);
 }
Пример #18
0
        public static SerializableStructPartBuilder TryCreate(Type type, PartDefinition partDefinition, IPartResolver resolver)
        {
            var attribute = Attribute
                            .GetCustomAttributes(type, typeof(SerializableStructAttribute), false)
                            .Cast <SerializableStructAttribute>()
                            .FirstOrDefault <SerializableStructAttribute>();

            if (attribute == null)
            {
                return(null);
            }

            var targetType = attribute.TargetType;

            if (!type.IsValueType)
            {
                throw new BarfException(string.Format(
                                            "{0}(typeof({1})) is invalid on type {2}. {2} must be a value type.",
                                            typeof(SerializableStructAttribute).Name,
                                            targetType,
                                            type), type, null);
            }

            if (!targetType.IsPrimitive)
            {
                throw new BarfException(string.Format(
                                            "{0}(typeof({1})) is invalid. {1} must be primitive type.",
                                            typeof(SerializableStructAttribute).Name,
                                            targetType.Name),
                                        type,
                                        null);
            }

            var possibleMethods = type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.DeclaredOnly)
                                  .Where <MethodInfo>(m => m.IsSpecialName)
                                  .Where <MethodInfo>(m => m.Name == "op_Explicit" || m.Name == "op_Implicit")
                                  .Where <MethodInfo>(m => !m.IsGenericMethodDefinition);

            var result = new SerializableStructPartBuilder
            {
                _targetType        = targetType,
                _toPrimitiveMethod = possibleMethods
                                     .Where <MethodInfo>(m => m.ReturnType == targetType)
                                     .Where <MethodInfo>(m =>
                {
                    var p = m.GetParameters();
                    return(p.Length == 1 && p[0].ParameterType == type);
                })
                                     .FirstOrDefault <MethodInfo>(),
                _fromPrimitiveMethod = possibleMethods
                                       .Where <MethodInfo>(m => m.ReturnType == type)
                                       .Where <MethodInfo>(m =>
                {
                    var p = m.GetParameters();
                    return(p.Length == 1 && p[0].ParameterType == targetType);
                })
                                       .FirstOrDefault <MethodInfo>(),
                _innerBuilder = resolver.GetPartBuilder(targetType, partDefinition, true)
            };

            if (result._toPrimitiveMethod == null || result._fromPrimitiveMethod == null)
            {
                throw new BarfException(string.Format(
                                            "{0}(typeof({1})) is invalid on type {2}. {2} must define an implicit or explicit conversion operator to type {1}.",
                                            typeof(SerializableStructAttribute).Name,
                                            targetType,
                                            type), type, null);
            }

            return(result);
        }
Пример #19
0
 private static bool IsLayerPart(PartDefinition def) =>
 def.RoleId?.StartsWith(PartBase.FR_PREFIX) == true;
Пример #20
0
        /// <summary>
        /// Gets the items.
        /// </summary>
        /// <param name="count">The desired count of items to get.</param>
        /// <returns>The items.</returns>
        public IEnumerable <IItem> GetItems(int count)
        {
            if (count < 1 ||
                _options.FacetDefinitions == null ||
                _options.FacetDefinitions.Length == 0)
            {
                yield break;
            }

            // init
            if (_options.Seed.HasValue)
            {
                Randomizer.Seed = new Random(_options.Seed.Value);
            }

            ItemSeeder itemSeeder = _factory.GetItemSeeder();

            _partSeeders = _factory.GetPartSeeders();
            IItemSortKeyBuilder sortKeyBuilder = _factory.GetItemSortKeyBuilder();

            // generate items
            for (int n = 1; n <= count; n++)
            {
                // pick a facet
                FacetDefinition facet = _options.FacetDefinitions[
                    _options.FacetDefinitions.Length == 1
                    ? 0
                    : Randomizer.Seed.Next(0, _options.FacetDefinitions.Length)];

                // get item
                IItem item = itemSeeder.GetItem(n, facet.Id);

                // add parts: first non layer parts, then the others.
                // This ensures that the item already has the base text part
                // before adding the layer parts, which refer to it.

                // 1) non-layer parts, required
                AddParts(facet.PartDefinitions
                         .Where(def => !IsLayerPart(def) && def.IsRequired),
                         item,
                         false);

                // 2) non-layer parts, optional
                AddParts(facet.PartDefinitions
                         .Where(def => !IsLayerPart(def) && !def.IsRequired),
                         item,
                         true);

                // 3) layer-parts
                // we must have a base text definition to have layers
                PartDefinition baseTextDef = facet.PartDefinitions.Find(
                    def => def.RoleId == PartBase.BASE_TEXT_ROLE_ID);

                if (baseTextDef != null && Randomizer.Seed.Next(0, 2) == 1)
                {
                    // ensure there is a base text. This is required for
                    // the text layer part seeder, which must rely on a base text.
                    IPart baseTextPart = item.Parts.Find(
                        p => p.TypeId == baseTextDef.TypeId);

                    // add a base text if none found
                    if (baseTextPart == null)
                    {
                        baseTextPart = GetPart(item, baseTextDef);
                        if (baseTextPart != null)
                        {
                            item.Parts.Add(baseTextPart);
                        }
                    }

                    // once we have one, eventually add layer(s)
                    if (baseTextPart != null)
                    {
                        // 3) layer parts, required
                        AddParts(facet.PartDefinitions
                                 .Where(def => IsLayerPart(def) && def.IsRequired),
                                 item,
                                 false);

                        // 4) layer parts, optional
                        AddParts(facet.PartDefinitions
                                 .Where(def => IsLayerPart(def) && !def.IsRequired),
                                 item,
                                 true);
                    }
                }

                // once all the parts are in place, override the item's sort key
                // if requested in the config.
                // Note that we do not provide a repository, as while seeding
                // there might be no database, and all the item's parts are
                // in the item itself.
                if (sortKeyBuilder != null)
                {
                    item.SortKey = sortKeyBuilder.BuildKey(item, null);
                }

                yield return(item);
            }
        }
Пример #21
0
        private PartDefinition ExtractActionsAndConditions(Type type, PartDefinition part, Func <Type, TypeIdentity> createTypeIdentity)
        {
            var actions    = new List <ScheduleActionDefinition>();
            var conditions = new List <ScheduleConditionDefinition>();

            foreach (var method in type.GetMethods())
            {
                if (method.ReturnType == typeof(void) && !method.GetParameters().Any())
                {
                    var actionAttribute = method.GetCustomAttribute <ScheduleActionAttribute>(true);
                    if (actionAttribute != null)
                    {
                        var actionDefinition = ScheduleActionDefinition.CreateDefinition(
                            actionAttribute.Name,
                            method,
                            createTypeIdentity);
                        actions.Add(actionDefinition);

                        m_Logger.Log(
                            LevelToLog.Info,
                            string.Format(
                                CultureInfo.InvariantCulture,
                                "Discovered action: {0}",
                                actionDefinition));
                    }

                    continue;
                }

                if (method.ReturnType == typeof(bool) && !method.GetParameters().Any())
                {
                    var conditionAttribute = method.GetCustomAttribute <ScheduleConditionAttribute>(true);
                    if (conditionAttribute != null)
                    {
                        var conditionDefinition = MethodBasedScheduleConditionDefinition.CreateDefinition(
                            conditionAttribute.Name,
                            method,
                            createTypeIdentity);
                        conditions.Add(conditionDefinition);

                        m_Logger.Log(
                            LevelToLog.Info,
                            string.Format(
                                CultureInfo.InvariantCulture,
                                "Discovered condition: {0}",
                                conditionDefinition));
                    }
                }
            }

            foreach (var property in type.GetProperties())
            {
                if (property.PropertyType == typeof(bool))
                {
                    var conditionAttribute = property.GetCustomAttribute <ScheduleConditionAttribute>(true);
                    if (conditionAttribute != null)
                    {
                        var conditionDefinition = PropertyBasedScheduleConditionDefinition.CreateDefinition(
                            conditionAttribute.Name,
                            property,
                            createTypeIdentity);
                        conditions.Add(conditionDefinition);

                        m_Logger.Log(
                            LevelToLog.Info,
                            string.Format(
                                CultureInfo.InvariantCulture,
                                "Discovered condition: {0}",
                                conditionDefinition));
                    }
                }
            }

            if (actions.Count > 0 || conditions.Count > 0)
            {
                part.Actions    = actions;
                part.Conditions = conditions;
            }

            return(part);
        }