Ejemplo n.º 1
0
        public static void Main()
        {
            var document = OpenApiDocument.FromUrlAsync("https://*****:*****@"..\..\..\..\Squidex.ClientLibrary\Management\Generated.cs", code);
        }
Ejemplo n.º 2
0
        static async Task Main(string[] args)
        {
            Console.WriteLine("准备生成,请键入回车键开始......");
            Console.ReadLine();

            var swaggerJsonUrl = @"https://localhost:5001/swagger/MiCake%20Demo%20Application/swagger.json";

            var document = await OpenApiDocument.FromUrlAsync(swaggerJsonUrl);

            var settings = new TypeScriptClientGeneratorSettings
            {
                ImportRequiredTypes   = false,
                GenerateClientClasses = false,      //是否生成请求的Client,因为使用了自定义的httpClient,所以不使用生成的版本。
                GenerateDtoTypes      = true,
            };

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

            //生成的路径,为了避免手动手改的内容被替换,所以不直接生成到前端项目的解决方案中。
            File.WriteAllText("nswagCode.ts", code);

            Console.WriteLine("生成完成......");
            Console.ReadLine();
        }
Ejemplo n.º 3
0
        public static void Main()
        {
            var document = OpenApiDocument.FromUrlAsync("https://localhost:5002/api/openapi.json").Result;

            GenerateTypescript(document);
            GenerateCSharp(document);
        }
Ejemplo n.º 4
0
        static async Task Main(string[] args)
        {
            // var document = OpenApiDocument.FromUrlAsync("https://firefinder.azurewebsites.net/swagger/v1/swagger.json");
            var document = OpenApiDocument.FromUrlAsync("https://localhost:5000/swagger/v1/swagger.json");

            var settings = new TypeScriptClientGeneratorSettings
            {
                ClassName                = "{controller}Client",
                HttpClass                = HttpClass.HttpClient,
                InjectionTokenType       = InjectionTokenType.InjectionToken,
                ImportRequiredTypes      = true,
                Template                 = TypeScriptTemplate.Angular,
                GenerateClientClasses    = true,
                GenerateClientInterfaces = true
            };

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

            string path = "firefinder-api.service.ts";

            using (StreamWriter sw = File.CreateText(path))
                sw.WriteLine(code);

            Console.WriteLine("Done");
        }
Ejemplo n.º 5
0
        public async Task <IActionResult> Generate()
        {
            string          baseUrl  = $"{this.Request.Scheme}://{this.Request.Host.Value.ToString()}{this.Request.PathBase.Value.ToString()}";
            OpenApiDocument document = await OpenApiDocument.FromUrlAsync($"{baseUrl}/swagger/v1/swagger.json");

            TypeScriptClientGeneratorSettings settings = new TypeScriptClientGeneratorSettings
            {
                Template                   = TypeScriptTemplate.Axios,
                PromiseType                = PromiseType.Promise,
                HttpClass                  = HttpClass.Http,
                InjectionTokenType         = InjectionTokenType.InjectionToken,
                BaseUrlTokenName           = "Authorization",
                WithCredentials            = true,
                ClientBaseClass            = "ApiClientBase",
                GenerateClientClasses      = true,
                UseTransformOptionsMethod  = true,
                UseTransformResultMethod   = true,
                GenerateOptionalParameters = true,
            };

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

            return(Content(code));
        }
Ejemplo n.º 6
0
        static async Task Main(CliOptions options)
        {
            Console.WriteLine("Start");
            await ClearOutput(options.OutputDirectory);

            try
            {
                Console.Write("Load Swagger JSON...\t");
                var swaggerDoc = await OpenApiDocument.FromUrlAsync(options.URL);

                Console.WriteLine("OK");

                switch (SchemaType = swaggerDoc.SchemaType)
                {
                case SchemaType.Swagger2:
                    Console.WriteLine("SchemaType: Swagger2");
                    break;

                case SchemaType.OpenApi3:
                    Console.WriteLine("SchemaType: OpenApi3");
                    break;

                default:
                    Console.WriteLine("SchemaType: Unsupported");
                    break;
                }

                Console.Write("Analysis Models...\t");
                var types = await LoadTypes(swaggerDoc);

                Console.WriteLine("OK");

                Console.Write("Analysis Services...\t");
                var services = await LoadServices(swaggerDoc, types);

                Console.WriteLine("OK");

                Console.Write("Output Models...\t");
                await OutputTypes(options, types);

                Console.WriteLine("OK");

                Console.Write("Output Services...\t");
                await OutputServices(options, services);

                Console.WriteLine("OK");

                Console.Write("Output Module...\t");
                await OutputModule(options, Path.Combine(options.OutputDirectory, FirstCharToLower(options.ModuleName) + ".module.ts"), options.ModuleName, services);
                await OutputModuleIndexTs(options, Path.Combine(options.OutputDirectory, "index.ts"), options.ModuleName);

                Console.WriteLine("OK");
            }
            catch
            {
                Console.WriteLine("ERROR");
            }

            Console.WriteLine("Finish");
        }
Ejemplo n.º 7
0
        public async Task <IActionResult> GenerateCSharpClient(GenerateCSharpClientRequest request)
        {
            try
            {
                OpenApiDocument document;
                try
                {
                    document = await OpenApiDocument.FromUrlAsync(request.SwaggerContractEndpoint.AbsoluteUri);
                }
                catch (HttpRequestException ex)
                {
                    return(StatusCode(404, ex.Message));
                }

                var settings = new CSharpClientGeneratorSettings
                {
                    ClassName = "{controller}Client",
                };

                var generator = new CSharpClientGenerator(document, settings);
                var code      = generator.GenerateFile();
                return(StatusCode(200, code));
            }
            catch (Exception ex)
            {
                return(StatusCode(500, new ServerError500Response(ex)
                {
                    Endpoint = request.SwaggerContractEndpoint
                }));
            }
        }
Ejemplo n.º 8
0
        public async Task Should_provide_general_spec()
        {
            var url = $"{_.ClientManager.Options.Url}/api/swagger/v1/swagger.json";

            var document = await OpenApiDocument.FromUrlAsync(url);

            Assert.NotNull(document);
        }
Ejemplo n.º 9
0
        public async Task Should_provide_flat_content_spec()
        {
            var url = $"{_.ClientManager.Options.Url}/api/content/{_.AppName}/flat/swagger/v1/swagger.json";

            var document = await OpenApiDocument.FromUrlAsync(url);

            Assert.NotNull(document);
        }
Ejemplo n.º 10
0
        private async Task <OpenApiDocument> DownloadOpenApiDocument()
        {
            Text.WhiteLine($"Downloading from [{Config.Address}]");

            //https://swagger.io/docs/specification/basic-structure/
            var gen = await OpenApiDocument.FromUrlAsync(Config.Address);

            gen.GenerateOperationIds();
            return(gen);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// 获取swagger文档
        /// </summary>
        /// <param name="swagger"></param>
        /// <returns></returns>
        private static OpenApiDocument GetDocument(string swagger)
        {
            Console.WriteLine($"正在分析OpenApi:{swagger}");
            if (Uri.TryCreate(swagger, UriKind.Absolute, out _))
            {
                return(OpenApiDocument.FromUrlAsync(swagger).Result);
            }

            return(OpenApiDocument.FromFileAsync(swagger).Result);
        }
Ejemplo n.º 12
0
        public async Task When_openapi_is_loaded_without_scopes_it_should_deserialize()
        {
            // Arrange


            // Act
            var document = await OpenApiDocument.FromUrlAsync("https://raw.githubusercontent.com/microsoft/commercial-marketplace-openapi/main/Microsoft.Marketplace.SaaS/2018-08-31/saasapi.v2.json");

            // Assert
            Assert.True(document.SchemaType == NJsonSchema.SchemaType.OpenApi3);
        }
Ejemplo n.º 13
0
        public async Task When_Swagger_is_loaded_from_url_schematype_is_Swagger2()
        {
            //// Arrange


            //// Act
            var document = await OpenApiDocument.FromUrlAsync("http://petstore.swagger.io/v2/swagger.json");

            //// Assert
            Assert.True(document.SchemaType == NJsonSchema.SchemaType.Swagger2);
        }
Ejemplo n.º 14
0
        // TODO: Reenable test
        //[Fact]
        public async Task When_OpenApi_is_loaded_from_url_schematype_is_OpenApi3()
        {
            //// Arrange


            //// Act
            var document = await OpenApiDocument.FromUrlAsync("https://api.percipio.com/common/swagger.json");

            //// Assert
            Assert.True(document.SchemaType == NJsonSchema.SchemaType.OpenApi3);
        }
Ejemplo n.º 15
0
        public async Task When_Swagger_is_loaded_from_url_then_it_works()
        {
            //// Arrange


            //// Act
            var document = await OpenApiDocument.FromUrlAsync("http://petstore.swagger.io/v2/swagger.json");

            //// Assert
            Assert.NotNull(document);
        }
Ejemplo n.º 16
0
 /// <summary>
 /// 获取OpenApi描述文档
 /// </summary>
 /// <param name="openApi"></param>
 /// <returns></returns>
 private static OpenApiDocument GetDocument(string openApi)
 {
     Console.WriteLine($"正在分析OpenApi:{openApi}");
     if (Uri.TryCreate(openApi, UriKind.Absolute, out var api))
     {
         if (api.Scheme.StartsWith(Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase))
         {
             return(OpenApiDocument.FromUrlAsync(openApi).Result);
         }
     }
     return(OpenApiDocument.FromFileAsync(openApi).Result);
 }
Ejemplo n.º 17
0
 /// <summary>
 /// 获取OpenApi描述文档
 /// </summary>
 /// <param name="openApi"></param>
 /// <returns></returns>
 private static OpenApiDocument GetDocument(string openApi)
 {
     Console.WriteLine($"正在分析OpenApi:{openApi}");
     if (Uri.TryCreate(openApi, UriKind.Absolute, out var _) == true)
     {
         return(OpenApiDocument.FromUrlAsync(openApi).Result);
     }
     else
     {
         return(OpenApiDocument.FromFileAsync(openApi).Result);
     }
 }
Ejemplo n.º 18
0
        public static async Task Main(string[] args)
        {
            const string apiClientClassName         = "OpenWaterApiClient";
            const string apiExceptionClassName      = "OpenWaterApiException";
            const string generatedClientFilePostfix = "Generated";
            const string apiClientNamespace         = "OpenWater.ApiClient";
            var          outputPath          = GetApiClientProjectDirectoryPath();
            var          generatedModelsPath = Path.Combine(outputPath, "Models", "Generated");

#if DEBUG
            var apiDocument = await OpenApiDocument.FromUrlAsync("http://localhost:11100/swagger/v2/swagger.json");
#else
            var apiDocument = await OpenApiDocument.FromUrlAsync("https://api.secure-platform.com/swagger/v2/swagger.json");
#endif

            apiDocument.SchemaType = SchemaType.OpenApi3;

            GenerateClient(apiDocument, outputPath, apiClientClassName, generatedClientFilePostfix, CSharpClientGeneratorSettingsCreator, out var typeNameHintsModelWithNamespaceInfos);

            GenerateModels(apiDocument, generatedModelsPath, apiClientNamespace, CSharpClientGeneratorSettingsCreator, typeNameHintsModelWithNamespaceInfos);

            GenerateDefinitions(apiDocument, generatedModelsPath, apiClientNamespace, CSharpClientGeneratorSettingsCreator, typeNameHintsModelWithNamespaceInfos);

            Console.Write("Press any key to exit...");
            Console.ReadKey(true);

            CSharpClientGeneratorSettings CSharpClientGeneratorSettingsCreator()
            {
                return(new CSharpClientGeneratorSettings
                {
                    CSharpGeneratorSettings =
                    {
                        Namespace                       = apiClientNamespace,
                        ClassStyle                      = CSharpClassStyle.Record,
                        GenerateDataAnnotations         = false,
                        TemplateDirectory               = "Templates",
                        RequiredPropertiesMustBeDefined = true
                    },
                    ParameterNameGenerator = new ParameterNameGenerator(),
                    AdditionalNamespaceUsages = new[] { "OpenWater.ApiClient.Definitions" },
                    OperationNameGenerator = new SingleClientFromOperationIdOperationNameGenerator(),
                    ClientClassAccessModifier = "public sealed",
                    ExcludedParameterNames = new[] { "X-ClientKey", "X-ApiKey" },
                    GenerateOptionalParameters = true,
                    ExceptionClass = apiExceptionClassName,
                    GenerateSyncMethods = true,
                    GenerateExceptionClasses = false,
                    ParameterDateTimeFormat = "u"
                });
            }
        }
Ejemplo n.º 19
0
        static void Main(string[] args)
        {
            var swagger        = "baseUrl";
            var result         = OpenApiDocument.FromUrlAsync(swagger).Result;
            var clientSettings = new CSharpRefitGeneratorSettings
            {
                UseActionResultType    = true,
                WrapResponses          = false,
                OperationNameGenerator = new MultipleClientsFromFirstTagAndOperationIdGenerator()
            };

            clientSettings.CodeGeneratorSettings.TemplateFactory = new RefitTemplateFactory(clientSettings.CSharpGeneratorSettings, new Assembly[3]
            {
                typeof(CSharpGeneratorSettings).GetTypeInfo().Assembly,
                typeof(CSharpGeneratorBaseSettings).GetTypeInfo().Assembly,
                typeof(CSharpRefitGeneratorSettings).GetTypeInfo().Assembly
            });
            clientSettings.CSharpGeneratorSettings.Namespace         = "Cms";
            clientSettings.CSharpGeneratorSettings.ArrayType         = "List";
            clientSettings.CSharpGeneratorSettings.ArrayInstanceType = "List";
            clientSettings.ResponseArrayType      = "ICollection";
            clientSettings.ResponseDictionaryType = "IDictionary";

            clientSettings.ParameterArrayType      = "IEnumerable";
            clientSettings.ParameterDictionaryType = "IDictionary";
            var clientGenerator = new CSharpRefitGenerator(result, clientSettings);
            var data            = clientGenerator.GetAllClientType();
            var models          = clientGenerator.GetAllGenerateDtoType();
            var dir             = Path.Combine("output", clientSettings.CSharpGeneratorSettings.Namespace);
            var apisPath        = Path.Combine(dir, "HttpApis");
            var modelsPath      = Path.Combine(dir, "HttpModels");

            Directory.CreateDirectory(apisPath);
            Directory.CreateDirectory(modelsPath);

            foreach (var api in data)
            {
                var file = Path.Combine(apisPath, $"{api.TypeName}.cs");
                File.WriteAllText(file, api.Code, Encoding.UTF8);
                Console.WriteLine($"输出接口文件:{file}");
            }
            foreach (var model in models)
            {
                var file = Path.Combine(modelsPath, $"{model.TypeName}.cs");
                File.WriteAllText(file, model.Code, Encoding.UTF8);
                Console.WriteLine($"输出模型文件:{file}");
            }
            Console.WriteLine("Hello World!");
        }
Ejemplo n.º 20
0
        private static string Generate()
        {
            const string SwaggerSpecUrl = "https://localhost:44376/swagger/v1/swagger.json";

            var document = OpenApiDocument.FromUrlAsync(SwaggerSpecUrl).Result;

            var settings = new TypeScriptClientGeneratorSettings
            {
                ClassName = "{controller}Client",
            };

            var generator = new TypeScriptClientGenerator(document, settings);

            return(generator.GenerateFile());
        }
Ejemplo n.º 21
0
        async static Task GenerateCSharpClient(string url, string generatePath) =>
        await GenerateClient(
            document : await OpenApiDocument.FromUrlAsync(url),
            generatePath : generatePath,
            generateCode : (OpenApiDocument document) =>
        {
            var settings = new CSharpClientGeneratorSettings
            {
                UseBaseUrl = false
            };

            var generator = new CSharpClientGenerator(document, settings);
            var code      = generator.GenerateFile();
            return(code);
        }
            );
Ejemplo n.º 22
0
        async static Task GenerateTypeScriptClient(string url, string generatePath) =>
        await GenerateClient(
            document : await OpenApiDocument.FromUrlAsync(url),
            generatePath : generatePath,
            generateCode : (OpenApiDocument document) =>
        {
            var settings = new TypeScriptClientGeneratorSettings();

            settings.TypeScriptGeneratorSettings.TypeStyle         = TypeScriptTypeStyle.Interface;
            settings.TypeScriptGeneratorSettings.TypeScriptVersion = 3.5M;
            settings.TypeScriptGeneratorSettings.DateTimeType      = TypeScriptDateTimeType.String;

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

            return(code);
        }
            );
        static async Task Main(string[] args)
        {
            var document = await OpenApiDocument.FromUrlAsync("https://localhost:5001/swagger/v1/swagger.json");

            var settings = new CSharpClientGeneratorSettings
            {
                CSharpGeneratorSettings =
                {
                    Namespace = "ImageRecognition.API.Client",
                }
            };

            var generator = new CSharpClientGenerator(document, settings);
            var code      = generator.GenerateFile();
            var fullPath  = DetermienFullFilePath("ImageRecognitionClient.cs");

            File.WriteAllText(fullPath, code);
        }
        public static async Task Run(string nightscoutBaseUri, string filename)
        {
            var uri      = Prep(nightscoutBaseUri);
            var document = await OpenApiDocument.FromUrlAsync(uri);

            var settings = new CSharpClientGeneratorSettings
            {
                ClassName = "Client",
                CSharpGeneratorSettings =
                {
                    Namespace = "Nightscout.API"
                }
            };

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

            File.WriteAllText(filename, code);
        }
Ejemplo n.º 25
0
        public async Task Generate(string url)
        {
            var document = await OpenApiDocument.FromUrlAsync(url);


            var settings = new CSharpClientGeneratorSettings
            {
                CSharpGeneratorSettings =
                {
                    Namespace = "SomeNameSpace",
                },

                OperationNameGenerator      = new MultipleClientsOperationNameGenerator(),
                GenerateBaseUrlProperty     = false,
                UseHttpClientCreationMethod = true,
            };
            var destinationPath = Path.GetFullPath(@"..\..\..\");
            var generator       = new CSharpClientGenerator(document, settings);

            var clients = generator.GenerateFile(NSwag.CodeGeneration.ClientGeneratorOutputType.Implementation);
            var models  = generator.GenerateFile(NSwag.CodeGeneration.ClientGeneratorOutputType.Contracts);

            var clientsPath = Path.Combine(destinationPath, "Clients.cs");
            var modelsPath  = Path.Combine(destinationPath, "Models.cs");

            File.WriteAllText(clientsPath, clients);
            File.WriteAllText(modelsPath, models);

            var clientsTree = CSharpSyntaxTree.ParseText(clients).WithFilePath(clientsPath);
            var modelsTree  = CSharpSyntaxTree.ParseText(models).WithFilePath(modelsPath);

            var compilation = CreateCompilation(clientsTree, modelsTree);

            var rewriter  = new ModelReferenceRewriter(compilation.GetSemanticModel(modelsTree));
            var newSource = rewriter.Visit(modelsTree.GetRoot());

            if (newSource != modelsTree.GetRoot())
            {
                File.WriteAllText(modelsTree.FilePath, newSource.ToFullString());
            }
            //unit.De.DescendantNodes<NamespaceSyntax
        }
        private static IApplicationBuilder MapClient(
            this IApplicationBuilder app,
            SwaggerDocumentationOptions options,
            string language,
            Func <SwaggerDocumentationOptions, string, OpenApiDocument, string> generateCode)
        => app.Map(new PathString($"/clients/{language}"), apiClients =>
        {
            var apiVersions = GetApiVersions(options);

            foreach (var description in apiVersions)
            {
                apiClients.Map(new PathString($"/{description}"), apiClient => apiClient.Run(async context =>
                {
                    var baseUrl  = $"{context.Request.Scheme}://{context.Request.Host}";
                    var document = await OpenApiDocument.FromUrlAsync($"{baseUrl}/docs/{description}/docs.json");

                    await context.Response.WriteAsync(generateCode(options, description, document));
                }));
            }
        });
Ejemplo n.º 27
0
 protected async Task <OpenApiDocument> 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 OpenApiYamlDocument.FromUrlAsync(input).ConfigureAwait(false));
             }
             else
             {
                 return(await OpenApiDocument.FromUrlAsync(input).ConfigureAwait(false));
             }
         }
         else
         {
             if (input.EndsWith(".yaml", StringComparison.OrdinalIgnoreCase) ||
                 input.EndsWith(".yml", StringComparison.OrdinalIgnoreCase))
             {
                 return(await OpenApiYamlDocument.FromFileAsync(input).ConfigureAwait(false));
             }
             else
             {
                 return(await OpenApiDocument.FromFileAsync(input).ConfigureAwait(false));
             }
         }
     }
     else
     {
         if (IsYaml(input))
         {
             return(await OpenApiYamlDocument.FromYamlAsync(input).ConfigureAwait(false));
         }
         else
         {
             return(await OpenApiDocument.FromJsonAsync(input).ConfigureAwait(false));
         }
     }
 }
