Пример #1
0
        private void Initialize(Action <IObjectTypeDescriptor> configure)
        {
            if (configure == null)
            {
                throw new ArgumentNullException(nameof(configure));
            }

            ObjectTypeDescriptor descriptor = CreateDescriptor();

            configure(descriptor);

            ObjectTypeDescription description = descriptor.CreateDescription();

            InitializeFields(description);

            _isOfType   = description.IsOfType;
            _interfaces = description.Interfaces;

            SyntaxNode = description.SyntaxNode;

            Initialize(description.Name, description.Description,
                       new DirectiveCollection(
                           this,
                           DirectiveLocation.Object,
                           description.Directives));
        }
Пример #2
0
        internal ObjectType(ObjectTypeConfig config)
        {
            if (config == null)
            {
                throw new ArgumentNullException(nameof(config));
            }

            if (string.IsNullOrEmpty(config.Name))
            {
                throw new ArgumentException(
                          "An object type name must not be null or empty.",
                          nameof(config));
            }

            Field[] fields = config.Fields?.ToArray();
            if (fields == null || fields.Length == 0)
            {
                throw new ArgumentException(
                          $"The object type `{Name}` has no fields.",
                          nameof(config));
            }

            foreach (Field field in fields)
            {
                _fieldMap[field.Name] = field;
            }

            _isOfType         = config.IsOfType;
            _interfaceFactory = config.Interfaces;

            SyntaxNode      = config.SyntaxNode;
            Name            = config.Name;
            Description     = config.Description;
            IsIntrospection = config.IsIntrospection;
        }
Пример #3
0
        IObjectTypeDescriptor IObjectTypeDescriptor.IsOfType(IsOfType isOfType)
        {
            if (isOfType == null)
            {
                throw new ArgumentNullException(nameof(isOfType));
            }

            IsOfType = isOfType;
            return(this);
        }
Пример #4
0
 private void CompleteIsOfType()
 {
     if (_isOfType == null)
     {
         if (ClrType == typeof(object))
         {
             _isOfType = IsOfTypeWithName;
         }
         else
         {
             _isOfType = IsOfTypeWithClrType;
         }
     }
 }
Пример #5
0
 private void CompleteIsOfType()
 {
     if (_isOfType == null)
     {
         if (_typeBinding?.Type == null)
         {
             _isOfType = IsOfTypeNameBased;
         }
         else
         {
             _isOfType = IsOfTypeWithNativeType;
         }
     }
 }
Пример #6
0
        public ObjectType()
        {
            ObjectTypeDescriptor descriptor = CreateDescriptor();

            Configure(descriptor);

            if (string.IsNullOrEmpty(descriptor.Name))
            {
                throw new ArgumentException(
                          "The type name must not be null or empty.");
            }

            if (descriptor.Fields.Count == 0)
            {
                throw new ArgumentException(
                          $"The object type `{Name}` has no fields.");
            }

            List <FieldBinding> fieldBindings = new List <FieldBinding>();

            foreach (FieldDescriptor fieldDescriptor in descriptor.Fields)
            {
                Field field = fieldDescriptor.CreateField();
                _fieldMap[fieldDescriptor.Name] = field;

                if (fieldDescriptor.Member != null)
                {
                    fieldBindings.Add(new FieldBinding(
                                          fieldDescriptor.Name, fieldDescriptor.Member, field));
                }
            }

            if (descriptor.NativeType != null)
            {
                _typeBinding = new ObjectTypeBinding(
                    descriptor.Name, descriptor.NativeType, this, fieldBindings);
            }

            _isOfType         = descriptor.IsOfType;
            _interfaceFactory = r => descriptor.Interfaces
                                .Select(t => t.TypeFactory(r))
                                .Cast <InterfaceType>();
            _interfaceTypeInfos = descriptor.Interfaces;

            Name            = descriptor.Name;
            Description     = descriptor.Description;
            IsIntrospection = descriptor.IsIntrospection;
        }
Пример #7
0
        private void Initialize(ObjectTypeDescriptor descriptor)
        {
            if (string.IsNullOrEmpty(descriptor.Name))
            {
                throw new ArgumentException(
                          "The type name must not be null or empty.");
            }

            InitializeFields(descriptor);

            _isOfType   = descriptor.IsOfType;
            _interfaces = descriptor.Interfaces;

            SyntaxNode      = descriptor.SyntaxNode;
            Name            = descriptor.Name;
            Description     = descriptor.Description;
            IsIntrospection = descriptor.IsIntrospection;
        }
Пример #8
0
 private void CompleteIsOfType(ICompletionContext context)
 {
     if (_isOfType == null)
     {
         if (context.IsOfType != null)
         {
             IsOfTypeFallback isOfType = context.IsOfType;
             _isOfType = (ctx, obj) => isOfType(this, ctx, obj);
         }
         else if (ClrType == typeof(object))
         {
             _isOfType = IsOfTypeWithName;
         }
         else
         {
             _isOfType = IsOfTypeWithClrType;
         }
     }
 }
