Example #1
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="specification"></param>
        /// <returns></returns>
        public NSwagRunner FromJsonSpecification(FilePath specification)
        {
            string          path     = Context.MakeAbsolute(specification).FullPath;
            OpenApiDocument document = OpenApiDocument.FromFileAsync(path).Result;

            return(new NSwagRunner(Context, document));
        }
        public async Task When_file_contains_path_reference_to_another_file_it_is_loaded()
        {
            var document = await OpenApiDocument.FromFileAsync("TestFiles/path-reference.json");

            Assert.NotNull(document);
            Assert.Equal("External path", document.Paths.First().Value.ActualPathItem.Values.First().Description);
        }
        public async Task When_file_contains_schema_reference_to_another_file_it_is_loaded()
        {
            var document = await OpenApiDocument.FromFileAsync("TestFiles/schema-reference.json");

            Assert.NotNull(document);
            Assert.Equal("External object", document.Paths.First().Value.Values.First().Responses.First().Value.Content.First().Value.Schema.ActualSchema.Description);
        }
        public async Task When_file_contains_parameter_reference_to_another_file_it_is_loaded()
        {
            var document = await OpenApiDocument.FromFileAsync("TestFiles/parameter-reference.json");

            Assert.NotNull(document);
            Assert.Equal(2, document.Paths.First().Value.Values.First().Parameters.Count);
            Assert.Equal("offset", document.Paths.First().Value.Values.First().Parameters.First().ActualParameter.Name);
        }
Example #5
0
        static async Task CompileFile(string input, string output, TypeScriptClientGeneratorSettings settings)
        {
            var doc = await OpenApiDocument.FromFileAsync(input);

            var generator = new TypeScriptClientGenerator(doc, settings);

            await File.WriteAllTextAsync(output, generator.GenerateFile());
        }
 private void ArrangeOpenApiDocumentFactory(
     IOpenApiDocumentFactory factory,
     string swaggerFile = null)
 {
     Mock.Get(factory)
     .Setup(
         c => c.GetDocumentAsync(
             It.IsAny <string>()))
     .Returns(OpenApiDocument.FromFileAsync(swaggerFile ?? SwaggerJsonFilename));
 }
 public OpenApiDocument GetDocument(string swaggerFile)
 {
     return(swaggerFile.EndsWith("yaml") || swaggerFile.EndsWith("yml")
         ? OpenApiYamlDocument.FromFileAsync(swaggerFile)
            .GetAwaiter()
            .GetResult()
         : OpenApiDocument.FromFileAsync(swaggerFile)
            .GetAwaiter()
            .GetResult());
 }
Example #8
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);
        }
Example #9
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);
 }
Example #10
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);
     }
 }
Example #11
0
        public async Task PathItem_With_External_Ref_Can_Be_Serialized()
        {
            string path = GetTestDirectory() + "/Serialization/PathItemTest/PathItemWithRef.json";

            OpenApiDocument doc = await OpenApiDocument.FromFileAsync(path);

            var paths          = doc.Paths;
            var pathItem       = paths[aValidPath];
            var actualPathItem = pathItem.ActualPathItem;
            var getOperation   = actualPathItem["get"];

            Assert.True(getOperation.ActualResponses.ContainsKey("200"));
        }
 public OpenApiDocument GetDocument(string swaggerFile)
 {
     try
     {
         return(ThreadHelper.JoinableTaskFactory
                ?.Run(() => OpenApiDocument.FromFileAsync(swaggerFile)));
     }
     catch (NullReferenceException)
     {
         return(OpenApiDocument
                .FromFileAsync(swaggerFile)
                .GetAwaiter()
                .GetResult());
     }
 }
