private void AddTypeInner(Type t)
        {
            if (t.GetInterface("IList") != null)
            {
                t = ReflectionX.ElementType(t);
            }

            if (TypeProperties.ContainsKey(t.AssemblyQualifiedName))
            {
                return;
            }

            var typeDict = new Dictionary <string, string>();

            TypeProperties.Add(t.AssemblyQualifiedName, typeDict);
            foreach (var prop in t.GetPersistedProperties())
            {
                if (typeDict.ContainsKey(prop.Name))
                {
                    log.Error("Property " + prop.Name + " repeated on type " + t.FullName);
                    continue;
                }
                typeDict.Add(prop.Name, prop.PropertyType.AssemblyQualifiedName);
                if (!prop.PropertyType.FullName.StartsWith("System."))
                {
                    AddTypeInner(prop.PropertyType);
                }
            }
        }
        /// <summary>
        /// Reverts part of the schema relevant to a problem to the state which when compared to its current
        /// state, regenerates the problem. The inverse of ResolveProblem.
        /// </summary>
        /// <param name="oldSchema">the old schema which generated the problem when compared to the current schema</param>
        /// <param name="problem">the problem it generated</param>
        public void ApplyProblem(ContentModelSchema oldSchema, ChangeProblem problem)
        {
            string aqTypeName = problem.GetAssemblyQualifiedTypeName();

            switch (problem.ProblemType)
            {
            case ChangeProblemType.DeletionNeeded:
                // copy the deleted type to the new schema
                TypeProperties.Add(aqTypeName, oldSchema.TypeProperties[aqTypeName]);
                break;

            case ChangeProblemType.PropertyDropped:
                // copy the dropped property to the new schema
                TypeProperties[aqTypeName].Add(problem.PropertyName, oldSchema.TypeProperties[aqTypeName][problem.PropertyName]);
                break;

            case ChangeProblemType.PropertyDroppedFromSummary:
                Type   contentType       = ContentTypeHierarchy.GetContentType(problem.TypeName);
                string aqSummaryTypeName = ContentTypeHierarchy.SummaryTypes[contentType].AssemblyQualifiedName;
                TypeProperties[aqTypeName].Add(problem.PropertyName, oldSchema.TypeProperties[aqTypeName][problem.PropertyName]);
                TypeProperties[aqSummaryTypeName].Add(problem.PropertyName, oldSchema.TypeProperties[aqSummaryTypeName][problem.PropertyName]);
                break;

            // Problems not requiring data modification
            case ChangeProblemType.NullObjectValue:
                break;
            }
        }
Exemplo n.º 3
0
        public static object GetResult(this Task task)
        {
            try
            {
                if (!task.IsCompleted)
                {
                    task.Wait();
                }

                if (task is Task <object> taskObj)
                {
                    return(taskObj.Result);
                }

                var taskType = task.GetType();
                if (!taskType.IsGenericType || taskType.FullName.Contains("VoidTaskResult"))
                {
                    return(null);
                }

                var props = TypeProperties.Get(taskType);
                var fn    = props.GetPublicGetter("Result");
                return(fn?.Invoke(task));
            }
            catch (TypeAccessException)
            {
                return(null); //return null for void Task's
            }
            catch (Exception ex)
            {
                throw ex.UnwrapIfSingleException();
            }
        }
