예제 #1
0
        private void Import()
        {
            var repositoryType    = typeof(IRepository <>).MakeGenericType(TargetType);
            var insertOrGetMethod = repositoryType.GetMethod("InsertOrGetWithEquality");
            var saveMethod        = repositoryType.GetMethod("Save");
            var accountProperty   = TargetType.GetProperties()
                                    .Single(info => info.PropertyType.IsInstanceOfType(OwningEntity));
            var repository = ComponentContext.Resolve(repositoryType);
            var toInsert   = FileParser.Parse(Source).ToList();

            toInsert = Order(toInsert);
            if (UniqueIdGroupingFunc != null)
            {
                var grouping = toInsert.GroupBy(UniqueIdGroupingFunc);
                foreach (var group in grouping)
                {
                    var uniqueId = 1;
                    var subList  = Order(group);
                    foreach (var bankTransactionEntity in subList)
                    {
                        var prop = bankTransactionEntity.GetType().GetProperty("UniqueId");
                        prop.SetValue(bankTransactionEntity, uniqueId++);
                    }
                }
            }
            foreach (var entity in toInsert)
            {
                accountProperty.SetValue(entity, OwningEntity);
                var persistedEntity = insertOrGetMethod.Invoke(repository, new[] { entity });
            }
            saveMethod.Invoke(repository, null);
        }
예제 #2
0
 void VerifyMethodsInitialized()
 {
     if (_methodsCache == null)
     {
         lock (_syncRoot)
         {
             Thread.MemoryBarrier();
             if (_methodsCache == null)
             {
                 var allProperties = TargetType.GetProperties(BindingFlags.Public | BindingFlags.Instance |
                                                              BindingFlags.Static | BindingFlags.FlattenHierarchy);
                 _methodsCache = (from method in TargetType.GetMethods(
                                      BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.FlattenHierarchy)
                                  where !allProperties.Any(x => x.GetGetMethod() == method || x.GetSetMethod() == method)
                                  select new ReflectionBasedMethod(
                                      // this,
                                      method.DeclaringType == TargetType
             ? (IMember)this
             : TypeSystem.FromClr(method.DeclaringType),
                                      method) as IMethod)
                                 .ToLookup(x => x.Name, StringComparer.OrdinalIgnoreCase);
             }
         }
     }
 }
예제 #3
0
        private void SetAutoMaps()
        {
            const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;

            var sourceMaps = SourceType.GetProperties(flags);
            var targetMaps = TargetType.GetProperties(flags);

            foreach (var sourceMap in sourceMaps)
            {
                var targetMap = targetMaps.FirstOrDefault(p =>
                                                          p.Name == sourceMap.Name && p.PropertyType == sourceMap.PropertyType);

                if (targetMap != null)
                {
                    var sourceMapItem = new MapItem {
                        Name = sourceMap.Name, Type = sourceMap.PropertyType
                    };
                    var mappingInfo   = CreateMappingInfo(sourceMapItem);
                    var targetMapItem = new MapItem {
                        Name = targetMap.Name, Type = targetMap.PropertyType
                    };
                    mappingInfo.Target = targetMapItem;
                    var typeArgs      = new [] { targetMap.PropertyType };
                    var converterType = typeof(DefaultTypeConverter <>);
                    mappingInfo.Converter = converterType.MakeGenericType(typeArgs);
                }
            }
        }
예제 #4
0
        protected internal override void Initialize(IntermediateSerializer serializer)
        {
            // If we have a base type then we need to deserialize it first.
            if (TargetType.BaseType != null)
            {
                _baseSerializer = serializer.GetTypeSerializer(TargetType.BaseType);
            }

            // Cache all our serializable properties.
            var properties = TargetType.GetProperties(_bindingFlags);

            foreach (var prop in properties)
            {
                ElementInfo info;
                if (GetElementInfo(serializer, prop, out info))
                {
                    _elements.Add(info);
                }
            }

            // Cache all our serializable fields.
            var fields = TargetType.GetFields(_bindingFlags);

            foreach (var field in fields)
            {
                ElementInfo info;
                if (GetElementInfo(serializer, field, out info))
                {
                    _elements.Add(info);
                }
            }
        }
 /// <summary>
 /// Initializes the lazy properties.
 /// </summary>
 protected virtual void InitLazyProperties()
 {
     //LazyProperties = new Lazy<IDictionary<string, PropertyInfo>>(() =>
     //    {
     //        return TargetType.GetProperties().ToDictionary(p => p.Name);
     //    }, true);
     _lazyProperties = TargetType.GetProperties().ToDictionary(p => p.Name);
 }
