Beispiel #1
0
        private void ReadClass(Type type, ModelTransferObject model, IOptions caller)
        {
            // Logger.Trace($"Reflection read type {type.Name} ({type.Namespace})");
            if (type.BaseType != typeof(object) && type.BaseType != typeof(ValueType) && type.BaseType != null)
            {
                IOptions baseOptions = this.options.Get(type.BaseType);
                if (!baseOptions.Ignore)
                {
                    model.BasedOn = this.Read(type.BaseType, caller);
                }
            }
            if (model.IsGeneric)
            {
                this.ReadGenericArguments(type, model);
            }

            model.IsInterface = type.IsInterface;
            model.IsAbstract  = type.IsAbstract;
            foreach (Type interFace in type.GetInterfaces(false))
            {
                IOptions interfaceOptions = this.options.Get(interFace);
                if (interfaceOptions.Ignore)
                {
                    continue;
                }
                ModelTransferObject interfaceTransferObject = this.Read(interFace, caller);
                if (this.transferObjects.Contains(interfaceTransferObject))
                {
                    model.Interfaces.Add(interfaceTransferObject);
                }
            }
            if (model is GenericModelTransferObject genericModel)
            {
                Type genericType = type.GetGenericTypeDefinition();
                this.ReadConstants(genericType, genericModel.Template);
                this.ReadFields(genericType, genericModel.Template);
                this.ReadProperties(genericType, genericModel.Template);
                this.ApplyGenericTemplate(type, genericModel);
            }
            else
            {
                this.ReadConstants(type, model);
                this.ReadFields(type, model);
                this.ReadProperties(type, model);
            }
        }
Beispiel #2
0
        protected virtual EnumTemplate WriteEnum(IModelConfiguration configuration, ModelTransferObject model, string nameSpace, List <FileTemplate> files)
        {
            if (model.EnumValues == null)
            {
                throw new InvalidOperationException("Can not write enum without values");
            }

            EnumTemplate enumTemplate = files.AddFile(configuration.RelativePath, configuration.AddHeader)
                                        .AddNamespace(nameSpace)
                                        .AddEnum(model.Name);

            foreach (KeyValuePair <string, int> pair in model.EnumValues)
            {
                string formattedName = Formatter.FormatProperty(pair.Key, configuration);
                enumTemplate.Values.Add(new EnumValueTemplate(pair.Key, Code.Number(pair.Value), formattedName));
            }
            return(enumTemplate);
        }
Beispiel #3
0
        protected virtual FieldTemplate AddField(ModelTransferObject model, MemberTransferObject member, ClassTemplate classTemplate)
        {
            IOptions fieldOptions = this.Options.Get(member);

            if (model.Language != null && fieldOptions.Language != null)
            {
                this.MapType(model.Language, fieldOptions.Language, member.Type);
            }
            this.AddUsing(member.Type, classTemplate, fieldOptions);
            FieldTemplate fieldTemplate = classTemplate.AddField(member.Name, member.Type.ToTemplate()).Public().FormatName(fieldOptions)
                                          .WithComment(member.Comment);

            if (fieldOptions.WithOptionalProperties)
            {
                fieldTemplate.Optional();
            }
            return(fieldTemplate);
        }
Beispiel #4
0
        protected override ClassTemplate WriteClass(ModelTransferObject model, string relativePath)
        {
            IOptions      modelOptions  = this.Options.Get(model);
            ClassTemplate classTemplate = base.WriteClass(model, relativePath);

            if (!model.IsAbstract && !classTemplate.IsInterface && modelOptions.Language.IsTypeScript())
            {
                ConstructorTemplate constructor = classTemplate.AddConstructor();
                constructor.AddParameter(Code.Generic("Partial", classTemplate.ToType()), "init").Optional();
                constructor.WithCode(Code.Static(Code.Type("Object")).Method("assign", Code.This(), Code.Local("init")).Close());
                if (classTemplate.BasedOn.Any(x => !x.ToType().IsInterface))
                {
                    // TODO: Add super parameters
                    constructor.WithSuper();
                }
            }
            return(classTemplate);
        }
