예제 #1
0
        private async Task TransformAsync(AssemblyLoader.AssemblyLoader assemblyLoader)
        {
            if (!string.IsNullOrEmpty(DocumentTemplate))
            {
                if (await DynamicApis.FileExistsAsync(DocumentTemplate).ConfigureAwait(false))
                {
                    Settings.DocumentTemplate = await DynamicApis.FileReadAllTextAsync(DocumentTemplate).ConfigureAwait(false);
                }
                else
                {
                    Settings.DocumentTemplate = DocumentTemplate;
                }

                if (!string.IsNullOrEmpty(Settings.DocumentTemplate) && !Settings.DocumentTemplate.StartsWith("{"))
                {
                    Settings.DocumentTemplate = (await SwaggerYamlDocument.FromYamlAsync(Settings.DocumentTemplate)).ToJson();
                }
            }
            else
            {
                Settings.DocumentTemplate = null;
            }

            if (DocumentProcessorTypes != null)
            {
                foreach (var p in DocumentProcessorTypes)
                {
                    var processor = (IDocumentProcessor)assemblyLoader.CreateInstance(p);
                    Settings.DocumentProcessors.Add(processor);
                }
            }

            if (OperationProcessorTypes != null)
            {
                foreach (var p in OperationProcessorTypes)
                {
                    var processor = (IOperationProcessor)assemblyLoader.CreateInstance(p);
                    Settings.OperationProcessors.Add(processor);
                }
            }

            if (!string.IsNullOrEmpty(TypeNameGeneratorType))
            {
                Settings.TypeNameGenerator = (ITypeNameGenerator)assemblyLoader.CreateInstance(TypeNameGeneratorType);
            }

            if (!string.IsNullOrEmpty(SchemaNameGeneratorType))
            {
                Settings.SchemaNameGenerator = (ISchemaNameGenerator)assemblyLoader.CreateInstance(SchemaNameGeneratorType);
            }
        }
예제 #2
0
        public async Task When_yaml_schema_has_references_it_works(string relativePath)
        {
            //// Arrange
            var path = GetTestDirectory() + relativePath;

            //// Act
            var document = await SwaggerYamlDocument.FromFileAsync(path);

            var json = document.ToJson();

            //// Assert
            Assert.Equal(JsonObjectType.Integer, document.Definitions["ContractObject"].Properties["foo"].ActualTypeSchema.Type);
            Assert.Equal(JsonObjectType.Boolean, document.Definitions["ContractObject"].Properties["bar"].ActualTypeSchema.Type);
        }
예제 #3
0
        public async Task When_body_is_binary_then_blob_is_used_as_parameter_in_TypeScript()
        {
            var yaml = @"openapi: 3.0.0
servers:
  - url: https://www.example.com/
info:
  version: '2.0.0'
  title: 'Test API'   
paths:
  /files:
    post:
      tags:
        - Files
      summary: 'Add File'
      operationId: addFile
      responses:
        '200':
          content:
            application/xml:
              schema:
                $ref: '#/components/schemas/FileToken'
      requestBody:
        content:
          image/png:
            schema:
              type: string
              format: binary
components:
  schemas:
    FileToken:
      type: object
      required:
        - fileId    
      properties:  
        fileId:
          type: string
          format: uuid";

            var document = await SwaggerYamlDocument.FromYamlAsync(yaml);

            //// Act
            var codeGenerator = new SwaggerToTypeScriptClientGenerator(document, new SwaggerToTypeScriptClientGeneratorSettings());
            var code          = codeGenerator.GenerateFile();

            //// Assert
            Assert.Contains("addFile(body: Blob | undefined): ", code);
            Assert.Contains("\"Content-Type\": \"image/png\"", code);
            Assert.Contains("\"Accept\": \"application/xml\"", code);
            Assert.Contains("const content_ = body;", code);
        }
예제 #4
0
        public async Task When_body_is_binary_then_stream_is_used_as_parameter_in_CSharp()
        {
            var yaml = @"openapi: 3.0.0
servers:
  - url: https://www.example.com/
info:
  version: '2.0.0'
  title: 'Test API'   
paths:
  /files:
    post:
      tags:
        - Files
      summary: 'Add File'
      operationId: addFile
      responses:
        '200':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/FileToken'
      requestBody:
        content:
          image/png:
            schema:
              type: string
              format: binary
components:
  schemas:
    FileToken:
      type: object
      required:
        - fileId    
      properties:  
        fileId:
          type: string
          format: uuid";

            var document = await SwaggerYamlDocument.FromYamlAsync(yaml);

            //// Act
            var codeGenerator = new SwaggerToCSharpClientGenerator(document, new SwaggerToCSharpClientGeneratorSettings());
            var code          = codeGenerator.GenerateFile();

            //// Assert
            Assert.Contains("public async System.Threading.Tasks.Task<FileToken> AddFileAsync(System.IO.Stream body, System.Threading.CancellationToken cancellationToken)", code);
            Assert.Contains("var content_ = new System.Net.Http.StreamContent(body);", code);
        }