Пример #9
0
        protected override void OnCompleteType(
            ICompletionContext context,
            ObjectTypeDefinition definition)
        {
            base.OnCompleteType(context, definition);

            _isOfType  = definition.IsOfType;
            SyntaxNode = definition.SyntaxNode;

            var fields = new List <ObjectField>();

            AddIntrospectionFields(context, fields);
            fields.AddRange(definition.Fields.Select(t => new ObjectField(t)));

            Fields = new FieldCollection <ObjectField>(fields);

            CompleteInterfaces(context, definition);
            CompleteIsOfType(context);
            FieldInitHelper.CompleteFields(context, definition, Fields);
        }
Пример #10
0
        private static ConditionResult VerifyCondition(List <object> objects, IsOfType typeCondition)
        {
            ConditionResult result = new ConditionResult()
            {
                Condition = typeCondition
            };
            List <string> info = new List <string>();

            Type type = typeCondition.Type is string?BH.Engine.Reflection.Create.Type(typeCondition.Type.ToString()) : typeCondition.Type as Type;

            if (type == null)
            {
                string error = $"Invalid {nameof(IsOfType.Type)} input in the given {nameof(IsOfType)}.";
                BH.Engine.Reflection.Compute.RecordError(error);
                result.FailedObjects = objects;
                result.FailInfo      = Enumerable.Repeat(error, objects.Count).ToList();
                return(result);
            }

            foreach (var obj in objects)
            {
                if (obj.GetType() == type)
                {
                    result.PassedObjects.Add(obj);
                    result.Pattern.Add(true);
                }
                else
                {
                    result.FailedObjects.Add(obj);
                    info.Add($"{(string.IsNullOrWhiteSpace(typeCondition.Clause) ? "" : typeCondition.Clause + " failed: ")}" +
                             $"Type was `{obj.GetType().Name}` instead of `{type.Name}`.");
                    result.Pattern.Add(false);
                }
            }

            result.FailInfo = info;
            return(result);
        }
Пример #11
0
 public IObjectTypeDescriptor IsOfType(IsOfType isOfType)
 {
     Definition.IsOfType = isOfType
                           ?? throw new ArgumentNullException(nameof(isOfType));
     return(this);
 }
Пример #12
0
 IObjectTypeDescriptor IObjectTypeDescriptor.IsOfType(IsOfType isOfType)
 {
     IsOfType(isOfType);
     return(this);
 }
Пример #13
0
 protected void IsOfType(IsOfType isOfType)
 {
     ObjectDescription.IsOfType = isOfType
                                  ?? throw new ArgumentNullException(nameof(isOfType));
 }
Пример #14
0
 public new IObjectTypeDescriptor <T> IsOfType(IsOfType isOfType)
 {
     base.IsOfType(isOfType);
     return(this);
 }
Пример #15
0
        /// <summary>
        ///	Method that will actually resolve the instances.
        /// </summary>
        /// <typeparam name="TInstance">The type of the instances we want.</typeparam>
        /// <returns>
        /// Returns a list with <see cref="TInstance"/> instances.
        /// The list could be empty when no implementations were found.
        /// </returns>
        public List <TInstance> ResolveInstances <TInstance>(bool onlyLookInPlugins = true)
        {
            // get the type once, instead of once every type.
            IsOfType typeCheckMethod = IsSubclassOf;
            var      typeOfTInstance = typeof(TInstance);

            if (typeOfTInstance.IsInterface)
            {
                typeCheckMethod = ImplementsInterface;
            }
            var returnList = new List <TInstance>();

            var assemblies = getAssemblyCollection(onlyLookInPlugins);

            if (assemblies.Count == 0)
            {
                LogUtility.Out("[SK] InstanceResolver: No assemblies found.");
                return(returnList);
            }

            foreach (var assembly in assemblies)
            {
                LogUtility.Out("[SK] InstanceResolver: Scanning assembly " + assembly.Location);
                // loop all assemblies, see if it contains types we are looking for.
                Type[] typesInAssembly = new Type[0];
                try
                {
                    typesInAssembly = assembly.GetTypes();
                }
                catch (Exception exception)
                {
                    // Not yet able to cover this piece of code with a unit test.
                    var survivalKitException = new SurvivalKit.Exceptions.SurvivalKitPluginException("SK.ResolveInstances", "SurvivalKit.Utility.InstanceResolver", "Unable to extract types from assembly: " + assembly.FullName, exception);
                    LogUtility.Exception(survivalKitException);
                }

                foreach (var typeInAssembly in typesInAssembly)
                {
                    if (typeInAssembly.IsInterface || typeInAssembly.IsAbstract)
                    {
                        continue;
                    }

                    // loop all types in the assembly. only act when it matches our needs.
                    if (typeCheckMethod(typeInAssembly, typeOfTInstance))
                    {
                        var constructors          = typeInAssembly.GetConstructors();
                        var foundValidConstructor = false;
                        foreach (var item in constructors)
                        {
                            if (item.GetParameters().Length == 0)
                            {
                                foundValidConstructor = true;
                            }
                        }

                        if (!foundValidConstructor)
                        {
                            // there is no constructor without arguments, we can't instantiate those (yet?)
                            continue;
                        }

                        try
                        {
                            var instance = (TInstance)Activator.CreateInstance(typeInAssembly);
                            returnList.Add(instance);
                        }
                        catch (Exception exception)
                        {
                            var wrappedException = new SurvivalKitPluginException("ResolvePlugin", "SurvivalKit.InstanceResolver.ResolveInstances", "Error while invoking constructor", exception);
                            LogUtility.Exception(wrappedException);
                        }
                    }
                }
            }

            return(returnList);
        }