Beispiel #5
0
        public void Read(DemoReadConfiguration configuration, List <ITransferObject> transferObjects)
        {
            Logger.Trace($"Read {configuration.HelloWorld.Name}...");
            // Read something here and create your transfer objects
            ModelTransferObject model = new ModelTransferObject {
                Name = configuration.HelloWorld.Name, Namespace = "Test"
            };

            if (configuration.HelloWorld.Test1)
            {
                model.Properties.Add(new PropertyTransferObject {
                    Name = "Test1", Type = new TypeTransferObject {
                        Name = "string"
                    }
                });
            }
            transferObjects.Add(model);
        }
Beispiel #6
0
 private void ReadFields(Type type, ModelTransferObject model)
 {
     FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
     foreach (FieldInfo field in fields)
     {
         IOptions fieldOptions = this.options.Get(field);
         if (fieldOptions.Ignore)
         {
             continue;
         }
         FieldTransferObject fieldTransferObject = new()
         {
             Name = field.Name,
             Type = this.Read(field.FieldType, fieldOptions)
         };
         model.Fields.Add(fieldTransferObject);
         this.options.Set(fieldTransferObject, fieldOptions);
     }
 }
        protected virtual EnumTemplate WriteEnum(ModelTransferObject model, string relativePath)
        {
            if (model.EnumValues == null)
            {
                throw new InvalidOperationException("Can not write enum without values");
            }
            IOptions     modelOptions = this.Options.Get(model);
            EnumTemplate enumTemplate = this.files.AddFile(relativePath, modelOptions)
                                        .WithName(model.FileName)
                                        .AddNamespace(modelOptions.SkipNamespace ? string.Empty : model.Namespace)
                                        .AddEnum(model.Name);

            foreach (KeyValuePair <string, int> pair in model.EnumValues)
            {
                string formattedName = Formatter.FormatProperty(pair.Key, modelOptions);
                enumTemplate.Values.Add(new EnumValueTemplate(pair.Key, Code.Number(pair.Value), formattedName));
            }
            return(enumTemplate);
        }
Beispiel #8
0
 private void ReadProperties(Type type, ModelTransferObject model)
 {
     PropertyInfo[] properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
     foreach (PropertyInfo property in properties)
     {
         IOptions propertyOptions = this.options.Get(property);
         if (propertyOptions.Ignore)
         {
             continue;
         }
         PropertyTransferObject propertyTransferObject = new()
         {
             Name       = property.Name,
             Type       = this.Read(property.PropertyType, propertyOptions),
             Attributes = property.GetCustomAttributes().ToTransferObjects().ToList()
         };
         model.Properties.Add(propertyTransferObject);
         this.options.Set(propertyTransferObject, propertyOptions);
     }
 }
Beispiel #9
0
 private void ReadConstants(Type type, ModelTransferObject model)
 {
     FieldInfo[] constants = type.GetFields(BindingFlags.Public | BindingFlags.Static);
     foreach (FieldInfo field in constants)
     {
         IOptions fieldOptions = this.options.Get(field);
         if (fieldOptions.Ignore)
         {
             continue;
         }
         FieldTransferObject fieldTransferObject = new()
         {
             Name    = field.Name,
             Type    = this.Read(field.FieldType, fieldOptions),
             Default = field.GetValue(null)
         };
         model.Constants.Add(fieldTransferObject);
         this.options.Set(fieldTransferObject, fieldOptions);
     }
 }
Beispiel #10
0
 protected virtual void WriteModel(IModelConfiguration configuration, ModelTransferObject model, string nameSpace, List <FileTemplate> files)
 {
     if (model == null)
     {
         return;
     }
     this.MapType(model.Language, configuration.Language, model);
     if (model.FromSystem)
     {
         return;
     }
     if (model.IsEnum)
     {
         this.WriteEnum(configuration, model, nameSpace, files);
     }
     else
     {
         this.WriteClass(configuration, model, nameSpace, files);
     }
 }