예제 #6
0
        protected internal override void Initialize(ContentTypeReaderManager manager)
        {
            base.Initialize(manager);

            Type baseType = TargetType.BaseType;

            if (baseType != null && baseType != typeof(object))
            {
                baseTypeReader = manager.GetTypeReader(baseType);
            }

            constructor = TargetType.GetDefaultConstructor();

            const BindingFlags attrs = (
                BindingFlags.NonPublic |
                BindingFlags.Public |
                BindingFlags.Instance |
                BindingFlags.DeclaredOnly
                );

            /* Sometimes, overridden properties of abstract classes can show up even with
             * BindingFlags.DeclaredOnly is passed to GetProperties. Make sure that
             * all properties in this list are defined in this class by comparing
             * its get method with that of its base class. If they're the same
             * Then it's an overridden property.
             */
            PropertyInfo[] properties = TargetType.GetProperties(attrs);
            FieldInfo[]    fields     = TargetType.GetFields(attrs);
            readers = new List <ReadElement>(fields.Length + properties.Length);

            // Gather the properties.
            foreach (PropertyInfo property in properties)
            {
                MethodInfo pm = property.GetGetMethod(true);
                if (pm == null || pm != pm.GetBaseDefinition())
                {
                    continue;
                }

                ReadElement read = GetElementReader(manager, property);
                if (read != null)
                {
                    readers.Add(read);
                }
            }

            // Gather the fields.
            foreach (FieldInfo field in fields)
            {
                ReadElement read = GetElementReader(manager, field);
                if (read != null)
                {
                    readers.Add(read);
                }
            }
        }
예제 #7
0
        IEnumerable <IValidatedElement> IValidatedType.GetValidatedProperties()
        {
            var flyweight = new MetadataValidatedElement(Ruleset);

            foreach (PropertyInfo propertyInfo in TargetType.GetProperties(BindingFlags.Public | BindingFlags.Instance))
            {
                if (ValidationReflectionHelper.IsValidProperty(propertyInfo))
                {
                    flyweight.UpdateFlyweight(propertyInfo);
                    yield return(flyweight);
                }
            }
        }
예제 #8
0
        private void ReadAttributes()
        {
            // todo: use Expression API to generate getters/setters instead of reflection
            // [low priority due to low likelyness of 1M+ invocations]

            // todo: add [CanPersist] attribute and use it for canReadFunc

            //set key if [TrackingKey] detected
            PropertyInfo keyProperty = TargetType.GetProperties().SingleOrDefault(pi => pi.IsDefined(typeof(TrackingIdAttribute), true));

            if (keyProperty != null)
            {
                idFunc = (t) => keyProperty.GetValue(t, null).ToString();
            }

            //add properties that have [Trackable] applied
            foreach (PropertyInfo pi in TargetType.GetProperties())
            {
                TrackableAttribute propTrackableAtt = pi.GetCustomAttributes(true).OfType <TrackableAttribute>().SingleOrDefault();
                if (propTrackableAtt != null)
                {
                    //use [DefaultValue] if present
                    DefaultValueAttribute defaultAtt = pi.CustomAttributes.OfType <DefaultValueAttribute>().SingleOrDefault();
                    if (defaultAtt != null)
                    {
                        TrackedProperties[pi.Name] = new TrackedPropertyInfo(x => pi.GetValue(x), (x, v) => pi.SetValue(x, v), defaultAtt.Value);
                    }
                    else
                    {
                        TrackedProperties[pi.Name] = new TrackedPropertyInfo(x => pi.GetValue(x), (x, v) => pi.SetValue(x, v));
                    }
                }
            }

            foreach (EventInfo eventInfo in TargetType.GetEvents())
            {
                var attributes = eventInfo.GetCustomAttributes(true);

                if (attributes.OfType <PersistOnAttribute>().Any())
                {
                    PersistOn(eventInfo.Name);
                }

                if (attributes.OfType <StopTrackingOnAttribute>().Any())
                {
                    StopTrackingOn(eventInfo.Name);
                }
            }
        }
예제 #9
0
        public ModelMapper(string[] propNames)
        {
            TargetType    = typeof(T);
            PropertyNames = propNames.ToArray();

            Mapper = TargetType.DelegateForMap(TargetType, MemberTypes.Property, MemberTypes.Property, Flags.InstancePublic, PropertyNames);

            PropertyGetters = new Dictionary <string, MemberGetter>();

            var props = TargetType.GetProperties();

            foreach (var prop in props)
            {
                PropertyGetters.Add(prop.Name, TargetType.DelegateForGetPropertyValue(prop.Name));
            }
        }