Exemplo n.º 4
0
        public void Can_access_ModelWithComplexTypes()
        {
            var idAccessor = TypeProperties <ModelWithComplexTypes> .GetAccessor("Id");

            var stringListAccessor = TypeProperties <ModelWithComplexTypes> .GetAccessor("StringList");

            var intListAccessor = TypeProperties <ModelWithComplexTypes> .GetAccessor("IntList");

            var stringMapAccessor = TypeProperties <ModelWithComplexTypes> .GetAccessor("StringMap");

            var intMapAccessor = TypeProperties <ModelWithComplexTypes> .GetAccessor("IntMap");

            var childAccessor = TypeProperties <ModelWithComplexTypes> .GetAccessor("Child");

            var original = ModelWithComplexTypesFactory.Instance.CreateInstance(1);

            Assert.That(idAccessor.PublicGetter(original), Is.EqualTo(original.Id));
            Assert.That(stringListAccessor.PublicGetter(original), Is.EqualTo(original.StringList));
            Assert.That(intListAccessor.PublicGetter(original), Is.EqualTo(original.IntList));
            Assert.That(stringMapAccessor.PublicGetter(original), Is.EqualTo(original.StringMap));
            Assert.That(intMapAccessor.PublicGetter(original), Is.EqualTo(original.IntMap));
            Assert.That(childAccessor.PublicGetter(original), Is.EqualTo(original.Child));

            var to = ModelWithComplexTypesFactory.Instance.CreateInstance(2);

            idAccessor.PublicSetter(original, to.Id);
            stringListAccessor.PublicSetter(original, to.StringList);
            intListAccessor.PublicSetter(original, to.IntList);
            stringMapAccessor.PublicSetter(original, to.StringMap);
            intMapAccessor.PublicSetter(original, to.IntMap);
            childAccessor.PublicSetter(original, to.Child);

            ModelWithComplexTypesFactory.Instance.AssertIsEqual(original, to);
        }
Exemplo n.º 5
0
        private void SetTypeTemplateProperty(string domainID, TypeProperties propertyName, object value)
        {
            var template       = this.GetDomainHost <ITypeTemplate>(domainID);
            var authentication = this.Context.GetAuthentication(this);

            template.Dispatcher.Invoke(() =>
            {
                if (propertyName == TypeProperties.Name)
                {
                    template.SetTypeName(authentication, (string)value);
                }
                else if (propertyName == TypeProperties.IsFlag)
                {
                    template.SetIsFlag(authentication, (bool)value);
                }
                else if (propertyName == TypeProperties.Comment)
                {
                    template.SetComment(authentication, (string)value);
                }
                else
                {
                    throw new NotImplementedException();
                }
            });
        }
Exemplo n.º 6
0
        protected virtual TExtensibleTypeProperties DeserializeTypeProperties(
            string typeName,
            string json,
            out Type type)
        {
            TExtensibleTypeProperties typeProperties;

            if (this.TryGetRegisteredType(typeName, out type))
            {
                if (string.IsNullOrEmpty(json))
                {
                    // No typeProperties exist to deserialize, just initialize a default instance
                    typeProperties = (TExtensibleTypeProperties)Activator.CreateInstance(type);
                }
                else
                {
                    typeProperties = (TExtensibleTypeProperties)TypeProperties.DeserializeObject(json, type);
                }
            }
            else
            {
                Dictionary <string, JToken> serviceExtraProperties =
                    JsonConvert.DeserializeObject <Dictionary <string, JToken> >(
                        json,
                        ConversionCommon.DefaultSerializerSettings);

                typeProperties = new TGenericTypeProperties()
                {
                    ServiceExtraProperties = serviceExtraProperties
                };
                type = typeof(TGenericTypeProperties);
            }

            return(typeProperties);
        }
Exemplo n.º 7
0
        public void Can_access_ModelWithFieldsOfDifferentTypes()
        {
            var idAccessor = TypeProperties <ModelWithFieldsOfDifferentTypes> .GetAccessor("Id");

            var nameAccessor = TypeProperties <ModelWithFieldsOfDifferentTypes> .GetAccessor("Name");

            var longIdAccessor = TypeProperties <ModelWithFieldsOfDifferentTypes> .GetAccessor("LongId");

            var guidAccessor = TypeProperties <ModelWithFieldsOfDifferentTypes> .GetAccessor("Guid");

            var boolAccessor = TypeProperties <ModelWithFieldsOfDifferentTypes> .GetAccessor("Bool");

            var dateTimeAccessor = TypeProperties <ModelWithFieldsOfDifferentTypes> .GetAccessor("DateTime");

            var original = ModelWithFieldsOfDifferentTypesFactory.Instance.CreateInstance(1);

            Assert.That(idAccessor.PublicGetter(original), Is.EqualTo(original.Id));
            Assert.That(nameAccessor.PublicGetter(original), Is.EqualTo(original.Name));
            Assert.That(longIdAccessor.PublicGetter(original), Is.EqualTo(original.LongId));
            Assert.That(guidAccessor.PublicGetter(original), Is.EqualTo(original.Guid));
            Assert.That(boolAccessor.PublicGetter(original), Is.EqualTo(original.Bool));
            Assert.That(dateTimeAccessor.PublicGetter(original), Is.EqualTo(original.DateTime));

            var to = ModelWithFieldsOfDifferentTypesFactory.Instance.CreateInstance(2);

            idAccessor.PublicSetter(original, to.Id);
            nameAccessor.PublicSetter(original, to.Name);
            longIdAccessor.PublicSetter(original, to.LongId);
            guidAccessor.PublicSetter(original, to.Guid);
            boolAccessor.PublicSetter(original, to.Bool);
            dateTimeAccessor.PublicSetter(original, to.DateTime);

            ModelWithFieldsOfDifferentTypesFactory.Instance.AssertIsEqual(original, to);
        }