Beispiel #11
0
        public ModelTransferObject Read(Type type, List <ITransferObject> transferObjects)
        {
            bool isFromSystem         = type.Namespace != null && type.Namespace.StartsWith("System");
            ModelTransferObject model = new ModelTransferObject {
                Language = ReflectionLanguage.Instance
            };

            model.FromType(type);
            ModelTransferObject existingModel = transferObjects.OfType <ModelTransferObject>().FirstOrDefault(entry => entry.Equals(model));

            if (existingModel != null)
            {
                return(existingModel);
            }
            if (type.GetCustomAttributes <GenerateIgnoreAttribute>().Any())
            {
                Logger.Trace($"{type.Name} ({type.Namespace}) ignored (decorated with {nameof(GenerateIgnoreAttribute)})");
                return(model);
            }
            if (type.IsArray)
            {
                this.ReadArray(type, model, transferObjects);
            }
            else if (type.IsGenericType && isFromSystem)
            {
                this.ReadGenericFromSystem(type, model, transferObjects);
            }
            else if (type.IsEnum)
            {
                transferObjects.Add(model);
                this.ReadEnum(type, model);
            }
            else if (!isFromSystem)
            {
                transferObjects.Add(model);
                this.ReadClass(type, model, transferObjects);
            }
            return(model);
        }
Beispiel #12
0
        private void ReadEnum(Type type, ModelTransferObject model)
        {
            // Logger.Trace($"Reflection read enum {type.Name} ({type.Namespace})");
            model.IsEnum     = true;
            model.EnumValues = new Dictionary <string, int>();
            Array values = Enum.GetValues(type);

            foreach (object value in values)
            {
                if (!(value is int))
                {
                    //throw new InvalidOperationException($"Can not convert {value.GetType().Name} enums. Only int enums are currently implemented");
                }
            }
            foreach (int value in values.Cast <int>())
            {
                string name = Enum.GetName(type, value);
                if (name != null)
                {
                    model.EnumValues.Add(name, value);
                }
            }
        }
        public IEnumerable <FileTemplate> Write(JsonWriteConfiguration configuration, List <ITransferObject> transferObjects)
        {
            ModelTransferObject model = transferObjects.OfType <ModelTransferObject>().FirstOrDefault();

            if (model == null)
            {
                throw new InvalidOperationException("Can not create JsonObjectReader without object. Add in settings a read configuration");
            }
            if (!configuration.Language.IsCsharp())
            {
                throw new InvalidOperationException($"Can not generate JsonReader ({configuration.Reader.Name}) for language {configuration.Language}");
            }
            Logger.Trace("Write JsonReader...");
            string        className     = configuration.Reader.Name ?? model.Name + "Reader";
            FileTemplate  fileTemplate  = new FileTemplate(configuration.Reader.RelativePath, configuration.AddHeader);
            ClassTemplate classTemplate = fileTemplate.AddNamespace(configuration.Reader.Namespace ?? model.Namespace ?? configuration.Object.Namespace)
                                          .AddClass(className)
                                          .FormatName(configuration);

            WriteReader(classTemplate, model, configuration.FormatNames);

            yield return(fileTemplate);
        }
        internal static void WriteReader(ClassTemplate classTemplate, ModelTransferObject model, bool formatNames)
        {
            TypeTemplate objectType = Code.Type(model.Name, model.Namespace);

            if (model.Namespace != classTemplate.Namespace.Name && model.Namespace != null)
            {
                classTemplate.AddUsing(model.Namespace);
            }
            classTemplate.WithUsing("Newtonsoft.Json")
            //.WithUsing("Newtonsoft.Json.Linq")
            .WithUsing("System.IO");

            classTemplate.AddMethod("Load", objectType)
            .FormatName(model.Language, formatNames)
            .WithParameter(Code.Type("string"), "fileName")
            .Static()
            .Code.AddLine(Code.Return(Code.Method("Parse", Code.Local("File").Method("ReadAllText", Code.Local("fileName")))));

            classTemplate.AddMethod("Parse", objectType)
            .FormatName(model.Language, formatNames)
            .WithParameter(Code.Type("string"), "json")
            .Static()
            .Code.AddLine(Code.Return(Code.Local("JsonConvert").GenericMethod("DeserializeObject", objectType, Code.Local("json"))));
        }
        protected override ClassTemplate WriteClass(IModelConfiguration configuration, ModelTransferObject model, string nameSpace, List <FileTemplate> files)
        {
            ClassTemplate classTemplate = base.WriteClass(configuration, model, nameSpace, files);

            if (!model.IsAbstract && !model.IsInterface && configuration.Language.IsTypeScript())
            {
                ConstructorTemplate constructor = classTemplate.AddConstructor();
                constructor.WithParameter(Code.Generic("Partial", classTemplate.ToType()), "init", Code.Null())
                .WithCode(Code.Static(Code.Type("Object")).Method("assign", Code.This(), Code.Local("init")).Close());
                if (classTemplate.BasedOn.Any(x => !x.ToType().IsInterface))
                {
                    // TODO: Add super parameters
                    constructor.WithSuper();
                }
            }
            return(classTemplate);
        }