예제 #10
0
        public SqlServerAdapter(string connectionString)
            : base(connectionString)
        {
            var keyProperty =
                TargetType.GetProperties().FirstOrDefault(prop => Attribute.IsDefined(prop, typeof(KeyAttribute)));

            if (keyProperty != null)
            {
                var columnAttribute = keyProperty.GetCustomAttributes(typeof(ColumnAttribute), true).FirstOrDefault();
                _sortField = columnAttribute != null ? ((ColumnAttribute)columnAttribute).Name : keyProperty.Name;
            }
            else
            {
                var columnAttribute = TargetType.GetProperties().First().GetCustomAttributes(typeof(ColumnAttribute), true).FirstOrDefault();
                _sortField = columnAttribute != null ? ((ColumnAttribute)columnAttribute).Name : TargetType.GetProperties().First().Name;
            }
        }
        internal PropertiesNotMapped GetPropertiesNotMapped()
        {
            // 克隆属性信息
            var sourceProperties = SourceType.GetProperties().ToList();
            var targetProperties = TargetType.GetProperties().ToList();

            var visitor = new PropertiesVisitor(TargetType);
            foreach (var members in memberForNew)
            {
                var members1 = members;
                sourceProperties.RemoveAll((p) => members1.Member.Name == p.Name);
                targetProperties.RemoveAll((p) => visitor.GetProperties(members.Expression).Contains(p));
            }

            // 检查被忽略映射的成员
            sourceProperties.RemoveAll((p) => _propertiesToIgnore.Contains(p));
            return new PropertiesNotMapped
            {
                sourceProperties = sourceProperties,
                targetProperties = targetProperties
            };
        }
예제 #12
0
 public BaseDAO()
 {
     fields = new List <object[]>();
     PropertyInfo[] p = TargetType.GetProperties();
     foreach (PropertyInfo property in p)
     {
         String fieldName  = property.Name;
         String columnName = StringUtils.CamelCaseToUnderline(fieldName);
         Type   csType     = property.PropertyType;
         if (!IsBasicType(csType))
         {
             continue;
         }
         String dbType = null;
         if (csType == typeof(int) || csType == typeof(long))
         {
             dbType = "int";
         }
         else if (csType == typeof(float) || csType == typeof(double))
         {
             dbType = "double";
         }
         else if (csType == typeof(string))
         {
             dbType = "varchar(" + VARCHAR_DEFAULT_LENGTH + ")";
         }
         else if (csType == typeof(DateTime))
         {
             dbType = "timestamp";
         }
         if (dbType == null)
         {
             continue;
         }
         object[] arr = { property, fieldName, columnName, csType, dbType };
         fields.Add(arr);
     }
 }
예제 #13
0
        private void LoadValidators()
        {
            var props = TargetType.GetProperties();

            PropertyDescriptors = props.Select(prop => new PropertyDescriptor(prop)).ToDictionary(p => p.Property.Name);

            ErrorValidators = props.ToDictionary(key =>
                                                 new PropertyDescriptor(key),
                                                 value =>
            {
                return(value.GetCustomAttributes <ValidationAttribute>(true)
                       .Where(a => !(a is WarningValidationAttribute)).ToList());
            }
                                                 );
            WarningValidators = props.ToDictionary(key => new PropertyDescriptor(key),
                                                   value =>
            {
                return(value.GetCustomAttributes <ValidationAttribute>(true)
                       .Where(a => (a is WarningValidationAttribute)).ToList());
            }
                                                   );
            ClassValidators = TargetType.GetCustomAttributes <ValidationAttribute>(false).ToList();
        }
예제 #14
0
        internal PropertiesNotMapped GetPropertiesNotMapped()
        {
            PropertiesNotMapped result = new PropertiesNotMapped();
            // Clone PropertyInfo.
            List <PropertyInfo> sourceProperties = SourceType.GetProperties().ToList();
            List <PropertyInfo> targetProperties = TargetType.GetProperties().ToList();

            PropertiesVisitor visitor = new PropertiesVisitor(TargetType);

            for (int i = 0; i < memberForNew.Count; i++)
            {
                var members = memberForNew[i];
                // Simple remove.
                sourceProperties.RemoveAll((p) => members.Member.Name == p.Name);
                targetProperties.RemoveAll((p) => visitor.GetProperties(members.Expression).Contains(p));
            }
            // Check the ignored properties.
            sourceProperties.RemoveAll((p) => propertiesToIgnore.Contains(p));
            result.sourceProperties = sourceProperties;
            result.targetProperties = targetProperties;

            return(result);
        }
        internal PropertiesNotMapped GetPropertiesNotMapped()
        {
            PropertiesNotMapped result = new PropertiesNotMapped();
            // 克隆属性信息
            List <PropertyInfo> sourceProperties = SourceType.GetProperties().ToList();
            List <PropertyInfo> targetProperties = TargetType.GetProperties().ToList();

            PropertiesVisitor visitor = new PropertiesVisitor(TargetType);

            foreach (var members in memberForNew)
            {
                var members1 = members;
                sourceProperties.RemoveAll((p) => members1.Member.Name == p.Name);
                targetProperties.RemoveAll((p) => visitor.GetProperties(members.Expression).Contains(p));
            }

            // 检查被忽略映射的成员
            sourceProperties.RemoveAll((p) => _propertiesToIgnore.Contains(p));
            result.sourceProperties = sourceProperties;
            result.targetProperties = targetProperties;

            return(result);
        }