Exemplo n.º 8
0
 private static void InitUserFieldDefinition(Type modelType, FieldDefinition fieldDef)
 {
     if (fieldDef.PropertyInfo == null)
     {
         fieldDef.PropertyInfo = TypeProperties.Get(modelType).GetPublicProperty(fieldDef.Name);
     }
 }
Exemplo n.º 9
0
 public ApiParameterModel(ApiParameterDescription apiParameterDescription)
 {
     Type                = apiParameterDescription.ParameterDescriptor.ParameterType.Name;
     TypeProperties      = apiParameterDescription.ParameterDescriptor.ParameterType.GetProperties().Select(k => k.Name).ToList();
     TypePropertiesLower = TypeProperties.Select(a => a[0].ToString().ToLower() + a.Substring(1)).ToList();
     Name                = apiParameterDescription.Name;
     IsUriParameter      = apiParameterDescription.Source == ApiParameterSource.FromUri;
     IsClass             = !apiParameterDescription.ParameterDescriptor.ParameterType.FullName.Contains("System");
     IsArray             = apiParameterDescription.ParameterDescriptor.ParameterType.IsArray;
 }
Exemplo n.º 10
0
            internal TypeResponse(Dictionary <string, string> body, TypeProperties properties)
            {
                if ((body == null) || (properties == null))
                {
                    throw new ArgumentNullException(nameof(body) + " || " + nameof(properties));
                }

                Body       = body;
                Properties = properties;
            }
Exemplo n.º 11
0
        static IEnumerable <PropertyInfo> GetTypeProperties(Type type)
        {
            IEnumerable <PropertyInfo> props;

            if (!TypeProperties.TryGetValue(type, out props))
            {
                TypeProperties[type] = props =
                    type.GetProperties(PropertyBinding)
                    .Where(p => p.GetCustomAttributes(IgnoreAttribute, true).Length < 1)
                    .OrderBy(p => p.Name);
            }
            return(props);
        }
        public void Can_use_getter_and_setter_on_ValueTypeProps()
        {
            var typeFields = TypeProperties.Get(typeof(ValueTypeProps));

            var o = (object)new ValueTypeProps {
                S = "foo", I = 1
            };

            typeFields.GetPublicSetter("S")(o, "bar");
            Assert.That(typeFields.GetPublicGetter("S")(o), Is.EqualTo("bar"));

            typeFields.GetPublicSetter("I")(o, 2);
            Assert.That(typeFields.GetPublicGetter("I")(o), Is.EqualTo(2));
        }
Exemplo n.º 13
0
        public static void Init()
        {
            // Use reflection to avoid tfm builds and binary dependency on .NET Framework v4.7.2+
            sameSiteFn = TypeProperties <HttpCookie> .GetAccessor("SameSite")?.PublicSetter;

            if (sameSiteFn != null)
            {
                var sameSiteMode = typeof(HttpCookie).Assembly.GetType("System.Web.SameSiteMode");
                if (sameSiteMode != null)
                {
                    sameSiteNone   = (Enum)Enum.Parse(sameSiteMode, "None");
                    sameSiteStrict = (Enum)Enum.Parse(sameSiteMode, "Strict");
                }
            }
        }
        public void Can_get_result_of_Task()
        {
            var tcs  = new TaskCompletionSource <string>();
            var task = tcs.Task;

            tcs.SetResult("foo");

            var fn    = TypeProperties.Get(task.GetType()).GetPublicGetter("Result");
            var value = fn(task);

            Assert.That(value, Is.EqualTo("foo"));

            fn    = TypeProperties.Get(task.GetType()).GetPublicGetter("Result");
            value = fn(task);
            Assert.That(value, Is.EqualTo("foo"));
        }