Beispiel #16
0
        public void Read(ConfigurationBase configurationBase, List <ITransferObject> transferObjects)
        {
            TsqlReadConfiguration configuration = (TsqlReadConfiguration)configurationBase;

            this.Validate(configuration);
            TsqlTypeReader typeReader = new TsqlTypeReader(configuration.Connection);

            foreach (TsqlReadEntity readEntity in configuration.Entities)
            {
                ModelTransferObject model;
                if (!string.IsNullOrEmpty(readEntity.Table))
                {
                    List <TsqlColumn> columns = typeReader.GetColumns(readEntity.Schema ?? configuration.Schema, readEntity.Table);
                    model = new ModelTransferObject
                    {
                        Name      = readEntity.Name ?? readEntity.Table,
                        Namespace = readEntity.Namespace ?? configuration.Namespace,
                        Language  = TsqlLanguage.Instance
                    };
                    foreach (TsqlColumn column in columns)
                    {
                        model.Properties.Add(new PropertyTransferObject
                        {
                            Name = column.Name,
                            Type = new TypeTransferObject {
                                Name = column.Type, IsNullable = column.IsNullable
                            }
                        });
                    }
                    transferObjects.Add(model);
                }
                else
                {
                    //TODO: Implement for StoredProcedure
                    model = new ModelTransferObject
                    {
                        Name      = readEntity.Name ?? readEntity.StoredProcedure,
                        Namespace = readEntity.Namespace ?? configuration.Namespace,
                        Language  = TsqlLanguage.Instance
                    };
                }
                EntityTransferObject entity = new EntityTransferObject
                {
                    Name   = model.Name,
                    Model  = model,
                    Table  = readEntity.Table,
                    Schema = readEntity.Schema ?? configuration.Schema
                };
                if (!string.IsNullOrEmpty(readEntity.Table))
                {
                    typeReader.GetPrimaryKeys(readEntity.Schema ?? configuration.Schema, readEntity.Table)
                    .Select(x => new EntityKeyTransferObject {
                        Name = x.Name
                    })
                    .ForEach(entity.Keys.Add);
                    List <TsqlNavigationProperty> navigationProperties = typeReader.GetNavigationProperties(readEntity.Schema ?? configuration.Schema, readEntity.Table);
                }
                foreach (TsqlReadEntityKeyAction action in readEntity.KeyActions)
                {
                    switch (action.Action.ToLowerInvariant())
                    {
                    case "remove":
                    case "delete":
                        if (action.All)
                        {
                            entity.Keys.Clear();
                        }
                        else
                        {
                            entity.Keys.Remove(entity.Keys.FirstOrDefault(x => x.Name.Equals(action.Name, StringComparison.InvariantCultureIgnoreCase)));
                        }
                        break;

                    case "add":
                    case "insert":
                        entity.Keys.Add(new EntityKeyTransferObject {
                            Name = action.Name
                        });
                        break;

                    default:
                        throw new InvalidOperationException($"Unknown entity key action {action.Action} found");
                    }
                }
                foreach (EntityKeyTransferObject key in entity.Keys)
                {
                    key.Property = entity.Model.Properties.FirstOrDefault(x => x.Name == key.Name).AssertIsNotNull(key.Name, $"Key {key.Name} has no matching property");
                    key.Type     = key.Property.Type;
                }
                transferObjects.Add(entity);
            }
            foreach (TsqlReadStoredProcedure readStoredProcedure in configuration.StoredProcedures)
            {
                string schema = readStoredProcedure.Schema ?? configuration.Schema;
                //List<TsqlColumn> columns = typeReader.GetColumnsFromStoredProcedure(schema, readStoredProcedure.Name);
                StoredProcedureTransferObject storedProcedure = new StoredProcedureTransferObject {
                    Schema = schema, Name = readStoredProcedure.Name
                };
                storedProcedure.ReturnType = new TypeTransferObject {
                    Name = "void", FromSystem = true
                };
                transferObjects.Add(storedProcedure);
            }
        }