Ejemplo n.º 28
0
        private static async Task <OpenApiDocument> CreateOpenApiDocumentAsync(CancellationToken cancellationToken = default)
        {
            OpenApiDocument document;
            var             swaggerJsonAddress = UrsaApplication.PackingParameters.SwaggerJsonAddress;

            if (Uri.TryCreate(swaggerJsonAddress, UriKind.Absolute, out var uri) &&
                (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps))
            {
                document = await OpenApiDocument.FromUrlAsync(swaggerJsonAddress);
            }
            else if (File.Exists(swaggerJsonAddress))
            {
                document = await OpenApiDocument.FromFileAsync(swaggerJsonAddress);
            }
            else
            {
                throw new FileNotFoundException("file could not be found", swaggerJsonAddress);
            }

            return(document);
        }
Ejemplo n.º 29
0
        public static void Main()
        {
            var document = OpenApiDocument.FromUrlAsync("http://*****:*****@"..\..\..\..\Squidex.ClientLibrary\Management\Generated.cs", code);
        }
Ejemplo n.º 30
0
        static async Task Main(string[] args)
        {
            // Start up the server mode to make the swagger.json file available.
            var portNumber    = 5678;
            var serverCommand = new ServerModeCommand(new ConsoleInteractiveServiceImpl(), portNumber, null, true);
            var cancelSource  = new CancellationTokenSource();

            _ = serverCommand.ExecuteAsync(cancelSource.Token);
            try
            {
                // Wait till server mode is started.
                await Task.Delay(3000);

                // Grab the swagger.json from the running instances of server mode
                var document = await OpenApiDocument.FromUrlAsync($"http://localhost:{portNumber}/swagger/v1/swagger.json");

                var settings = new CSharpClientGeneratorSettings
                {
                    ClassName = "RestAPIClient",
                    GenerateClientInterfaces = true,
                    CSharpGeneratorSettings  =
                    {
                        Namespace = "AWS.Deploy.ServerMode.Client",
                    },
                    HttpClientType = "ServerModeHttpClient"
                };

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

                // Save the generated client to the AWS.Deploy.ServerMode.Client project
                var fullPath = DetermineFullFilePath("RestAPI.cs");
                File.WriteAllText(fullPath, code);
            }
            finally
            {
                // terminate running server mode.
                cancelSource.Cancel();
            }
        }