Exemplo n.º 15
0
        public object GetValue(object instance)
        {
            var type = instance.GetType();

            if (PropertyInfo.DeclaringType?.IsAssignableFrom(type) != true)
            {
                if (instance is IDictionary d)
                {
                    return(d[Name]);
                }

                var accessor = TypeProperties.Get(type).GetAccessor(Name);
                return(accessor?.PublicGetter(instance));
            }

            return(this.GetValueFn?.Invoke(instance));
        }
        public void Can_use_TypedProperties_accessor()
        {
            var runtimeType = typeof(MyType);
            var typeProps   = TypeProperties.Get(runtimeType); //Equivalent to:
            //  typeProps = TypeProperties<MyType>.Instance;

            var instance = runtimeType.CreateInstance();

            var propAccessor = typeProps.GetAccessor("LongProp");

            propAccessor.PublicSetter(instance, 1L);
            Assert.That(propAccessor.PublicGetter(instance), Is.EqualTo(1));

            typeProps.GetPublicSetter("StringProp")(instance, "foo");
            var value = typeProps.GetPublicGetter("StringProp")(instance);

            Assert.That(value, Is.EqualTo("foo"));
        }
Exemplo n.º 17
0
 /// <summary>
 /// Determines whether the specified type has a given set of properties such as being public, sealed, etc.
 /// The method asserts if one or more of the properties are not satisfied.
 /// </summary>
 /// <param name="type">The type to test for properties.</param>
 /// <param name="typeProperties">The set of type properties to test for.</param>
 /// <param name="isAssignableFrom">Verify that the type to test is assignable from this type.</param>
 public void HasProperties(Type type, TypeProperties typeProperties, Type isAssignableFrom)
 {
     TypeAssert.CheckProperty(type, (typeProperties & TypeProperties.IsAbstract) > 0, type.GetTypeInfo().IsAbstract, "abstract");
     TypeAssert.CheckProperty(type, (typeProperties & TypeProperties.IsClass) > 0, type.GetTypeInfo().IsClass, "a class");
     TypeAssert.CheckProperty(type, (typeProperties & TypeProperties.IsDisposable) > 0, typeof(IDisposable).IsAssignableFrom(type), "disposable");
     TypeAssert.CheckProperty(type, (typeProperties & TypeProperties.IsEnum) > 0, type.GetTypeInfo().IsEnum, "an enum");
     TypeAssert.CheckProperty(type, (typeProperties & TypeProperties.IsGenericType) > 0, type.GetTypeInfo().IsGenericType, "a generic type");
     TypeAssert.CheckProperty(type, (typeProperties & TypeProperties.IsGenericTypeDefinition) > 0, type.GetTypeInfo().IsGenericTypeDefinition, "a generic type definition");
     TypeAssert.CheckProperty(type, (typeProperties & TypeProperties.IsInterface) > 0, type.GetTypeInfo().IsInterface, "an interface");
     TypeAssert.CheckProperty(type, (typeProperties & TypeProperties.IsNestedPrivate) > 0, type.GetTypeInfo().IsNestedPrivate, "nested private");
     TypeAssert.CheckProperty(type, (typeProperties & TypeProperties.IsNestedPublic) > 0, type.GetTypeInfo().IsNestedPublic, "nested public");
     TypeAssert.CheckProperty(type, (typeProperties & TypeProperties.IsPublic) > 0, type.GetTypeInfo().IsPublic, "public");
     TypeAssert.CheckProperty(type, (typeProperties & TypeProperties.IsSealed) > 0, type.GetTypeInfo().IsSealed, "sealed");
     TypeAssert.CheckProperty(type, (typeProperties & TypeProperties.IsVisible) > 0, type.GetTypeInfo().IsVisible, "visible");
     if (isAssignableFrom != null)
     {
         TypeAssert.CheckProperty(type, true, isAssignableFrom.GetTypeInfo().IsAssignableFrom(type.GetTypeInfo()), String.Format("assignable from {0}", isAssignableFrom.FullName));
     }
 }