Beispiel #17
0
        private ModelTransferObject ReadModel(string name, JObject source, List <ITransferObject> list)
        {
            ModelTransferObject model = name == null ? new JsonModelTransferObject {
                Name = "Unknown", Language = JsonLanguage.Instance
            } : new ModelTransferObject {
                Name = name, Language = JsonLanguage.Instance
            };

            list.Add(model);

            foreach (JProperty property in source.Properties())
            {
                if (property.Value.Type == JTokenType.Object)
                {
                    ModelTransferObject propertyModel = this.ReadModel(property.Name, (JObject)property.Value, list);
                    model.Properties.Add(new PropertyTransferObject {
                        Name = propertyModel.Name, Type = propertyModel
                    });
                }
                else if (property.Value.Type == JTokenType.Array)
                {
                    TypeTransferObject listType = new TypeTransferObject {
                        Name = JTokenType.Array.ToString()
                    };
                    model.Properties.Add(new PropertyTransferObject {
                        Name = property.Name, Type = listType
                    });

                    List <JToken> children = property.Value.Children().ToList();
                    if (children.Count == 0 || children.Any(x => x.Type != children.First().Type))
                    {
                        listType.Generics.Add(new GenericAliasTransferObject {
                            Type = new TypeTransferObject {
                                Name = JTokenType.Object.ToString()
                            }
                        });
                    }
                    else if (children.First().Type == JTokenType.Object)
                    {
                        ModelTransferObject entryModel = this.ReadModel(property.Name, (JObject)children.First(), list);
                        listType.Generics.Add(new GenericAliasTransferObject {
                            Type = entryModel
                        });
                    }
                    else
                    {
                        listType.Generics.Add(new GenericAliasTransferObject {
                            Type = new TypeTransferObject {
                                Name = children.First().Type.ToString()
                            }
                        });
                    }
                }
                else
                {
                    model.Properties.Add(new PropertyTransferObject {
                        Name = property.Name, Type = new TypeTransferObject {
                            Name = property.Value.Type.ToString()
                        }
                    });
                }
            }
            return(model);
        }
Beispiel #18
0
        private TypeTransferObject Read(OpenApiReadConfiguration configuration, OpenApiSchema schema)
        {
            if (schema.Reference == null)
            {
                return(new TypeTransferObject
                {
                    Name = schema.Type
                });
            }

            ModelTransferObject model = transferObjects.OfType <ModelTransferObject>().FirstOrDefault(x => x.Name == schema.Reference.Id);

            if (model != null)
            {
                return(model);
            }

            if (schema.Type == "array")
            {
                return(new TypeTransferObject
                {
                    Name = schema.Type,
                    Generics =
                    {
                        new GenericAliasTransferObject {
                            Type = this.Read(configuration, schema.Items)
                        }
                    }
                });
            }
            if (schema.Type == "object")
            {
                model = new ModelTransferObject
                {
                    Name      = schema.Reference.Id,
                    Namespace = configuration.Namespace,
                    Language  = OpenApiLanguage.Instance
                };
                foreach (KeyValuePair <string, OpenApiSchema> propertyPair in schema.Properties)
                {
                    PropertyTransferObject property = new PropertyTransferObject
                    {
                        Name = propertyPair.Key,
                        Type = this.Read(configuration, propertyPair.Value)
                    };

                    if (configuration.DataAnnotations && propertyPair.Value.MaxLength.HasValue)
                    {
                        property.Attributes.Add(new AttributeTransferObject
                        {
                            Name      = "MaxLength",
                            Namespace = "System.ComponentModel.DataAnnotations",
                            Value     = propertyPair.Value.MaxLength.Value
                        });
                    }
                    model.Properties.Add(property);
                }

                transferObjects.Add(model);
                return(model);
            }
            throw new InvalidOperationException($"Unknown schema type {schema.Type}");
        }
Beispiel #19
0
        protected override ClassTemplate WriteClass(IModelConfiguration configuration, ModelTransferObject model, string nameSpace, List <FileTemplate> files)
        {
            ClassTemplate classTemplate = base.WriteClass(configuration, model, nameSpace, files);

            if (model is JsonModelTransferObject && this.jsonConfiguration.Object.WithReader)
            {
                ObjectReaderWriter.WriteReader(classTemplate, model, configuration.FormatNames);
            }
            return(classTemplate);
        }