예제 #5
0
 public static async Task <SwaggerDocument> LoadFromStringAsync(string data)
 {
     try
     {
         return(await SwaggerDocument.FromJsonAsync(data));
     }
     catch
     {
         try
         {
             return(await SwaggerYamlDocument.FromYamlAsync(data));
         }
         catch
         {
             throw new InvalidOperationException("Could not determine content type");
         }
     }
 }
예제 #6
0
        private static void GenerateCode(ExchangeSettings exchangeSettings)
        {
            try
            {
                Console.WriteLine($"Generating Documentation for {exchangeSettings.ExchangeName}");
                var document =
                    SwaggerYamlDocument.FromUrlAsync(exchangeSettings.SwaggerFileUrl).Result;

                var settings = new SwaggerToCSharpClientGeneratorSettings
                {
                    ClassName = $"{exchangeSettings.ExchangeName}Client",
                    CSharpGeneratorSettings =
                    {
                        Namespace  = $"CryptoSharp.Client.Exchanges.{exchangeSettings.ExchangeName}",
                        SchemaType = SchemaType.OpenApi3,
                        ClassStyle = CSharpClassStyle.Poco,
                    },
                    GenerateClientInterfaces = true,
                    CodeGeneratorSettings    = { SchemaType = SchemaType.OpenApi3 },
                };



                var generator = new SwaggerToCSharpClientGenerator(document, settings);
                var code      = generator.GenerateFile();

                // hack to replace double by decimal
                var regex = new Regex("\\sdouble\\s", RegexOptions.Multiline);

                code = regex.Replace(code, " decimal ");

                if (!Directory.Exists(_generatedDirectory))
                {
                    Directory.CreateDirectory(_generatedDirectory);
                }

                File.WriteAllText($"{ _generatedDirectory}/{exchangeSettings.ExchangeName}Client.cs", code);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
예제 #7
0
 protected async Task <SwaggerDocument> ReadSwaggerDocumentAsync(string input)
 {
     if (!IsJson(input) && !IsYaml(input))
     {
         if (input.StartsWith("http://") || input.StartsWith("https://"))
         {
             if (input.EndsWith(".yaml", StringComparison.OrdinalIgnoreCase) ||
                 input.EndsWith(".yml", StringComparison.OrdinalIgnoreCase))
             {
                 return(await SwaggerYamlDocument.FromUrlAsync(input).ConfigureAwait(false));
             }
             else
             {
                 return(await SwaggerDocument.FromUrlAsync(input).ConfigureAwait(false));
             }
         }
         else
         {
             if (input.EndsWith(".yaml", StringComparison.OrdinalIgnoreCase) ||
                 input.EndsWith(".yml", StringComparison.OrdinalIgnoreCase))
             {
                 return(await SwaggerYamlDocument.FromFileAsync(input).ConfigureAwait(false));
             }
             else
             {
                 return(await SwaggerDocument.FromFileAsync(input).ConfigureAwait(false));
             }
         }
     }
     else
     {
         if (IsYaml(input))
         {
             return(await SwaggerYamlDocument.FromYamlAsync(input).ConfigureAwait(false));
         }
         else
         {
             return(await SwaggerDocument.FromJsonAsync(input).ConfigureAwait(false));
         }
     }
 }
예제 #8
0
        public static async Task <SwaggerDocument> LoadFromUrlAsync(string url)
        {
            var http     = new HttpClient();
            var response = await http.GetAsync(url);

            if (response.Content == null)
            {
                throw new InvalidOperationException("Request did not return any content");
            }

            var data = await response.Content.ReadAsStringAsync();

            switch (response.Content.Headers.ContentType?.MediaType)
            {
            case "text/json": return(await SwaggerDocument.FromJsonAsync(data));

            case "text/yaml": return(await SwaggerYamlDocument.FromYamlAsync(data));

            // If no proper content type is provided, try both: JSON, then YAML
            default: return(await LoadFromStringAsync(data));
            }
        }
예제 #9
0
 /// <summary>Loads the Swagger spec.</summary>
 public async Task <SwaggerDocument> RunAsync()
 {
     if (!string.IsNullOrEmpty(Swagger))
     {
         if (Swagger.StartsWith("{"))
         {
             return(await SwaggerDocument.FromJsonAsync(Swagger).ConfigureAwait(false));
         }
         else
         {
             return(await SwaggerYamlDocument.FromYamlAsync(Swagger).ConfigureAwait(false));
         }
     }
     else if (Url.StartsWith("http://") || Url.StartsWith("https://"))
     {
         if (Url.EndsWith(".yaml", StringComparison.OrdinalIgnoreCase))
         {
             return(await SwaggerYamlDocument.FromUrlAsync(Url).ConfigureAwait(false));
         }
         else
         {
             return(await SwaggerDocument.FromUrlAsync(Url).ConfigureAwait(false));
         }
     }
     else
     {
         if (Url.EndsWith(".yaml", StringComparison.OrdinalIgnoreCase))
         {
             return(await SwaggerYamlDocument.FromFileAsync(Url).ConfigureAwait(false));
         }
         else
         {
             return(await SwaggerDocument.FromFileAsync(Url).ConfigureAwait(false));
         }
     }
 }
예제 #10
0
 protected Task <bool> TryWriteDocumentOutputAsync(IConsoleHost host, Func <SwaggerDocument> generator)
 {
     return(TryWriteFileOutputAsync(OutputFilePath, host, () =>
                                    OutputFilePath.EndsWith(".yaml", StringComparison.OrdinalIgnoreCase) ? SwaggerYamlDocument.ToYaml(generator()) : generator().ToJson()));
 }
예제 #11
0
 public static Task <bool> TryWriteDocumentOutputAsync(this IOutputCommand command, IConsoleHost host, Func <SwaggerDocument> generator)
 {
     return(TryWriteFileOutputAsync(command, command.OutputFilePath, host, () =>
                                    command.OutputFilePath.EndsWith(".yaml", StringComparison.OrdinalIgnoreCase) ? SwaggerYamlDocument.ToYaml(generator()) : generator().ToJson()));
 }
예제 #12
0
        public async Task <SwaggerDocument> RunAsync()
        {
            return(await Task.Run(async() =>
            {
                if (!string.IsNullOrEmpty(DocumentTemplate))
                {
                    if (await DynamicApis.FileExistsAsync(DocumentTemplate).ConfigureAwait(false))
                    {
                        Settings.DocumentTemplate = await DynamicApis.FileReadAllTextAsync(DocumentTemplate).ConfigureAwait(false);
                    }
                    else
                    {
                        Settings.DocumentTemplate = DocumentTemplate;
                    }

                    if (!string.IsNullOrEmpty(Settings.DocumentTemplate) && !Settings.DocumentTemplate.StartsWith("{"))
                    {
                        Settings.DocumentTemplate = (await SwaggerYamlDocument.FromYamlAsync(Settings.DocumentTemplate)).ToJson();
                    }
                }
                else
                {
                    Settings.DocumentTemplate = null;
                }

                var generator = new WebApiAssemblyToSwaggerGenerator(Settings);

                var controllerNames = ControllerNames.Where(s => !string.IsNullOrWhiteSpace(s)).Distinct().ToList();
                if (!controllerNames.Any() && Settings.AssemblySettings.AssemblyPaths?.Length > 0)
                {
                    controllerNames = generator.GetExportedControllerClassNames().ToList();
                }

                var document = await generator.GenerateForControllersAsync(controllerNames).ConfigureAwait(false);
                if (ServiceHost == ".")
                {
                    document.Host = string.Empty;
                }
                else if (!string.IsNullOrEmpty(ServiceHost))
                {
                    document.Host = ServiceHost;
                }

                if (!string.IsNullOrEmpty(InfoTitle))
                {
                    document.Info.Title = InfoTitle;
                }
                if (!string.IsNullOrEmpty(InfoVersion))
                {
                    document.Info.Version = InfoVersion;
                }
                if (!string.IsNullOrEmpty(InfoDescription))
                {
                    document.Info.Description = InfoDescription;
                }

                if (ServiceSchemes != null && ServiceSchemes.Any())
                {
                    document.Schemes = ServiceSchemes.Select(s => (SwaggerSchema)Enum.Parse(typeof(SwaggerSchema), s, true)).ToList();
                }

                if (!string.IsNullOrEmpty(ServiceBasePath))
                {
                    document.BasePath = ServiceBasePath;
                }

                return document;
            }));
        }