Exemplo n.º 18
0
        /// <summary>
        /// Updates this schema so it can no longer generate a given problem when compared to another schema.
        /// </summary>
        /// <param name="problem">The change problem</param>
        public void ResolveProblem(ChangeProblem problem)
        {
            switch (problem.ProblemType)
            {
            case ChangeProblemType.DeletionNeeded:
                // Remove the problem for which deletion was needed
                TypeProperties.Remove(problem.TypeName);
                break;

            case ChangeProblemType.PropertyDropped:
            case ChangeProblemType.PropertyDroppedFromSummary:
                // Remove the property which was dropped
                TypeProperties[problem.TypeName].Remove(problem.PropertyName);
                break;

            // Problems not requiring data modification
            case ChangeProblemType.NotBinarySerializable:
            case ChangeProblemType.NullObjectValue:
                break;
            }
        }
Exemplo n.º 19
0
        private static object PropValue(object targetValue, Type targetType, string name)
        {
            var memberFn = TypeProperties.Get(targetType).GetPublicGetter(name)
                           ?? TypeFields.Get(targetType).GetPublicGetter(name);

            if (memberFn != null)
            {
                return(memberFn(targetValue));
            }

            var indexerMethod = targetType.GetInstanceMethod("get_Item");

            if (indexerMethod != null)
            {
                var fn  = indexerMethod.GetInvoker();
                var ret = fn(targetValue, name);
                return(ret ?? JsNull.Value);
            }

            throw new ArgumentException($"'{targetType.Name}' does not have a '{name}' property or field");
        }
Exemplo n.º 20
0
        /// <summary>
        /// Reverts part of the schema relevant to a problem to the state which when compared to its current
        /// state, regenerates the problem. The inverse of ResolveProblem.
        /// </summary>
        /// <param name="oldSchema">the old schema which generated the problem when compared to the current schema</param>
        /// <param name="problem">the problem it generated</param>
        public void ApplyProblem(ContentModelSchema oldSchema, ChangeProblem problem)
        {
            switch (problem.ProblemType)
            {
            case ChangeProblemType.DeletionNeeded:
                // copy the deleted type to the new schema
                TypeProperties.Add(problem.TypeName, oldSchema.TypeProperties[problem.TypeName]);
                break;

            case ChangeProblemType.PropertyDropped:
            case ChangeProblemType.PropertyDroppedFromSummary:
                // copy the dropped property to the new schema
                TypeProperties[problem.TypeName].Add(problem.PropertyName, oldSchema.TypeProperties[problem.TypeName][problem.PropertyName]);
                break;

            // Problems not requiring data modification
            case ChangeProblemType.NotBinarySerializable:
            case ChangeProblemType.NullObjectValue:
                break;
            }
        }
Exemplo n.º 21
0
        private object GetTypeTemplateProperty(string domainID, TypeProperties propertyName)
        {
            var template = this.GetDomainHost <ITypeTemplate>(domainID);

            return(template.Dispatcher.Invoke(() =>
            {
                if (propertyName == TypeProperties.Name)
                {
                    return (object)template.TypeName;
                }
                else if (propertyName == TypeProperties.IsFlag)
                {
                    return (object)template.IsFlag;
                }
                else if (propertyName == TypeProperties.Comment)
                {
                    return (object)template.Comment;
                }

                throw new NotImplementedException();
            }));
        }