Beispiel #20
0
 private void ReadGenericFromSystem(Type type, ModelTransferObject model)
 {
     // Logger.Trace($"Reflection read generic system type {type.Name}<{string.Join(",", type.GetGenericArguments().Select(x => x.Name))}> ({type.Namespace})");
     this.ReadGenericArguments(type, model);
     this.ApplyGenericTemplate(type, (GenericModelTransferObject)model);
 }
 protected virtual FieldTemplate AddField(ModelTransferObject model, string name, TypeTransferObject type, ClassTemplate classTemplate, IConfiguration configuration)
 {
     this.MapType(model.Language, configuration.Language, type);
     this.AddUsing(type, classTemplate, configuration);
     return(classTemplate.AddField(name, type.ToTemplate()).Public().FormatName(configuration));
 }
Beispiel #22
0
        protected virtual ClassTemplate WriteClass(IModelConfiguration configuration, ModelTransferObject model, string nameSpace, List <FileTemplate> files)
        {
            if (model.BasedOn != null)
            {
                this.MapType(model.Language, configuration.Language, model.BasedOn);
            }

            ClassTemplate classTemplate = files.AddFile(configuration.RelativePath, configuration.AddHeader)
                                          .AddNamespace(nameSpace)
                                          .AddClass(model.Name, model.BasedOn?.ToTemplate())
                                          .FormatName(configuration);

            if (model.BasedOn != null)
            {
                this.AddUsing(model.BasedOn, classTemplate, configuration);
            }
            configuration.Usings?.ForEach(x => classTemplate.AddUsing(x, null, null));

            classTemplate.IsInterface = model.IsInterface;
            classTemplate.IsAbstract  = model.IsAbstract;
            if (model.IsGeneric)
            {
                classTemplate.Generics.AddRange(model.Generics.Where(x => x.Alias != null).Select(x => new ClassGenericTemplate(x.Alias)));
            }
            foreach (TypeTransferObject interFace in model.Interfaces)
            {
                this.MapType(model.Language, configuration.Language, interFace);
                classTemplate.BasedOn.Add(new BaseTypeTemplate(classTemplate, Code.Interface(interFace.Name, interFace.Namespace)));
                this.AddUsing(interFace, classTemplate, configuration);
            }
            this.AddFields(model, classTemplate, configuration);
            this.AddProperties(model, classTemplate, configuration);
            return(classTemplate);
        }
Beispiel #23
0
        private void ReadClass(Type type, ModelTransferObject model, List <ITransferObject> transferObjects)
        {
            Logger.Trace($"Reflection read type {type.Name} ({type.Namespace})");
            if (type.BaseType != typeof(object) && type.BaseType != null)
            {
                model.BasedOn = this.Read(type.BaseType, transferObjects);
            }
            Dictionary <Type, string> genericMapping = new Dictionary <Type, string>();

            if (type.IsGenericType)
            {
                model.IsGeneric = true;
                model.Generics.Clear();
                foreach (Type argument in type.GenericTypeArguments)
                {
                    string alias = genericMapping.Count > 1 ? $"T{genericMapping.Count}" : "T";
                    genericMapping.Add(argument, alias);
                    model.Generics.Add(new GenericAliasTransferObject
                    {
                        Alias = alias,
                        Type  = this.Read(argument, transferObjects)
                    });
                }
            }

            model.IsInterface = type.IsInterface;
            model.IsAbstract  = type.IsAbstract;
            foreach (Type interFace in type.GetInterfaces(false))
            {
                model.Interfaces.Add(this.Read(interFace, transferObjects));
            }
            FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
            foreach (FieldInfo field in fields)
            {
                FieldTransferObject fieldTransferObject = new FieldTransferObject
                {
                    Name = field.Name,
                    Type = genericMapping.ContainsKey(field.FieldType)
                                                                         ? new TypeTransferObject {
                        Name = genericMapping[field.FieldType]
                    }
                                                                         : this.Read(field.FieldType, transferObjects)
                };
                model.Fields.Add(fieldTransferObject);
            }
            PropertyInfo[] properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
            foreach (PropertyInfo property in properties)
            {
                PropertyTransferObject propertyTransferObject = new PropertyTransferObject
                {
                    Name = property.Name,
                    Type = genericMapping.ContainsKey(property.PropertyType)
                                                                               ? new TypeTransferObject {
                        Name = genericMapping[property.PropertyType]
                    }
                                                                               : this.Read(property.PropertyType, transferObjects),
                    CanRead  = property.CanRead,
                    CanWrite = property.CanWrite
                };
                model.Properties.Add(propertyTransferObject);
            }
        }