예제 #16
0
        private int PropertyPropLogic()
        {
            int retval = 0;

            EditorUtility.DisplayProgressBar("Generating " + ClassName, "Property Scanning Props", 0);
            var props = TargetType.GetProperties(GetBindingFlags());

            for (int i = 0; i < props.Length; i++)
            {
                if (helper.IsTypeHandled(props[i].PropertyType) && props[i].GetIndexParameters().Length == 0 && !IsObsolete(props[i].GetCustomAttributes(false)))
                {
                    var actualName    = props[i].Name;
                    var upperCaseName = Char.ToUpperInvariant(actualName[0]) + actualName.Substring(1);
                    //add it to the enum
                    AddToEnum(upperCaseName);

                    if (props[i].CanRead)
                    {
                        //add it to the get
                        AddToGet(props[i].PropertyType, upperCaseName, actualName);
                    }
                    if (props[i].CanWrite)
                    {
                        //add it to the set
                        AddToSet(props[i].PropertyType, upperCaseName, actualName);
                    }

                    if (props[i].CanRead || props[i].CanWrite)
                    {
                        retval++;
                    }
                }
            }

            return(retval);
        }
예제 #17
0
        public ViewMetaData()
        {
            ViewPortDescriptors = new Dictionary <string, BaseDescriptor>();

            TargetType = typeof(T);
            foreach (var item in TargetType.GetProperties())
            {
                TypeCode code = Type.GetTypeCode(item.PropertyType.GetTypeInfo().IsGenericType ? item.PropertyType.GetGenericArguments()[0] : item.PropertyType);
                switch (code)
                {
                case TypeCode.Boolean:
                    ViewConfig(item.Name).AsCheckBox();
                    break;

                case TypeCode.Char:
                    ViewConfig(item.Name).AsTextBox().MaxLength(1).RegularExpression(RegularExpression.Letters).Search(LINQ.Query.Operators.Contains);
                    break;

                case TypeCode.DateTime:
                    ViewConfig(item.Name).AsTextBox().FormatAsDate().Search(LINQ.Query.Operators.Range);
                    break;

                case TypeCode.UInt16:
                case TypeCode.UInt32:
                case TypeCode.UInt64:
                    ViewConfig(item.Name).AsTextBox().RegularExpression(RegularExpression.PositiveIntegersAndZero).Search(LINQ.Query.Operators.Range);
                    break;

                case TypeCode.SByte:
                case TypeCode.Int16:
                case TypeCode.Int32:
                case TypeCode.Int64:
                    ViewConfig(item.Name).AsTextBox().RegularExpression(RegularExpression.Integer).Search(LINQ.Query.Operators.Range);
                    break;

                case TypeCode.Object:
                    ViewConfig(item.Name).AsHidden().Ignore();
                    break;

                case TypeCode.Single:
                case TypeCode.Double:
                case TypeCode.Decimal:
                    ViewConfig(item.Name).AsTextBox().RegularExpression(RegularExpression.Float).Search(LINQ.Query.Operators.Range);
                    break;

                case TypeCode.String:
                    ViewConfig(item.Name).AsTextBox().MaxLength(200).Search(LINQ.Query.Operators.Contains);
                    break;

                case TypeCode.Byte:
                case TypeCode.Empty:
                default:
                    ViewConfig(item.Name).AsTextBox();
                    break;
                }
            }
            if (typeof(EditorEntity).IsAssignableFrom(TargetType))
            {
                ViewConfig("CreateBy").AsHidden();
                ViewConfig("CreatebyName").AsTextBox().Hide().ShowInGrid();
                ViewConfig("CreateDate").AsTextBox().Hide().FormatAsDateTime().ShowInGrid().Search(LINQ.Query.Operators.Range);

                ViewConfig("LastUpdateBy").AsHidden();
                ViewConfig("LastUpdateByName").AsTextBox().Hide().ShowInGrid();
                ViewConfig("LastUpdateDate").AsTextBox().Hide().FormatAsDateTime().ShowInGrid().Search(LINQ.Query.Operators.Range);
                ViewConfig("ActionType").AsHidden().AddClass("ActionType");
                ViewConfig("Title").AsTextBox().Order(1).ShowInGrid().Search(LINQ.Query.Operators.Contains).MaxLength(200);
                ViewConfig("Description").AsTextArea().Order(101).MaxLength(500);
                ViewConfig("Status").AsDropDownList().DataSource(DicKeys.RecordStatus, SourceType.Dictionary).ShowInGrid();
            }
            if (typeof(IImage).IsAssignableFrom(TargetType))
            {
                ViewConfig("ImageUrl").AsTextBox();
                ViewConfig("ImageThumbUrl").AsTextBox();
            }

            ViewConfigure();
        }