Example #13
0
        public NSwagCSharpCodeGeneratorTests()
        {
            document = OpenApiDocument.FromFileAsync("Swagger.json").GetAwaiter().GetResult();
            documentFactoryMock.Setup(c => c.GetDocument("Swagger.json"))
            .Returns(document);

            settingsMock.Setup(c => c.GetGeneratorSettings(It.IsAny <OpenApiDocument>()))
            .Returns(new CSharpClientGeneratorSettings());

            var sut = new NSwagCSharpCodeGenerator(
                "Swagger.json",
                documentFactoryMock.Object,
                settingsMock.Object);

            code = sut.GenerateCode(progressMock.Object);
        }
 public async Task <OpenApiDocument> GetDocumentAsync(string swaggerFile)
 {
     try
     {
         return(await ThreadHelper.JoinableTaskFactory.RunAsync(
                    () => swaggerFile.EndsWith("yaml") || swaggerFile.EndsWith("yml")
                    ?OpenApiYamlDocument.FromFileAsync(swaggerFile)
                    : OpenApiDocument.FromFileAsync(swaggerFile)));
     }
     catch (NullReferenceException)
     {
         return(await(swaggerFile.EndsWith("yaml") || swaggerFile.EndsWith("yml")
                 ? OpenApiYamlDocument.FromFileAsync(swaggerFile)
                 : OpenApiDocument.FromFileAsync(swaggerFile)));
     }
 }
Example #15
0
        protected override async Task OnInitializeAsync()
        {
            document = await OpenApiDocument.FromFileAsync(SwaggerJsonFilename);

            documentFactoryMock.Setup(c => c.GetDocumentAsync(SwaggerJsonFilename))
            .ReturnsAsync(document);

            settingsMock.Setup(c => c.GetGeneratorSettings(It.IsAny <OpenApiDocument>()))
            .Returns(new CSharpClientGeneratorSettings());

            var sut = new NSwagCSharpCodeGenerator(
                SwaggerJsonFilename,
                documentFactoryMock.Object,
                settingsMock.Object);

            code = sut.GenerateCode(progressMock.Object);
        }
 public OpenApiDocument GetDocument(string swaggerFile)
 {
     try
     {
         return(ThreadHelper.JoinableTaskFactory?.Run(
                    () => swaggerFile.EndsWith("yaml") || swaggerFile.EndsWith("yml")
                 ? OpenApiYamlDocument.FromFileAsync(swaggerFile)
                 : OpenApiDocument.FromFileAsync(swaggerFile)));
     }
     catch (NullReferenceException)
     {
         return((swaggerFile.EndsWith("yaml") || swaggerFile.EndsWith("yml")
                 ? OpenApiYamlDocument.FromFileAsync(swaggerFile)
                 : OpenApiDocument.FromFileAsync(swaggerFile))
                .GetAwaiter()
                .GetResult());
     }
 }
Example #17
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));
         }
     }
 }
Example #18
0
        private static async Task GeneratePaymentsApi(string inputFile, string outputFile)
        {
            CheckFileExists(inputFile);

            var document = await OpenApiDocument.FromFileAsync(inputFile);

            var settings = new CSharpClientGeneratorSettings
            {
                ClassName = PaymentsApi,
                CSharpGeneratorSettings =
                {
                    Namespace = $"CoffeeCard.MobilePay.Generated.Api.{PaymentsApi}"
                },
                UseBaseUrl = false
            };

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

            await File.WriteAllTextAsync(outputFile, code);
        }
Example #19
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);
        }
