mardi 28 mai 2019

Generate a swagger file from unknown objects (.net)

I want to develop a new API. It must connect a Dynamics CRM and front developers.

Today, the developed "workaround" is :

  1. Fill an Excel file to describe the CRM and custom objects (with fetchXml, ...)
  2. Write and concatenate strings to write a YAML file.
  3. Copy this file to swagger editor and make tests with Postman

In a first step, I want to generate the schema without strings concatenations... (temporarily, waiting to replace the Excel file with OData and ASP.NET Core to have something more powerful)

For the moment, I use reflection to build my objects from the Excel file:

using System.Reflection;
using System.Reflection.Emit;
using Swashbuckle.Swagger;
...

var assemblyName = new AssemblyName(Guid.NewGuid().ToString();
var assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
var moduleBuilder = assemblyBuilder.DefineDynamicModule("Module");
var typeBuilder = moduleBuilder.DefineType(entity.CrmEntityName);
foreach (var attribute in entity.Attributes)
{
    Type t = typeof(int);
    switch (attribute.DataType.ToLower())
    {
        case "string":
            t = typeof(string);
            break;
        case "integer":
            t = typeof(int);
            break;
        case "date":
            t = typeof(DateTime);
            break;
    }
    typeBuilder.DefineField(attribute.CrmName, t.GetType(), FieldAttributes.Public);
    var type = typeBuilder.CreateType();

    // create the Swagger models here
}

How can I generate my swagger from these types and properties? I've view an object named Schema which contains a name and another Schema, I don't know if is a wrong way...





Aucun commentaire:

Enregistrer un commentaire