Beispiel #1
0
		public RecordMap(Type type, RecordAttribute recordAttribute, RecordTypeAttribute recordTypeAttribute, IDictionary<int, FieldMap> basicFieldMaps, IList<FieldMap> advancedFieldMaps, IList<IndexMap> indexMaps, IList<LinkRecord> linkRecords)
		{
			this.type = type;
			this.recordAttribute = recordAttribute;
			this.recordTypeAttribute = recordTypeAttribute;
			this.basicFieldMaps = basicFieldMaps;
			this.advancedFieldMaps = advancedFieldMaps;
			this.indexMaps = indexMaps;
			this.linkRecords = linkRecords;
		}
Beispiel #2
0
        public JsonContainer(object obj)
        {
            if (obj == null)
            {
                throw new ArgumentNullException();
            }

            Type type = obj.GetType();

            if (obj is IList)
            {
                ContainerType = ContainType.Array;
                foreach (object i in obj as IList)
                {
                    Serialize_AddData(i, null);
                }
            }
            else
            {
                ContainerType = ContainType.Object;
                if (obj is IDictionary)
                {
                    foreach (DictionaryEntry i in obj as IDictionary)
                    {
                        Serialize_AddData(i.Value, i.Key.ToString());
                    }
                }
                else
                {
                    foreach (FieldInfo field in type.GetFields())
                    {
                        object [] attrs = field.GetCustomAttributes(typeof(RecordAttribute), false);
                        if (attrs.Length == 0)
                        {
                            continue;
                        }
                        RecordAttribute attr = attrs.GetValue(0) as RecordAttribute;
                        Serialize_AddData(field.GetValue(obj), attr.Name ?? field.Name);
                    }
                    foreach (PropertyInfo prop in type.GetProperties())
                    {
                        object [] attrs = prop.GetCustomAttributes(typeof(RecordAttribute), false);
                        if (attrs.Length == 0)
                        {
                            continue;
                        }
                        RecordAttribute attr = attrs.GetValue(0) as RecordAttribute;
                        Serialize_AddData(prop.GetValue(obj, null), attr.Name ?? prop.Name);
                    }
                }
            }
        }
        static CaseClass GenerateCaseClass(
            RecordAttribute attr, SemanticModel model, TypeDeclarationSyntax cds, INamedTypeSymbol symbolInfo
            )
        {
            var members = symbolInfo.GetMembers();

            var fieldsAndProps = members.SelectMany(member => {
                switch (member)
                {
                case IFieldSymbol fieldSymbol: {
                    if (fieldSymbol.IsConst || fieldSymbol.IsStatic)
                    {
                        break;
                    }
                    // backing fields of properties
                    if (fieldSymbol.DeclaringSyntaxReferences.Length == 0)
                    {
                        break;
                    }
                    var untypedSyntax = fieldSymbol.DeclaringSyntaxReferences.Single().GetSyntax();
                    var syntax        = (VariableDeclaratorSyntax)untypedSyntax;
                    return(new[] {
                            new FieldOrProp(
                                fieldSymbol.Type, fieldSymbol.Name, syntax.Initializer != null, model
                                )
                        });
                }

                case IPropertySymbol propertySymbol: {
                    if (propertySymbol.IsStatic)
                    {
                        break;
                    }
                    if (propertySymbol.IsIndexer)
                    {
                        break;
                    }
                    var syntax = (PropertyDeclarationSyntax)
                                 propertySymbol.DeclaringSyntaxReferences.Single().GetSyntax();
                    var hasGetterOrSetter = syntax.AccessorList?.Accessors.Any(ads =>
                                                                               ads.Body != null || ads.ExpressionBody != null
                                                                               ) ?? false;
                    if (hasGetterOrSetter)
                    {
                        break;
                    }
                    if (syntax.ExpressionBody != null)
                    {
                        break;
                    }
                    return(new[] {
                            new FieldOrProp(
                                propertySymbol.Type, propertySymbol.Name, syntax.Initializer != null, model
                                )
                        });
                }
                }

                return(Enumerable.Empty <FieldOrProp>());
            }).ToArray();

            var hasAnyFields = fieldsAndProps.Any();

            var initializedFieldsAndProps = fieldsAndProps.Where(_ => !_.initialized).ToImmutableArray();

            var constructor = createIf(
                attr.GenerateConstructor.HasFlag(ConstructorFlags.Constructor) && hasAnyFields,
                () => {
                var parameters = initializedFieldsAndProps.JoinCommaSeparated(f => f.type + " " + f.identifier);
                var body       = initializedFieldsAndProps.Any()
            ? initializedFieldsAndProps
                                 .Select(f => $"this.{f.identifier} = {f.identifier};")
                                 .Tap(s => Join("\n", s) + "\n")
            : "";

                return(ParseClassMembers($"public {cds.Identifier}({parameters}){{{body}}}"));
            }
                );

            IReadOnlyList <MemberDeclarationSyntax> createIf(bool condition, Func <SyntaxList <MemberDeclarationSyntax> > a)
            {
                return(condition ? (IReadOnlyList <MemberDeclarationSyntax>)a() : Array.Empty <MemberDeclarationSyntax>());
            }

            var toString = createIf(
                attr.GenerateToString,
                () => {
                var returnString = fieldsAndProps
                                   .JoinCommaSeparated(f => f.traversable
              ? f.identifier +
                                                       ": [\" + Helpers.enumerableToString(" + f.identifier + ") + \"]"
              : f.identifier +
                                                       ": \" + " + f.identifier + " + \""
                                                       );

                return(ParseClassMembers(
                           $"public override string ToString() => \"{cds.Identifier.ValueText}({returnString})\";"
                           ));
            });

            var getHashCode = createIf(attr.GenerateGetHashCode, () => {
                if (hasAnyFields)
                {
                    var hashLines = Join("\n", fieldsAndProps.Select(f => {
                        var type        = f.typeInfo;
                        var isValueType = type.IsValueType;
                        var name        = f.identifier;


                        string ValueTypeHash(ITypeSymbol t)
                        {
                            if (t.IsEnum(out var underlyingType))
                            {
                                switch (underlyingType)
                                {
                                case SpecialType.System_Int64:
                                case SpecialType.System_UInt64:
                                    return($"{name}.GetHashCode()");

                                default:
                                    return($"(int) {name}");
                                }
                            }

                            var sType = t.SpecialType;
                            switch (sType)
                            {
                            case SpecialType.System_Byte:
                            case SpecialType.System_SByte:
                            case SpecialType.System_Int16:
                            case SpecialType.System_Int32: return(name);

                            case SpecialType.System_UInt32: return("(int) " + name);

                            default: return(name + ".GetHashCode()");
                            }
                        }

                        var fieldHashCode = isValueType
              ? ValueTypeHash(type)
              : $"({name} == null ? 0 : {name}.GetHashCode())";
                        return($"hashCode = (hashCode * 397) ^ {fieldHashCode}; // {type.SpecialType}");
                    }));
                    return(ParseClassMembers(
                               $@"public override int GetHashCode() {{
                            unchecked {{
                                var hashCode = 0;
                                {hashLines}
                                return hashCode;
                            }}
                        }}"));
                }
        private void AddColumn(FieldInfo fieldInfo, RecordAttribute recordAttribute)
        {
            // not sure whether it is more convenient for the user to inherit or not
            var atts = fieldInfo.GetCustomAttributes(typeof(ColumnAttribute), true);

            ColumnAttribute column = null;

            if (atts.Length == 0)
            {
                var fm = recordAttribute.FieldMapping;
                if (fieldInfo.IsPublic)
                {
                    if ((fm & FieldMapping.PublicFields) == 0) return;
                }
                else
                {
                    if ((fm & FieldMapping.PrivateFields) == 0) return;
                }
            }
            else column = (ColumnAttribute)atts[0];
            ColumnDefinition cd = null;
            if (mCreateColumns)
            {
                cd = new ColumnDefinition();
                cd.Initialize(mVersion, fieldInfo, column);
                mColumns.Add(cd);
            }
            else if (column != null && column.Type == ColumnType.DELETED_FLAG)
            {
                cd = new ColumnDefinition();
                cd.Initialize(mVersion, fieldInfo, column);
                mColumns.Insert(0, cd);
            }
            else
            {
                bool found = false;
                for (int i = 0; i < mColumns.Count; i++)
                {
                    cd = mColumns[i];
                    if (fieldInfo.Name == cd.mColumnName)
                    {
                        cd.mFieldInfo = fieldInfo;
                        found = true;
                        break;
                    }
                }
                if (found == false && mIgnoreMissingFields == false)
                {
                    throw new Exception(string.Format("Column {0} was not found in existing DBF file", fieldInfo.Name));
                }
            }

            if (cd.mWidth == 0) mIsFixedRecordWidth = false;
        }
Beispiel #5
0
 public object ToObject(Type type)
 {
     if (ContainerType == ContainType.Object)
     {
         object obj = Activator.CreateInstance(type);
         if (obj is IDictionary)
         {
             foreach (KeyValuePair <object, object> i in container)
             {
                 (obj as IDictionary).Add(i.Key, null);
                 PropertyInfo prop = type.GetProperty("Item");
                 prop.SetValue(obj, Deserialize_GetData(prop.PropertyType, i.Value), new object [] { i.Key });
             }
             return(obj);
         }
         else
         {
             foreach (KeyValuePair <object, object> i in GetDictionaryEnumerable())
             {
                 foreach (FieldInfo field in type.GetFields())
                 {
                     object [] attrs = field.GetCustomAttributes(typeof(RecordAttribute), false);
                     if (attrs.Length == 0)
                     {
                         continue;
                     }
                     RecordAttribute attr = attrs.GetValue(0) as RecordAttribute;
                     if ((attr.Name ?? field.Name) == i.Key as string)
                     {
                         field.SetValue(obj, Deserialize_GetData(field.FieldType, i.Value));
                     }
                 }
                 foreach (PropertyInfo prop in type.GetProperties())
                 {
                     object [] attrs = prop.GetCustomAttributes(typeof(RecordAttribute), false);
                     if (attrs.Length == 0)
                     {
                         continue;
                     }
                     RecordAttribute attr = attrs.GetValue(0) as RecordAttribute;
                     if ((attr.Name ?? prop.Name) == i.Key as string)
                     {
                         prop.SetValue(obj, Deserialize_GetData(prop.PropertyType, i.Value), null);
                     }
                 }
             }
         }
         return(obj);
     }
     else if (ContainerType == ContainType.Array)
     {
         if (IsSubtypeOf(type, typeof(Array)))
         {
             object     obj    = Activator.CreateInstance(type, container.Count);
             MethodInfo method = type.GetMethod("Set");
             foreach (KeyValuePair <object, object> i in container)
             {
                 object temp = i.Value;
                 if (temp is JsonContainer)
                 {
                     temp = (temp as JsonContainer).ToObject(method.GetParameters() [1].ParameterType);
                 }
                 method.Invoke(obj, new object [] { i.Key, temp });
             }
             return(obj);
         }
         else if (IsSubtypeOf(type, typeof(IList)))
         {
             object obj = Activator.CreateInstance(type);
             for (int i = 0; i < container.Count; ++i)
             {
                 (obj as IList).Add(null);
             }
             PropertyInfo prop = type.GetProperty("Item");
             foreach (KeyValuePair <object, object> i in container)
             {
                 prop.SetValue(obj, Deserialize_GetData(prop.PropertyType, i.Value), new object [] { i.Key });
             }
             return(obj);
         }
     }
     return(null);
 }
        private void AddColumn(FieldInfo fieldInfo, RecordAttribute recordAttribute)
        {
            // not sure whether it is more convenient for the user to inherit or not
            var atts = fieldInfo.GetCustomAttributes(typeof(ColumnAttribute), true);

            ColumnAttribute column = null;

            if (atts.Length == 0)
            {
                var fm = recordAttribute.FieldMapping;
                if (fieldInfo.IsPublic)
                {
                    if ((fm & FieldMapping.PublicFields) == 0)
                    {
                        return;
                    }
                }
                else
                {
                    if ((fm & FieldMapping.PrivateFields) == 0)
                    {
                        return;
                    }
                }
            }
            else
            {
                column = (ColumnAttribute)atts[0];
            }
            ColumnDefinition cd = null;

            if (mCreateColumns)
            {
                cd = new ColumnDefinition();
                cd.Initialize(mVersion, fieldInfo, column);
                mColumns.Add(cd);
            }
            else if (column != null && column.Type == ColumnType.DELETED_FLAG)
            {
                cd = new ColumnDefinition();
                cd.Initialize(mVersion, fieldInfo, column);
                mColumns.Insert(0, cd);
            }
            else
            {
                bool found = false;
                for (int i = 0; i < mColumns.Count; i++)
                {
                    cd = mColumns[i];
                    if (fieldInfo.Name == cd.mColumnName)
                    {
                        cd.mFieldInfo = fieldInfo;
                        found         = true;
                        break;
                    }
                }
                if (found == false && mIgnoreMissingFields == false)
                {
                    throw new Exception(string.Format("Column {0} was not found in existing DBF file", fieldInfo.Name));
                }
            }

            if (cd.mWidth == 0)
            {
                mIsFixedRecordWidth = false;
            }
        }