예제 #18
0
        public void Init()
        {
            Alias      = "T0";
            TargetType = typeof(T);
            foreach (var item in TargetType.GetProperties())
            {
                TypeCode code;
                code = Type.GetTypeCode(item.PropertyType.Name == "Nullable`1" ? item.PropertyType.GetGenericArguments()[0] : item.PropertyType);
                switch (code)
                {
                case TypeCode.Boolean: ViewConfig(item.Name).AsCheckBox(); break;

                case TypeCode.Char: ViewConfig(item.Name).AsTextBox().MaxLength(1).RegularExpression(RegularExpression.Letters); break;

                case TypeCode.DateTime: ViewConfig(item.Name).AsTextBox().FormatAsDate(); break;

                case TypeCode.UInt16:
                case TypeCode.UInt32:
                case TypeCode.UInt64: ViewConfig(item.Name).AsTextBox().RegularExpression(RegularExpression.PositiveIntegersAndZero); break;

                case TypeCode.SByte:
                case TypeCode.Int16:
                case TypeCode.Int32:
                case TypeCode.Int64: ViewConfig(item.Name).AsTextBox().RegularExpression(RegularExpression.Integer); break;

                case TypeCode.Object:
                {
                    ViewConfig(item.Name).AsHidden().Ignore(); break;
                }

                case TypeCode.Single:
                case TypeCode.Double:
                case TypeCode.Decimal:
                {
                    TextBoxHtmlTag tag = ViewConfig(item.Name).AsTextBox().RegularExpression(Easy.Constant.RegularExpression.Float);
                    if (code == TypeCode.Decimal)
                    {
                        tag.Format(FormatStyle.Currency);
                    }
                    break;
                }

                case TypeCode.String: ViewConfig(item.Name).AsTextBox().MaxLength(200);
                    break;

                case TypeCode.DBNull:
                case TypeCode.Byte:
                case TypeCode.Empty:
                default: ViewConfig(item.Name).AsTextBox();
                    break;
                }
                if (code == TypeCode.Object)
                {
                    DataConfig(item.Name).Ignore();
                }
                else
                {
                    DataConfig(item.Name);
                }
            }
            if (typeof(EditorEntity).IsAssignableFrom(TargetType))
            {
                ViewConfig("CreateBy").AsHidden();
                ViewConfig("CreatebyName").AsTextBox().Hide();
                ViewConfig("CreateDate").AsTextBox().Hide().FormatAsDateTime();

                ViewConfig("LastUpdateBy").AsHidden();
                ViewConfig("LastUpdateByName").AsTextBox().Hide();
                ViewConfig("LastUpdateDate").AsTextBox().Hide().FormatAsDateTime();
                ViewConfig("ActionType").AsHidden().AddClass("actionType");
                ViewConfig("Title").AsTextBox().Order(1);
                ViewConfig("Description").AsMutiLineTextBox().Order(101);
                ViewConfig("Status").AsDropDownList().DataSource(Constant.DicKeys.RecordStatus, SourceType.Dictionary);

                DataConfig("CreateBy").Update();
                DataConfig("CreatebyName").Update();
                DataConfig("CreateDate").Update();
                DataConfig("ActionType").Ignore();
            }
            if (typeof(IImage).IsAssignableFrom(TargetType))
            {
                ViewConfig("ImageUrl").AsTextBox().HideInGrid();
                ViewConfig("ImageThumbUrl").AsTextBox().HideInGrid();
            }
            if (IsIgnoreBase())
            {
                IgnoreBase();
            }
            DataConfigure();
            ViewConfigure();
        }