Exemplo n.º 22
0
        /// <summary>
        /// Updates this schema so it can no longer generate a given problem when compared to another schema.
        /// </summary>
        /// <param name="problem">The change problem</param>
        public void ResolveProblem(ChangeProblem problem)
        {
            string aqTypeName = problem.GetAssemblyQualifiedTypeName();

            switch (problem.ProblemType)
            {
            case ChangeProblemType.DeletionNeeded:
                // Remove the problem for which deletion was needed
                TypeProperties.Remove(aqTypeName);
                break;

            case ChangeProblemType.PropertyDropped:
            case ChangeProblemType.PropertyDroppedFromSummary:
                // Remove the property which was dropped
                TypeProperties[aqTypeName].Remove(problem.PropertyName);
                break;

            // Problems not requiring data modification
            case ChangeProblemType.NullObjectValue:
                break;
            }
        }
        public void Can_cache_ValueTuple_field_accessors()
        {
            var typeProperties = TypeProperties.Get(typeof(RefTypeProps));

            var oTuple = (object)CreateTypedTuple();

            typeProperties.GetPublicSetter("S")(oTuple, "bar");
            typeProperties.GetPublicSetter("I")(oTuple, 10);
            typeProperties.GetPublicSetter("L")(oTuple, 20L);
            typeProperties.GetPublicSetter("D")(oTuple, 4.4d);

            Assert.That(typeProperties.GetPublicGetter("S")(oTuple), Is.EqualTo("bar"));
            Assert.That(typeProperties.GetPublicGetter("I")(oTuple), Is.EqualTo(10));
            Assert.That(typeProperties.GetPublicGetter("L")(oTuple), Is.EqualTo(20));
            Assert.That(typeProperties.GetPublicGetter("D")(oTuple), Is.EqualTo(4.4));

            var tuple = (RefTypeProps)oTuple;

            Assert.That(tuple.S, Is.EqualTo("bar"));
            Assert.That(tuple.I, Is.EqualTo(10));
            Assert.That(tuple.L, Is.EqualTo(20));
            Assert.That(tuple.D, Is.EqualTo(4.4));
        }
Exemplo n.º 24
0
        private static object PropValue(object targetValue, Type targetType, string name)
        {
            var memberFn = TypeProperties.Get(targetType).GetPublicGetter(name)
                           ?? TypeFields.Get(targetType).GetPublicGetter(name);

            if (memberFn != null)
            {
                return(memberFn(targetValue));
            }

            var methods       = targetType.GetInstanceMethods();
            var indexerMethod =
                methods.FirstOrDefault(x => x.Name == "get_Item" && x.GetParameters().Any(p => p.ParameterType == typeof(string))) ??
                methods.FirstOrDefault(x => x.Name == "get_Item" && x.GetParameters().Any(p => p.ParameterType != typeof(string)));

            if (indexerMethod != null)
            {
                var fn  = indexerMethod.GetInvoker();
                var ret = fn(targetValue, name);
                return(ret);
            }

            throw new ArgumentException($"'{targetType.Name}' does not have a '{name}' property or field");
        }
Exemplo n.º 25
0
 internal TypeResponse(Dictionary <string, string> body, TypeProperties properties)
 {
     Body       = body ?? throw new ArgumentNullException(nameof(body));
     Properties = properties ?? throw new ArgumentNullException(nameof(properties));
 }