Beispiel #24
0
        private Dictionary <IEdmType, TypeTransferObject> ReadModels(IEdmModel edmModel, List <ITransferObject> list)
        {
            Dictionary <IEdmType, TypeTransferObject>   modelMapping  = new Dictionary <IEdmType, TypeTransferObject>();
            Dictionary <IEdmType, EntityTransferObject> entityMapping = new Dictionary <IEdmType, EntityTransferObject>();

            foreach (IEdmSchemaType schemaType in edmModel.SchemaElements.Select(element => edmModel.FindDeclaredType(element.FullName())).Where(x => x != null))
            {
                if (schemaType.TypeKind == EdmTypeKind.Entity && schemaType is IEdmEntityType entityType)
                {
                    ModelTransferObject model = new ModelTransferObject
                    {
                        Name      = schemaType.Name,
                        Namespace = schemaType.Namespace,
                        Language  = ODataLanguage.Instance
                    };
                    modelMapping[entityType.AsActualType()] = model;
                    EntityTransferObject entity = new EntityTransferObject
                    {
                        Name  = schemaType.Name,
                        Model = model
                    };
                    entityMapping[entityType.AsActualType()] = entity;
                    foreach (IEdmProperty edmProperty in entityType.DeclaredProperties)
                    {
                        model.Properties.Add(new PropertyTransferObject
                        {
                            Name = edmProperty.Name,
                            Type = this.ToTransferObject(edmProperty.Type.Definition, modelMapping)
                        });
                    }
                    if (entityType.DeclaredKey != null)
                    {
                        foreach (IEdmStructuralProperty key in entityType.DeclaredKey)
                        {
                            PropertyTransferObject property = model.Properties.FirstOrDefault(x => x.Name == key.Name);
                            entity.Keys.Add(new EntityKeyTransferObject
                            {
                                Name     = key.Name,
                                Type     = this.ToTransferObject(key.Type.Definition, modelMapping).Clone(),
                                Property = property
                            });
                        }
                    }
                    // TODO: Add Navigation Properties
                    list.Add(model);
                    list.Add(entity);
                }
            }
            foreach (IEdmAction action in edmModel.SchemaElements.OfType <IEdmAction>())
            {
                IEdmType boundTo = action.FindParameter(BindingParameterName)?.Type.Definition;
                if (boundTo != null && modelMapping.ContainsKey(boundTo))
                {
                    EntityTransferObject       entity       = entityMapping[boundTo];
                    EntityActionTransferObject entityAction = new EntityActionTransferObject {
                        Name = action.Name, Namespace = action.Namespace
                    };
                    if (action.ReturnType != null)
                    {
                        entityAction.ReturnType = modelMapping[action.ReturnType.Definition];
                    }
                    entity.Actions.Add(entityAction);
                    foreach (IEdmOperationParameter actionParameter in action.Parameters.Where(parameter => parameter.Name != BindingParameterName))
                    {
                        entityAction.Parameters.Add(new EntityActionParameterTransferObject {
                            Name = actionParameter.Name, Type = modelMapping[actionParameter.Type.Definition]
                        });
                    }
                }
                else
                {
                    // TODO: Unbound actions
                }
            }
            return(modelMapping);
        }