예제 #19
0
            // Rather ugly, but this is where the magic happens.
            // Intended to parse what the selector function really points to so that we can bind
            // a PropertyInfo object on the resulting key before we use it later via reflection.
            private PropertyInfo GetTargetProperty()
            {
                if (Property == null)
                {
                    throw new InvalidOperationException("The property that the foreign key belongs to is not available.");
                }

                var sourceType    = Property.ReflectedType;
                var sourceAsm     = sourceType.Assembly;
                var sourceAsmName = sourceAsm.GetName();

                var sourceAsmDefinition = AssemblyCache.GetOrAdd(sourceAsmName, _ => new Lazy <AssemblyDefinition>(() => AssemblyDefinition.ReadAssembly(sourceAsm.Location))).Value;

                // Mono.Cecil uses '/' to declare nested type names instead of '+'
                var sourceSearchTypeName = sourceType.FullName.Replace('+', '/');
                var sourceTypeDefinition = sourceAsmDefinition.MainModule.GetType(sourceSearchTypeName);
                var sourceProperty       = sourceTypeDefinition.Properties.SingleOrDefault(p => p.Name == Property.Name && !p.HasParameters);

                if (sourceProperty == null)
                {
                    throw new ArgumentException(
                              "Could not find the source property "
                              + Property.ReflectedType.FullName + "." + Property.Name
                              + ". Check that assemblies are up to date.",
                              Property.ReflectedType.FullName + "." + Property.Name
                              );
                }

                var sourcePropInstructions = sourceProperty.GetMethod.Body.Instructions;
                var fnInstruction          = sourcePropInstructions.FirstOrDefault(i => i.OpCode.Code == Code.Ldftn);

                if (fnInstruction == null)
                {
                    throw new ArgumentException(
                              "Could not find function pointer instruction in the get method of the source property "
                              + Property.ReflectedType.FullName + "." + Property.Name
                              + ". Is the key selector method a simple lambda expression?",
                              Property.ReflectedType.FullName + "." + Property.Name
                              );
                }

                if (!(fnInstruction.Operand is MethodDefinition fnOperand))
                {
                    throw new ArgumentException(
                              "Expected to find a method definition associated with a function pointer instruction but could not find one for "
                              + Property.ReflectedType.FullName + "." + Property.Name + ".",
                              Property.ReflectedType.FullName + "." + Property.Name
                              );
                }

                var operandInstructions = fnOperand.Body.Instructions;
                var bodyCallInstr       = operandInstructions.FirstOrDefault(i => i.OpCode.Code == Code.Callvirt || i.OpCode.Code == Code.Call);

                if (bodyCallInstr == null)
                {
                    throw new ArgumentException(
                              "Could not find call or virtual call instruction in the key selector function that was provided to "
                              + Property.ReflectedType.FullName + "." + Property.Name
                              + ". Is the key selector method a simple lambda expression?",
                              Property.ReflectedType.FullName + "." + Property.Name
                              );
                }

                if (!(bodyCallInstr.Operand is MethodDefinition bodyMethodDef))
                {
                    throw new ArgumentException("Expected to find a method definition associated with the call or virtual call instruction but could not find one in the key selector.");
                }

                var targetPropertyName = bodyMethodDef.Name;
                var targetProp         = TargetType.GetProperties().SingleOrDefault(p => p.GetGetMethod().Name == targetPropertyName && p.GetIndexParameters().Length == 0);

                if (targetProp == null)
                {
                    throw new ArgumentException(
                              $"Expected to find a property named { targetPropertyName } in { TargetType.FullName } but could not find one.",
                              Property.ReflectedType.FullName + "." + Property.Name
                              );
                }

                return(targetProp);
            }