Exemplo n.º 26
0
        public async Task Any(ModifyValidationRules request)
        {
            var appHost = HostContext.AssertAppHost();
            var feature = appHost.AssertPlugin <ValidationFeature>();
            await RequestUtils.AssertAccessRoleAsync(base.Request, accessRole : feature.AccessRole, authSecret : request.AuthSecret);

            var utcNow   = DateTime.UtcNow;
            var userName = (await base.GetSessionAsync()).GetUserAuthName();
            var rules    = request.SaveRules;

            if (!rules.IsEmpty())
            {
                foreach (var rule in rules)
                {
                    if (rule.Type == null)
                    {
                        throw new ArgumentNullException(nameof(rule.Type));
                    }

                    var existingType = appHost.Metadata.FindDtoType(rule.Type);
                    if (existingType == null)
                    {
                        throw new ArgumentException(@$ "{rule.Type} does not exist", nameof(rule.Type));
                    }

                    if (rule.Validator == "")
                    {
                        rule.Validator = null;
                    }
                    if (rule.Condition == "")
                    {
                        rule.Condition = null;
                    }
                    if (rule.Field == "")
                    {
                        rule.Field = null;
                    }
                    if (rule.ErrorCode == "")
                    {
                        rule.ErrorCode = null;
                    }
                    if (rule.Message == "")
                    {
                        rule.Message = null;
                    }
                    if (rule.Notes == "")
                    {
                        rule.Notes = null;
                    }

                    if (rule.Field != null && TypeProperties.Get(existingType).GetAccessor(rule.Field) == null)
                    {
                        throw new ArgumentException(@$ "{rule.Field} does not exist on {rule.Type}", nameof(rule.Field));
                    }

                    if (rule.Validator != null)
                    {
                        object validator;
                        try
                        {
                            validator = appHost.EvalExpression(rule.Validator);
                            if (validator == null)
                            {
                                throw new ArgumentException(@$ "Validator does not exist", nameof(rule.Validator));
                            }
                        }
                        catch (Exception e)
                        {
                            throw new ArgumentException(@$ "Invalid Validator: " + e.Message, nameof(rule.Validator));
                        }

                        var validators     = (validator as List <object>) ?? TypeConstants.EmptyObjectList;
                        var firstValidator = validator is IPropertyValidator pv
                            ? pv
                            : validator is ITypeValidator tv
                            ? tv
                            : validators?.FirstOrDefault() ?? validator;

                        if (rule.Field != null && !(firstValidator is IPropertyValidator && validators.All(v => v is IPropertyValidator)))
                        {
                            throw new ArgumentException(@$ "{nameof(IPropertyValidator)} is expected but was {(validators?.FirstOrDefault(v => !(v is IPropertyValidator)) ?? firstValidator).GetType().Name}", nameof(rule.Validator));
                        }

                        if (rule.Field == null && !(firstValidator is ITypeValidator && validators.All(v => v is ITypeValidator)))
                        {
                            throw new ArgumentException(@$ "{nameof(ITypeValidator)} is expected but was {(validators?.FirstOrDefault(v => !(v is IPropertyValidator)) ?? firstValidator).GetType().Name}", nameof(rule.Validator));
                        }

                        if (rule.Condition != null)
                        {
                            throw new ArgumentException(@$ "Only {nameof(rule.Validator)} or {nameof(rule.Condition)} can be specified, not both", nameof(rule.Condition));
                        }
                    }
                    else
                    {
                        if (rule.Condition == null)
                        {
                            throw new ArgumentNullException(nameof(rule.Validator), @$ "{nameof(rule.Validator)} or {nameof(rule.Condition)} is required");
                        }

                        try
                        {
                            var ast = Validators.ParseCondition(appHost.ScriptContext, rule.Condition);
                            await ast.Init().ConfigAwait();
                        }
                        catch (Exception e)
                        {
                            var useEx = e is ScriptException se ? se.InnerException ?? e : e;
                            throw new ArgumentException(useEx.Message, nameof(rule.Condition));
                        }
                    }

                    if (rule.CreatedBy == null)
                    {
                        rule.CreatedBy   = userName;
                        rule.CreatedDate = utcNow;
                    }
                    rule.ModifiedBy   = userName;
                    rule.ModifiedDate = utcNow;
                }

                await ValidationSource.SaveValidationRulesAsync(rules).ConfigAwait();
            }

            if (!request.SuspendRuleIds.IsEmpty())
            {
                var suspendRules = await ValidationSource.GetValidateRulesByIdsAsync(request.SuspendRuleIds).ConfigAwait();

                foreach (var suspendRule in suspendRules)
                {
                    suspendRule.SuspendedBy   = userName;
                    suspendRule.SuspendedDate = utcNow;
                }

                await ValidationSource.SaveValidationRulesAsync(suspendRules).ConfigAwait();
            }

            if (!request.UnsuspendRuleIds.IsEmpty())
            {
                var unsuspendRules = await ValidationSource.GetValidateRulesByIdsAsync(request.UnsuspendRuleIds).ConfigAwait();

                foreach (var unsuspendRule in unsuspendRules)
                {
                    unsuspendRule.SuspendedBy   = null;
                    unsuspendRule.SuspendedDate = null;
                }

                await ValidationSource.SaveValidationRulesAsync(unsuspendRules).ConfigAwait();
            }

            if (!request.DeleteRuleIds.IsEmpty())
            {
                await ValidationSource.DeleteValidationRulesAsync(request.DeleteRuleIds.ToArray()).ConfigAwait();
            }

            if (request.ClearCache.GetValueOrDefault())
            {
                await ValidationSource.ClearCacheAsync().ConfigAwait();
            }
        }