Beispiel #25
0
        protected virtual ClassTemplate WriteClass(ModelTransferObject model, string relativePath)
        {
            IOptions modelOptions = this.Options.Get(model);

            if (model.BasedOn != null && model.Language != null && modelOptions.Language != null)
            {
                this.MapType(model.Language, modelOptions.Language, model.BasedOn);
            }

            bool          isInterface        = model.IsInterface || modelOptions.PreferInterfaces;
            string        modelNamespace     = modelOptions.SkipNamespace ? string.Empty : model.Namespace;
            ClassTemplate otherClassTemplate = this.files.Where(file => file.RelativePath == relativePath &&
                                                                file.Options.Language == modelOptions.Language)
                                               .SelectMany(file => file.Namespaces)
                                               .SelectMany(ns => ns.Children).OfType <ClassTemplate>()
                                               .FirstOrDefault(x => x.Namespace.Name == modelNamespace && x.Name == model.Name);
            NamespaceTemplate namespaceTemplate = otherClassTemplate?.Namespace ?? this.files.AddFile(relativePath, modelOptions)
                                                  .WithName(model.FileName)
                                                  // .WithType(isInterface ? "interface" : null)
                                                  .AddNamespace(modelNamespace);

            ClassTemplate classTemplate = namespaceTemplate.AddClass(model.Name, model.BasedOn?.ToTemplate())
                                          .FormatName(modelOptions);

            if (model.BasedOn != null)
            {
                this.AddUsing(model.BasedOn, classTemplate, modelOptions);
            }

            classTemplate.IsInterface = isInterface;
            classTemplate.IsAbstract  = model.IsAbstract;
            if (model is GenericModelTransferObject generic)
            {
                generic.Template.Generics.Select(x => new ClassGenericTemplate(x.Alias.Name)).ForEach(classTemplate.Generics.Add);
            }
            foreach (TypeTransferObject interFace in model.Interfaces)
            {
                if (model.Language != null && modelOptions.Language != null)
                {
                    this.MapType(model.Language, modelOptions.Language, interFace);
                }
                if (interFace.Name == model.Name)
                {
                    continue;
                }
                classTemplate.BasedOn.Add(new BaseTypeTemplate(classTemplate, interFace.ToTemplate()));
                this.AddUsing(interFace, classTemplate, modelOptions);
            }
            if (model is GenericModelTransferObject genericModel)
            {
                this.AddConstants(genericModel.Template, classTemplate);
                this.AddFields(genericModel.Template, classTemplate);
                this.AddProperties(genericModel.Template, classTemplate);
            }
            else
            {
                this.AddConstants(model, classTemplate);
                this.AddFields(model, classTemplate);
                this.AddProperties(model, classTemplate);
            }
            return(classTemplate);
        }
Beispiel #26
0
        public ModelTransferObject Read(Type type, IOptions caller = null)
        {
            ModelTransferObject model = new() { Language = ReflectionLanguage.Instance, Type = type };

            model.Name               = model.OriginalName = type.Name;
            model.Namespace          = type.Namespace;
            model.IsNullable         = !type.IsValueType;
            model.IsGeneric          = type.IsGenericType;
            model.IsGenericParameter = type.IsGenericParameter;
            model.FromSystem         = type.Namespace != null && type.Namespace.StartsWith("System");

            IOptions typeOptions = this.options.Get(type, caller);

            if (model.IsGeneric)
            {
                model.Name = model.OriginalName = type.Name.Split('`').First();
                model      = new GenericModelTransferObject(model);
            }
            ModelTransferObject existingModel = this.transferObjects.OfType <ModelTransferObject>().FirstOrDefault(entry => entry.Equals(model));

            if (existingModel != null)
            {
                // TODO: Replace complete if with cached model reading after cloning of TransferModels is fixed
                if (model.IsGeneric)
                {
                    GenericModelTransferObject genericModel = new(existingModel);
                    existingModel = genericModel;
                    this.options.Set(existingModel, typeOptions);
                    this.ApplyGenericTemplate(type, genericModel);
                    this.transferObjects.Add(existingModel);
                }
                return(existingModel);
            }
            // TODO: Uncomment cached model reading after cloning of TransferModels is fixed
            // existingModel = this.environment.TransferObjects.OfType<ModelTransferObject>().FirstOrDefault(entry => entry.Equals(model));
            // if (existingModel != null)
            // {
            //     return this.ReadExisting(existingModel, caller);
            // }
            this.options.Set(model, typeOptions);
            if (typeOptions.Ignore)
            {
                Logger.Trace($"{type.Name} ({type.Namespace}) ignored (decorated with {nameof(GenerateIgnoreAttribute)})");
                return(model);
            }
            if (type.IsGenericParameter)
            {
                return(model);
            }
            if (type.IsArray)
            {
                this.ReadArray(type, model);
            }
            else if (model.IsGeneric && model.FromSystem)
            {
                this.ReadGenericFromSystem(type, model);
            }
            else if (type.IsEnum)
            {
                this.transferObjects.Add(model);
                this.ReadEnum(type, model);
            }
            else if (!model.FromSystem)
            {
                this.transferObjects.Add(model);
                this.ReadClass(type, model, caller);
            }
            if (model.Name == nameof(Nullable))
            {
                model.IsNullable = true;
            }
            return(model);
        }