예제 #20
0
        /// <summary>Sets all attribute-tagged fields and properties in the given object from the config values provided.</summary>
        /// <remarks>If a value is not set in the config file, or is set to an invalid value, or is set out of range (where applicable), the default value specified in the attribute is used instead. All attribute-tagged fields and properties are therefore set to reasonable values after this method returns true.</remarks>
        /// <param name="targetObj">The object to configure. Must implement <see cref="IConfigurableAttr"/>.</param>
        /// <param name="config">The set of config values to apply.</param>
        /// <returns>Whether applying the configuration values succeeded.</returns>
        /// <exception cref="InvalidOperationException">If the field or property type is not compatible with the attribute used.</exception>
        /// <exception cref="NotImplementedException">If the attribute is one that is not yet supported.</exception>
        public static bool Configure(object targetObj, Dictionary <string, object> config)
        {
            Type?TargetType;
            IConfigurableAttr?TargetInst = null;  // Only valid for instances (non-static classes)

            if (targetObj is Type)
            {
                TargetType = (Type?)targetObj;
            }                                                         // For configuring static classes
            else
            {
                TargetType = targetObj?.GetType();
                if (targetObj is not IConfigurableAttr Target)
                {
                    Log.Warn("Tried to configure non-configurable object " + targetObj);
                    return(false);
                }
                TargetInst = Target;
            }
            if (TargetType == null)
            {
                Log.Error("Tried to configure object whose type cannot be determined."); return(false);
            }
            Log.Info("Reading config for " + TargetType.Name + '.');

            FieldInfo[]    Fields     = TargetType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
            PropertyInfo[] Properties = TargetType.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);

            foreach (FieldInfo Field in Fields)
            {
                Attribute?Attr = Attribute.GetCustomAttribute(Field, typeof(ConfigAttribute));
                if (Attr is null)
                {
                    continue;
                }                              // Field without attribute, ignore
                if (Attr is ConfigIntAttribute IntAttr)
                {
                    long Value = CheckInt(config, IntAttr);

                    if (Field.FieldType == typeof(int))
                    {
                        Field.SetValue(targetObj, (int)Value);
                    }
                    else if (Field.FieldType == typeof(uint))
                    {
                        Field.SetValue(targetObj, (uint)Value);
                    }
                    else if (Field.FieldType == typeof(short))
                    {
                        Field.SetValue(targetObj, (short)Value);
                    }
                    else if (Field.FieldType == typeof(ushort))
                    {
                        Field.SetValue(targetObj, (ushort)Value);
                    }
                    else if (Field.FieldType == typeof(byte))
                    {
                        Field.SetValue(targetObj, (byte)Value);
                    }
                    else if (Field.FieldType == typeof(sbyte))
                    {
                        Field.SetValue(targetObj, (sbyte)Value);
                    }
                    else if (Field.FieldType == typeof(long))
                    {
                        Field.SetValue(targetObj, (long)Value);
                    }
                    else if (Field.FieldType == typeof(ulong))
                    {
                        Field.SetValue(targetObj, (ulong)Value);
                    }
                    else
                    {
                        throw new InvalidOperationException($"Field {IntAttr.Name} in {TargetType.FullName} used ConfigInt but is not a numeric type.");
                    }

                    config.Remove(IntAttr.Name);
                }
                else if (Attr is ConfigStringAttribute StrAttr)
                {
                    string Value = CheckString(config, StrAttr);

                    if (Field.FieldType == typeof(string))
                    {
                        Field.SetValue(targetObj, Value);
                    }
                    else
                    {
                        throw new InvalidOperationException($"Field {StrAttr.Name} in {TargetType.FullName} used ConfigString but is not a string type.");
                    }

                    config.Remove(StrAttr.Name);
                }
                else if (Attr is ConfigBoolAttribute BoolAttr)
                {
                    bool Value = CheckBool(config, BoolAttr);

                    if (Field.FieldType == typeof(bool))
                    {
                        Field.SetValue(targetObj, Value);
                    }
                    else
                    {
                        throw new InvalidOperationException($"Field {BoolAttr.Name} in {TargetType.FullName} used ConfigBool but is not a bool type.");
                    }

                    config.Remove(BoolAttr.Name);
                }
                else if (Attr is ConfigFloatAttribute FltAttr)
                {
                    float Value = CheckFloat(config, FltAttr);

                    if (Field.FieldType == typeof(float))
                    {
                        Field.SetValue(targetObj, Value);
                    }
                    else if (Field.FieldType == typeof(double))
                    {
                        Field.SetValue(targetObj, (double)Value);
                    }
                    else if (Field.FieldType == typeof(decimal))
                    {
                        Field.SetValue(targetObj, (decimal)Value);
                    }
                    else
                    {
                        throw new InvalidOperationException($"Field {FltAttr.Name} in {TargetType.FullName} used ConfigFloat but is not a float type.");
                    }

                    config.Remove(FltAttr.Name);
                }
                else
                {
                    throw new NotImplementedException("Unsupported config type encountered: " + Attr?.GetType()?.FullName);
                }
            }

            foreach (PropertyInfo Prop in Properties)
            {
                Attribute?Attr = Attribute.GetCustomAttribute(Prop, typeof(ConfigAttribute));
                if (Attr is null)
                {
                    continue;
                }                               // Property without attribute, ignore
                if (Attr is ConfigIntAttribute IntAttr)
                {
                    long Value = CheckInt(config, IntAttr);

                    if (Prop.PropertyType == typeof(int))
                    {
                        Prop.SetValue(targetObj, (int)Value);
                    }
                    else if (Prop.PropertyType == typeof(uint))
                    {
                        Prop.SetValue(targetObj, (uint)Value);
                    }
                    else if (Prop.PropertyType == typeof(short))
                    {
                        Prop.SetValue(targetObj, (short)Value);
                    }
                    else if (Prop.PropertyType == typeof(ushort))
                    {
                        Prop.SetValue(targetObj, (ushort)Value);
                    }
                    else if (Prop.PropertyType == typeof(byte))
                    {
                        Prop.SetValue(targetObj, (byte)Value);
                    }
                    else if (Prop.PropertyType == typeof(sbyte))
                    {
                        Prop.SetValue(targetObj, (sbyte)Value);
                    }
                    else if (Prop.PropertyType == typeof(long))
                    {
                        Prop.SetValue(targetObj, (long)Value);
                    }
                    else if (Prop.PropertyType == typeof(ulong))
                    {
                        Prop.SetValue(targetObj, (ulong)Value);
                    }
                    else
                    {
                        throw new InvalidOperationException($"Property {IntAttr.Name} in {TargetType.FullName} used ConfigInt but is not a numeric type.");
                    }

                    config.Remove(IntAttr.Name);
                }
                else if (Attr is ConfigStringAttribute StrAttr)
                {
                    string Value = CheckString(config, StrAttr);

                    if (Prop.PropertyType == typeof(string))
                    {
                        Prop.SetValue(targetObj, Value);
                    }
                    else
                    {
                        throw new InvalidOperationException($"Property {StrAttr.Name} in {TargetType.FullName} used ConfigString but is not a string type.");
                    }

                    config.Remove(StrAttr.Name);
                }
                else if (Attr is ConfigBoolAttribute BoolAttr)
                {
                    bool Value = CheckBool(config, BoolAttr);

                    if (Prop.PropertyType == typeof(bool))
                    {
                        Prop.SetValue(targetObj, Value);
                    }
                    else
                    {
                        throw new InvalidOperationException($"Field {BoolAttr.Name} in {TargetType.FullName} used ConfigBool but is not a bool type.");
                    }

                    config.Remove(BoolAttr.Name);
                }
                else if (Attr is ConfigFloatAttribute FltAttr)
                {
                    float Value = CheckFloat(config, FltAttr);

                    if (Prop.PropertyType == typeof(float))
                    {
                        Prop.SetValue(targetObj, Value);
                    }
                    else if (Prop.PropertyType == typeof(double))
                    {
                        Prop.SetValue(targetObj, (double)Value);
                    }
                    else if (Prop.PropertyType == typeof(decimal))
                    {
                        Prop.SetValue(targetObj, (decimal)Value);
                    }
                    else
                    {
                        throw new InvalidOperationException($"Field {FltAttr.Name} in {TargetType.FullName} used ConfigFloat but is not a float type.");
                    }

                    config.Remove(FltAttr.Name);
                }
                else
                {
                    throw new NotImplementedException("Unsupported config type encountered: " + Attr.GetType().FullName);
                }
            }

            // Warn about any remaining items
            foreach (string Item in config.Keys)
            {
                if (Item == "Type" || Item == "Name")
                {
                    continue;
                }
                if (TargetInst is IOutput && (Item == "VisualizerName" || Item == "Modes"))
                {
                    continue;
                }
                Log.Warn($"Unknown config entry \"{Item}\" found while configuring {TargetType.FullName}.");
            }

            return(true);
        }