Exemplo n.º 27
0
        internal static IDbCommand SetParameters(this IDbCommand dbCmd, Type type, object anonType, bool excludeDefaults, ref string sql)
        {
            if (anonType == null)
            {
                return(dbCmd);
            }

            dbCmd.Parameters.Clear();

            var modelDef        = type.GetModelDefinition();
            var dialectProvider = dbCmd.GetDialectProvider();
            var fieldMap        = type.IsUserType() //Ensure T != Scalar<int>()
                ? dialectProvider.GetFieldDefinitionMap(modelDef)
                : null;

            var sqlCopy = sql; //C# doesn't allow changing ref params in lambda's
            Dictionary <string, PropertyAccessor> anonTypeProps = null;

            var paramIndex = 0;

            anonType.ToObjectDictionary().ForEachParam(modelDef, excludeDefaults, (propName, columnName, value) =>
            {
                var propType = value?.GetType() ?? ((anonTypeProps ??= TypeProperties.Get(anonType.GetType()).PropertyMap)
                                                    .TryGetValue(propName, out var pType)
                        ? pType.PropertyInfo.PropertyType
                        : typeof(object));
                var inValues = GetMultiValues(value);
                if (inValues != null)
                {
                    var sb = StringBuilderCache.Allocate();
                    foreach (var item in inValues)
                    {
                        var p           = dbCmd.CreateParameter();
                        p.ParameterName = "v" + paramIndex++;

                        if (sb.Length > 0)
                        {
                            sb.Append(',');
                        }
                        sb.Append(dialectProvider.ParamString + p.ParameterName);

                        p.Direction = ParameterDirection.Input;
                        dialectProvider.InitDbParam(p, item.GetType());

                        dialectProvider.SetParamValue(p, item, item.GetType());

                        dbCmd.Parameters.Add(p);
                    }

                    var sqlIn = StringBuilderCache.ReturnAndFree(sb);
                    if (string.IsNullOrEmpty(sqlIn))
                    {
                        sqlIn = "NULL";
                    }
                    sqlCopy = sqlCopy?.Replace(dialectProvider.ParamString + propName, sqlIn);
                    if (dialectProvider.ParamString != "@")
                    {
                        sqlCopy = sqlCopy?.Replace("@" + propName, sqlIn);
                    }
                }
                else
                {
                    var p           = dbCmd.CreateParameter();
                    p.ParameterName = propName;
                    p.Direction     = ParameterDirection.Input;
                    dialectProvider.InitDbParam(p, propType);

                    FieldDefinition fieldDef = null;
                    fieldMap?.TryGetValue(columnName, out fieldDef);

                    dialectProvider.SetParamValue(p, value, propType, fieldDef);

                    dbCmd.Parameters.Add(p);
                }
            });
Exemplo n.º 28
0
 /// <summary>
 /// Determines whether the specified type has a given set of properties such as being public, sealed, etc.
 /// The method asserts if one or more of the properties are not satisfied.
 /// </summary>
 /// <typeparam name="T">The type to test for properties.</typeparam>
 /// <param name="typeProperties">The set of type properties to test for.</param>
 public void HasProperties <T>(TypeProperties typeProperties)
 {
     HasProperties(typeof(T), typeProperties);
 }
Exemplo n.º 29
0
 /// <summary>
 /// Determines whether the specified type has a given set of properties such as being public, sealed, etc.
 /// The method asserts if one or more of the properties are not satisfied.
 /// </summary>
 /// <param name="type">The type to test for properties.</param>
 /// <param name="typeProperties">The set of type properties to test for.</param>
 public void HasProperties(Type type, TypeProperties typeProperties)
 {
     HasProperties(type, typeProperties, null);
 }
Exemplo n.º 30
0
 /// <summary>
 /// Determines whether the specified type has a given set of properties such as being public, sealed, etc.
 /// The method asserts if one or more of the properties are not satisfied.
 /// </summary>
 /// <typeparam name="T">The type to test for properties.</typeparam>
 /// <typeparam name="TIsAssignableFrom">Verify that the type to test is assignable from this type.</typeparam>
 /// <param name="typeProperties">The set of type properties to test for.</param>
 public void HasProperties <T, TIsAssignableFrom>(TypeProperties typeProperties)
 {
     HasProperties(typeof(T), typeProperties, typeof(TIsAssignableFrom));
 }