Пример #16
0
        private static ConditionResult VerifyCondition(List <object> objects, ValueCondition valueCondition)
        {
            ConditionResult conditionResult = new ConditionResult()
            {
                Condition = valueCondition
            };

            var refValue = valueCondition.ReferenceValue;

            if (refValue == null)
            {
                BH.Engine.Reflection.Compute.RecordNote($"A {nameof(ValueCondition)}'s {nameof(valueCondition.ReferenceValue)} was null. Make sure this is intended.\nTo check for null/not null, consider using a {nameof(IsNull)} instead.");
            }

            foreach (var obj in objects)
            {
                bool passed = true;

                // Value to be compared to the referenceValue.
                object value = obj.ValueFromSource(valueCondition.PropertyName);

                // If no propertyName was assigned, assume we want to compare the entire object.
                if (string.IsNullOrWhiteSpace(valueCondition.PropertyName))
                {
                    value = obj;
                }

                // Basic cases (check for nullity)
                if (valueCondition.ReferenceValue == null && value == null)
                {
                    passed = true;
                    PopulateConditionResults(obj, value, valueCondition, conditionResult, passed);
                    continue;
                }
                if (valueCondition.ReferenceValue == null && value != null)
                {
                    passed = false;
                    PopulateConditionResults(obj, value, valueCondition, conditionResult, passed);
                    continue;
                }
                else if (valueCondition.ReferenceValue != null && value == null)
                {
                    if (valueCondition.PropertyName == "Type" && valueCondition.ReferenceValue is Type)
                    {
                        passed = obj.GetType() == (Type)valueCondition.ReferenceValue;
                    }
                    else
                    {
                        passed = false;
                    }


                    PopulateConditionResults(obj, value, valueCondition, conditionResult, passed);
                    continue;
                }

                // Try a numerical comparison.
                double numericalValue;
                if (double.TryParse(value?.ToString(), out numericalValue))
                {
                    double referenceNumValue;
                    double.TryParse(valueCondition.ReferenceValue?.ToString(), out referenceNumValue);

                    double numTolerance;
                    if (!double.TryParse(valueCondition.Tolerance?.ToString(), out numTolerance))
                    {
                        numTolerance = 1e-03;
                    }

                    passed = NumericalComparison(numericalValue, referenceNumValue, numTolerance, valueCondition.Comparison);
                    PopulateConditionResults(obj, value, valueCondition, conditionResult, passed);
                    continue;
                }

                // Consider some other way to compare objects.
                if (valueCondition.Comparison == ValueComparisons.EqualTo)
                {
                    // If the referenceValue is a Type, convert this ValueCondition to a IsOfType condition.
                    if (valueCondition.ReferenceValue is Type)
                    {
                        IsOfType typeCondition = new IsOfType()
                        {
                            Type = valueCondition.ReferenceValue as Type
                        };
                        var TypeCondResult = VerifyCondition(new List <object>()
                        {
                            value
                        }, typeCondition);
                        conditionResult.PassedObjects.Add(TypeCondResult.PassedObjects);
                        conditionResult.FailedObjects.Add(TypeCondResult.FailedObjects);
                        conditionResult.FailInfo.Add(TypeCondResult.FailInfo.FirstOrDefault());
                        conditionResult.Pattern.Add(TypeCondResult.Pattern.FirstOrDefault());
                        conditionResult.Condition = valueCondition;
                        continue;
                    }

                    passed = CompareEquality(value, valueCondition.ReferenceValue, valueCondition.Tolerance);
                    PopulateConditionResults(obj, value, valueCondition, conditionResult, passed);
                }
            }

            return(conditionResult);
        }