Example #20
0
        public static async Task Main(string[] args)
        {
            var projectFolder = Path.GetFullPath(@"..\..\..\");
            // TODO fix path
            //var document = {./swaggerServer.json};
            var document = OpenApiDocument.FromFileAsync("./swaggerServer.json").Result;

            // var document = OpenApiDocument.FromUrlAsync("https://localhost:5001/swagger/v1/swagger.json").Result;

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

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

            // TODO fix path
            await File.WriteAllTextAsync("./client.generated.ts", code);

            // await File.WriteAllTextAsync(Path.Combine(projectFolder, "/Users/dieterbalis/Documents/App42/Server/app42.server/Pencil42App.TypescriptGenerator/client.generated.ts"), code);
            // await File.WriteAllTextAsync(Path.Combine(projectFolder, "/Users/jokeclaeys/Documents/App42/app42.server/Pencil42App.TypescriptGenerator/client.generated.ts"), code);
        }
Example #21
0
 internal static async Task <OpenApiDocument> ReadSwaggerDocumentAsync(this string input)
 {
     if (!input.IsJson() && !input.IsYaml())
     {
         if (input.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || input.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
         {
             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
     {
         return(input.IsYaml()
             ? await OpenApiYamlDocument.FromYamlAsync(input).ConfigureAwait(false)
             : await OpenApiDocument.FromJsonAsync(input).ConfigureAwait(false));
     }
 }
Example #22
0
        static async Task <int> Main(string[] args)
        {
            IConfiguration config = new ConfigurationBuilder()
                                    .AddCommandLine(args, CommandLineKeyMappingDictionary)
                                    .Build();

            var documentPath = config.GetValue <string>(DocumentKey);
            var outputPath   = config.GetValue <string>(OutputKey);

            if (string.IsNullOrWhiteSpace(documentPath) ||
                string.IsNullOrWhiteSpace(outputPath))
            {
                Console.WriteLine("Requested command line parameters must be set.");
                Console.WriteLine("-d input swagger.json document");
                Console.WriteLine("-o output client file");

                return(1);
            }

            try
            {
                ////TODO create OpenAPI doc here
                //var settingsOpenApi = new WebApiOpenApiDocumentGeneratorSettings
                //{
                //    //DefaultUrlTemplate = "api/{controller}/{action}/{id}"
                //};

                //Assembly.lo

                //var generator = new WebApiOpenApiDocumentGenerator(settingsOpenApi);
                //var document = await generator.GenerateForControllersAsync() .GenerateForControllerAsync<PersonsController>();
                //var swaggerSpecification = document.ToJson();


                var settings = new CSharpClientGeneratorSettings
                {
                    CSharpGeneratorSettings =
                    {
                        Namespace = "Orange.ApiTokenValidation.Client"
                    },
                    GenerateExceptionClasses = true,
                    GenerateClientInterfaces = true,
                    InjectHttpClient         = true,
                    DisposeHttpClient        = false,
                    GenerateDtoTypes         = true,
                };

                var document = await OpenApiDocument.FromFileAsync(documentPath);

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

                await File.WriteAllTextAsync(outputPath, code);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Generation client error: {Environment.NewLine}{ex}");
                return(-1);
            }

            Console.WriteLine("Client was generated");

            return(0);
        }
Example #23
0
 public async Task Can_GenerateClassName_From_FileName()
 => (await OpenApiDocument.FromFileAsync(SwaggerJsonFilename))
 .GenerateClassName(false)
 .Should()
 .Be(SwaggerJsonFilename.Replace(".json", string.Empty));
 public OpenApiDocument GetDocument(string swaggerFile)
 {
     return(OpenApiDocument.FromFileAsync(swaggerFile)
            .GetAwaiter()
            .GetResult());
 }
 public Task <OpenApiDocument> GetDocumentAsync(string swaggerFile)
 {
     return(swaggerFile.EndsWith("yaml") || swaggerFile.EndsWith("yml")
         ? OpenApiYamlDocument.FromFileAsync(swaggerFile)
         : OpenApiDocument.FromFileAsync(swaggerFile));
 }
Example #26
0
 public async Task <OpenApiDocument> FromPathAsync(string swaggerPath)
 {
     return(await OpenApiDocument.FromFileAsync(swaggerPath));
 }
Example #27
0
 public async Task Can_GenerateClassName_From_FileName()
 => (await OpenApiDocument.FromFileAsync("Swagger.json"))
 .GenerateClassName(false)
 .Should()
 .Be("Swagger");