예제 #21
0
        public void Init()
        {
            ViewPortDescriptors = new Dictionary <string, BaseDescriptor>();
            PropertyDataConfig  = new Dictionary <string, PropertyDataInfo>();
            DataRelations       = new List <Relation>();
            Alias      = "T0";
            TargetType = typeof(T);
            foreach (var item in TargetType.GetProperties())
            {
                TypeCode code = Type.GetTypeCode(item.PropertyType.IsGenericType ? item.PropertyType.GetGenericArguments()[0] : item.PropertyType);
                switch (code)
                {
                case TypeCode.Boolean:
                    ViewConfig(item.Name).AsCheckBox().SetColumnWidth(75);
                    break;

                case TypeCode.Char:
                    ViewConfig(item.Name).AsTextBox().MaxLength(1).RegularExpression(RegularExpression.Letters);
                    break;

                case TypeCode.DateTime:
                    ViewConfig(item.Name).AsTextBox().FormatAsDate().SetColumnWidth(140);
                    break;

                case TypeCode.UInt16:
                case TypeCode.UInt32:
                case TypeCode.UInt64:
                    ViewConfig(item.Name).AsTextBox().RegularExpression(RegularExpression.PositiveIntegersAndZero).SetColumnWidth(75);
                    break;

                case TypeCode.SByte:
                case TypeCode.Int16:
                case TypeCode.Int32:
                case TypeCode.Int64:
                    ViewConfig(item.Name).AsTextBox().RegularExpression(RegularExpression.Integer).SetColumnWidth(75);
                    break;

                case TypeCode.Object:
                    ViewConfig(item.Name).AsHidden().Ignore();
                    break;

                case TypeCode.Single:
                case TypeCode.Double:
                case TypeCode.Decimal:
                    ViewConfig(item.Name).AsTextBox().RegularExpression(RegularExpression.Float).SetColumnWidth(75);
                    break;

                case TypeCode.String:
                    ViewConfig(item.Name).AsTextBox().MaxLength(200).SetColumnWidth(200);
                    break;

                case TypeCode.DBNull:
                case TypeCode.Byte:
                case TypeCode.Empty:
                default: ViewConfig(item.Name).AsTextBox();
                    break;
                }
                if (code == TypeCode.Object)
                {
                    DataConfig(item.Name).Ignore();
                }
                else
                {
                    DataConfig(item.Name);
                }
            }
            if (typeof(EditorEntity).IsAssignableFrom(TargetType))
            {
                ViewConfig("CreateBy").AsHidden();
                ViewConfig("CreatebyName").AsTextBox().Hide().SetColumnWidth(80);
                ViewConfig("CreateDate").AsTextBox().Hide().FormatAsDateTime().SetColumnWidth(140);

                ViewConfig("LastUpdateBy").AsHidden();
                ViewConfig("LastUpdateByName").AsTextBox().Hide().SetColumnWidth(80);
                ViewConfig("LastUpdateDate").AsTextBox().Hide().FormatAsDateTime().SetColumnWidth(140);
                ViewConfig("ActionType").AsHidden().AddClass("ActionType");
                ViewConfig("Title").AsTextBox().Order(1).SetColumnWidth(200);
                ViewConfig("Description").AsTextArea().SetColumnWidth(250).Order(101);
                ViewConfig("Status").AsDropDownList().DataSource(DicKeys.RecordStatus, SourceType.Dictionary).SetColumnWidth(70);

                DataConfig("CreateBy").Update(false);
                DataConfig("CreatebyName").Update(false);
                DataConfig("CreateDate").Update(false);
                DataConfig("ActionType").Ignore();
            }
            if (typeof(IImage).IsAssignableFrom(TargetType))
            {
                ViewConfig("ImageUrl").AsTextBox().HideInGrid();
                ViewConfig("ImageThumbUrl").AsTextBox().HideInGrid();
            }
            if (IsIgnoreBase())
            {
                IgnoreBase();
            }
            DataConfigure();
            ViewConfigure();
        }