Ejemplo n.º 1
0
        public async Task When_swagger_reponse_contains_plain_text_then_Convert_is_generated()
        {
            // Arrange
            var swagger  = @"{
  ""swagger"" : ""2.0"",
  ""paths"" : {
    ""/instances/text"": {
      ""get"": {
        ""description"": ""sample"",
        ""operationId"": ""plain"",
        ""produces"": [ ""text/plain"" ],
        ""responses"": {
          ""200"": {
            ""description"": ""plain string return"",
            ""schema"": {
                ""type"": ""string"",
              }
          }
        }
      }
    }
  }
}";
            var document = await OpenApiDocument.FromJsonAsync(swagger);

            // Act
            var codeGenerator = new CSharpClientGenerator(document, new CSharpClientGeneratorSettings
            {
                GenerateClientInterfaces = true
            });
            var code = codeGenerator.GenerateFile();

            // Assert
            Assert.Contains("public async System.Threading.Tasks.Task<string> PlainAsync(", code);
        }
Ejemplo n.º 2
0
        static async Task Main(string[] args)
        {
            System.Net.WebClient wclient = new System.Net.WebClient();

            var document = await OpenApiDocument.FromJsonAsync(wclient.DownloadString("https://app.amphoradata.com/swagger/v1/swagger.json"));

            wclient.Dispose();

            var settings = new CSharpClientGeneratorSettings
            {
                //ClassName = "AmphoraClient",
                CSharpGeneratorSettings =
                {
                    Namespace = "AmphoraData.Client",
                }
            };

            var generator = new CSharpClientGenerator(document, settings);
            var code      = generator.GenerateFile();
            var directory = System.IO.Directory.GetCurrentDirectory();
            var filePath  = $"{directory}/client/AmphoraClient.cs";

            System.IO.File.Delete(filePath);
            Console.WriteLine($"Deleted {filePath}");
            System.IO.File.WriteAllText(filePath, code);
            Console.WriteLine($"Wrote {filePath}");
        }
        private async Task <OpenApiDocument> CreateDocumentAsync()
        {
            var document = !string.IsNullOrEmpty(Settings.DocumentTemplate) ?
                           await OpenApiDocument.FromJsonAsync(Settings.DocumentTemplate).ConfigureAwait(false) :
                           new OpenApiDocument();

            document.Generator  = $"NSwag v{OpenApiDocument.ToolchainVersion} (NJsonSchema v{JsonSchema.ToolchainVersion})";
            document.SchemaType = Settings.SchemaType;

            if (document.Info == null)
            {
                document.Info = new OpenApiInfo();
            }

            if (string.IsNullOrEmpty(Settings.DocumentTemplate))
            {
                if (!string.IsNullOrEmpty(Settings.Title))
                {
                    document.Info.Title = Settings.Title;
                }

                if (!string.IsNullOrEmpty(Settings.Description))
                {
                    document.Info.Description = Settings.Description;
                }

                if (!string.IsNullOrEmpty(Settings.Version))
                {
                    document.Info.Version = Settings.Version;
                }
            }

            return(document);
        }
Ejemplo n.º 4
0
        public async Task When_request_body_is_changed_then_body_parameter_Content_is_updated()
        {
            //// Arrange
            var document = CreateDocument();

            //// Act
            var json = document.ToJson(SchemaType.OpenApi3);

            document = await OpenApiDocument.FromJsonAsync(json);

            var requestBody = document.Paths["/baz"][OpenApiOperationMethod.Get].RequestBody;

            requestBody.Content["application/json"] = new OpenApiMediaType
            {
                Schema = new JsonSchema {
                    Title = "blub"
                }
            };

            //// Assert
            var parameter = document.Paths["/baz"][OpenApiOperationMethod.Get].Parameters
                            .Single(p => p.Kind == OpenApiParameterKind.Body);

            Assert.Equal("blub", parameter.Schema.Title);
        }
Ejemplo n.º 5
0
        public static async void GenerateCodeInterfaceAndService(CSharpClientGeneratorSettings settings, string serviceName)
        {
            System.Net.WebClient wclient = new System.Net.WebClient();

            string url = @"https://cloud.squidex.io/api/content/ilearn/swagger/v1/swagger.json";

            var document = await OpenApiDocument.FromJsonAsync(wclient.DownloadString(url));

            wclient.Dispose();

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

            int indexSplitInterfaceAndApp = IndexOfOccurence(allCode, "[System.CodeDom.Compiler.GeneratedCode(\"NSwag\", \"13.10.1.0 (NJsonSchema v10.3.3.0 (Newtonsoft.Json v12.0.0.0))\")]", 2);
            int indexSplitDto             = IndexOfOccurence(allCode, "[System.CodeDom.Compiler.GeneratedCode(\"NJsonSchema\"", 1);

            string nameSpace = "namespace ContentManagement.Content {\n";

            //Interface Service
            string interfaceCode = allCode.Remove(indexSplitInterfaceAndApp) + "}";

            File.WriteAllText(baseLocation + "I" + serviceName, interfaceCode);

            //ServiceCode
            int    length      = indexSplitDto - indexSplitInterfaceAndApp;
            string serviceCode = nameSpace + allCode.Substring(indexSplitInterfaceAndApp, length) + "}";

            File.WriteAllText(baseLocation + serviceName, serviceCode);

            string dtoCode = nameSpace + allCode.Substring(indexSplitDto);

            File.WriteAllText(baseLocation + "Dto" + serviceName, dtoCode);
        }
Ejemplo n.º 6
0
        public OpenApiDocument GetOpenApiDocument()
        {
            Log.Information("Fetching OpenApi information");

            string openApiDocText = null;

            using (var webClient = new System.Net.WebClient())
            {
                try
                {
                    openApiDocText = webClient.DownloadString(_settings.OpenApiUri);
                    var doc = OpenApiDocument.FromJsonAsync(openApiDocText).Result;
                    if (!string.IsNullOrEmpty(_settings.ConfigurationFile))
                    {
                        SaveOfflineVersionOfOpenApi(_settings, _fileSystem, openApiDocText);
                    }

                    return(doc);
                }
                catch (WebException)
                {
                    var fallbackDoc = LoadCachedOpenApiDoc(_settings, _fileSystem);
                    return(fallbackDoc);
                }
            }
        }
Ejemplo n.º 7
0
 public async Task Can_GenerateClassName_From_Json_Using_DocumentTitle()
 {
     (await OpenApiDocument.FromJsonAsync(swaggerJson))
     .GenerateClassName()
     .Should()
     .Be("PetstoreClient");
 }
Ejemplo n.º 8
0
        public async Task When_generating_csharp_with_any_inheritance_then_inheritance_is_generated()
        {
            // Arrange
            var json     = @"{
    ""openapi"": ""3.0.0"",
    ""components"": {
        ""schemas"": {
            ""SessionStateResent"": {
                ""allOf"": [
                    {
                        ""$ref"": ""#/components/schemas/SportsbookEventBody""
                    },
                    {
                        ""type"": ""object"",
                        ""additionalProperties"": false
                    }
                ]
            },
            ""SportsbookEventBody"": {
                ""type"": ""object"",
                ""additionalProperties"": false
            }
        }
    }
}";
            var document = await OpenApiDocument.FromJsonAsync(json);

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

            // Assert
            Assert.Contains("class SessionStateResent : SportsbookEventBody", code);
        }
Ejemplo n.º 9
0
        public async Task When_openapi3_contains_octet_stream_response_then_FileResponse_is_generated()
        {
            // Arrange
            var json     = @"{
  ""x-generator"": ""NSwag v13.0.6.0 (NJsonSchema v10.0.23.0 (Newtonsoft.Json v12.0.0.0))"",
  ""openapi"": ""3.0.0"",
  ""info"": {
    ""title"": ""Apiverse API"",
    ""version"": ""1.0.0""
  },
  ""paths"": {
    ""/api/endpoints/{endpointId}/environments/{environmentId}/documents/openapi/compare"": {
      ""post"": {
        ""tags"": [
          ""Endpoints""
        ],
        ""summary"": ""Compares a new document against an existing document."",
        ""operationId"": ""Endpoints_CompareOpenApiDocument"",
        ""parameters"": [],
        ""requestBody"": {
          ""content"": {
            ""application/json"": {
              ""schema"": {
                ""type"": ""file""
              }
            }
          }
        },
        ""responses"": {
          ""200"": {
            ""description"": ""The comparison result."",
            ""content"": {
              ""application/json"": {
                ""schema"": {
                  ""type"": ""string""
                }
              }
            }
          }
        }
      }
    }
  },
  ""components"": {
    ""schemas"": { }
  }
}";
            var document = await OpenApiDocument.FromJsonAsync(json, null, SchemaType.OpenApi3, null);

            //// Act
            var codeGenerator = new CSharpClientGenerator(document, new CSharpClientGeneratorSettings
            {
                GenerateClientInterfaces = true
            });
            var code = codeGenerator.GenerateFile();

            //// Assert
            Assert.Contains("var content_ = new System.Net.Http.StreamContent(body);", code);
        }
Ejemplo n.º 10
0
        public async Task OpenApiDocumentCanBeLoadedFromJsonFile()
        {
            string result = LoadResourceData("DrawIoDotNetPluginsTest.examples.test.json");

            OpenApiDocument document = await OpenApiDocument.FromJsonAsync(result);

            Assert.AreEqual(6, document.Definitions.Count);
        }
Ejemplo n.º 11
0
        public async Task When_same_response_is_referenced_multiple_times_in_operation_then_class_is_generated()
        {
            // Arrange
            string json = @"{
  ""openapi"": ""3.0.0"",
  ""paths"": {
    ""/v1/exceptions/get"": {
      ""get"": {
        ""operationId"": ""Exceptions_GetException"",
        ""responses"": {
          ""200"": {
            ""$ref"": ""#/components/responses/BusinessExceptionResponse"",
            },
          ""400"": {
            ""$ref"": ""#/components/responses/BusinessExceptionResponse"",
          }
        }
      }
    }
  },
  ""components"": {
    ""schemas"": {
      ""BusinessException"": {
        ""type"": ""object"",
        ""additionalProperties"": false
      }
    },
    ""responses"": {
      ""BusinessExceptionResponse"": {
        ""description"": ""List of NSwagStudio bugs"",
        ""content"": {
          ""application/json"": {
            ""schema"": {
              ""type"": ""array"",
              ""items"": {
                ""$ref"": ""#/components/schemas/BusinessException""
              }
            }
          }
        }
      }
    }
  }
}";

            var document = await OpenApiDocument.FromJsonAsync(json);

            // Act
            var settings = new CSharpClientGeneratorSettings {
                ClassName = "MyClass"
            };
            var generator = new CSharpClientGenerator(document, settings);
            var code      = generator.GenerateFile();

            // Assert
            Assert.Contains("System.Threading.Tasks.Task<System.Collections.Generic.ICollection<BusinessException>>", code);
            Assert.Contains("class BusinessException", code);
        }
Ejemplo n.º 12
0
        public async Task Can_GenerateClassName_From_Json_Without_DocumentTitle()
        {
            var sut = await OpenApiDocument.FromJsonAsync(swaggerJson);

            sut.Info.Title = null;
            sut.GenerateClassName()
            .Should()
            .Be("ApiClient");
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Create the openapi document file, based on the input.
        /// </summary>
        /// <returns></returns>
        public static async Task <OpenApiDocument> GetOpenApiDoc()
        {
            var fileTxt = GetFileTxt();

            if (JsonOrYaml)
            {
                return(await OpenApiDocument.FromJsonAsync(fileTxt));
            }
            return(await OpenApiYamlDocument.FromYamlAsync(fileTxt));
        }
Ejemplo n.º 14
0
        public async Task When_json_has_extension_data_then_it_is_loaded()
        {
            //// Arrange
            var json = _jsonVendorExtensionData;

            //// Act
            var document = await OpenApiDocument.FromJsonAsync(json);

            //// Assert
            Assert.NotNull(document.Operations.First().Operation.ActualResponses["202"].ExtensionData);
        }
Ejemplo n.º 15
0
        public async Task When_parameter_references_schema_then_it_is_resolved()
        {
            //// Arrange
            var json = @"{
  ""openapi"": ""3.0.0"",
  ""servers"": [
    {
      ""url"": ""/api/v2"",
      ""description"": ""server""
    }
  ],
  ""paths"": {
    ""/subscriptions/{subscriptionId}"": {
      ""get"": {
        ""tags"": [
          ""subscriptions""
        ],
        ""summary"": ""get subscription details"",
        ""operationId"": ""subscriptions_details"",
        ""responses"": {
          
        }
      },
      ""parameters"": [
        {
          ""name"": ""subscriptionId"",
          ""in"": ""path"",
          ""required"": true,
          ""schema"": {
            ""$ref"": ""#/components/schemas/EntityId""
          }
        }
      ]
    }
  },
  ""components"": {
    ""schemas"": {
      ""EntityId"": {
        ""format"": ""secret"",
        ""type"": ""string"",
        ""example"": ""851D64D0-86DF-4BEC-8BA0-C81E326D735A""
      }
    }
  }
}";

            //// Act
            var document = await OpenApiDocument.FromJsonAsync(json);

            json = document.ToJson();

            //// Assert
            Assert.Equal("secret", document.Operations.First().Operation.ActualParameters.First().ActualSchema.Format);
        }
Ejemplo n.º 16
0
        public async Task When_document_has_null_schema_definition_then_it_is_ignored()
        {
            //// Arrange
            var json = @"{ ""definitions"": { ""definitions"": null } }";

            //// Act
            var document = await OpenApiDocument.FromJsonAsync(json);

            //// Assert
            Assert.True(document.Definitions.Count == 0);
        }
Ejemplo n.º 17
0
        public async Task When_generating_operation_ids_then_missing_ids_are_generated()
        {
            //// Arrange
            var json = _sampleServiceCode;

            //// Act
            var document = await OpenApiDocument.FromJsonAsync(json);

            document.GenerateOperationIds();

            //// Assert
            Assert.Equal("pets", document.Operations.First().Operation.OperationId);
        }
Ejemplo n.º 18
0
        public async Task OpenApiDocumentCanCreateXmlDiagram()
        {
            string result           = LoadResourceData("DrawIoDotNetPluginsTest.examples.test.json");
            string targetXmlDiagram = LoadResourceData("DrawIoDotNetPluginsTest.examples.targetXml.txt");

            OpenApiDocument document = await OpenApiDocument.FromJsonAsync(result);

            OpenApiDiagramBuilder builder = new OpenApiDiagramBuilder(document, new DiagramXmlBuilder("111"));

            var xmlDiagram = builder.BuildDiagram();

            Assert.AreEqual(targetXmlDiagram, xmlDiagram);
        }
Ejemplo n.º 19
0
        public override async Task <object> RunAsync(CommandLineProcessor processor, IConsoleHost host)
        {
            JsonReferenceResolver ReferenceResolverFactory(OpenApiDocument d) =>
            new JsonAndYamlReferenceResolver(new JsonSchemaResolver(d, Settings));

            var documentJson = await RunIsolatedAsync((string)null);

            var document = await OpenApiDocument.FromJsonAsync(documentJson, null, OutputType, ReferenceResolverFactory).ConfigureAwait(false);

            await this.TryWriteDocumentOutputAsync(host, NewLineBehavior, () => document).ConfigureAwait(false);

            return(document);
        }
Ejemplo n.º 20
0
        public async Task When_custom_BasePath_is_not_specified_then_the_BasePath_from_document_is_used_as_Route()
        {
            //// Arrange
            var document = await OpenApiDocument.FromJsonAsync(_swagger);

            //// Act
            var settings  = new CSharpControllerGeneratorSettings();
            var generator = new CSharpControllerGenerator(document, settings);
            var code      = generator.GenerateFile();

            //// Assert
            Assert.Contains("Route(\"virtual_directory/v1\")]", code);
        }
Ejemplo n.º 21
0
        private static int GenerateCSharpClient(GenerateClientOptions options)
        {
            try
            {
                var swaggerJson = GetSwaggerJson();
#pragma warning disable S4462
                var document = OpenApiDocument.FromJsonAsync(swaggerJson).Result;
#pragma warning restore S4462

                var filePath = options.CsFilePath.GetRootedPath();
                Console.WriteLine($"Start generate client code with nswag. OutputPath: {filePath}");

                var settings = new CSharpClientGeneratorSettings
                {
                    GenerateClientInterfaces    = true,
                    OperationNameGenerator      = new SingleClientFromOperationIdOperationNameGenerator(),
                    ExceptionClass              = "MetadataIntegrationServiceClientException",
                    UseHttpClientCreationMethod = true,
                    InjectHttpClient            = true,
                    ClassName = "MetadataIntegrationServiceClient",
                    GenerateBaseUrlProperty = false,
                    UseBaseUrl      = false,
                    ClientBaseClass = "ClientBaseClass",
                    UseHttpRequestMessageCreationMethod        = true,
                    GenerateUpdateJsonSerializerSettingsMethod = true,
                    CSharpGeneratorSettings =
                    {
                        Namespace           = "SimairaDigital.Backend.ItemManagement.Client",
                        InlineNamedTuples   = true,
                        GenerateJsonMethods = true,
                    },
                };

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

                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                }

                File.WriteAllText(filePath, code);
                return(0);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return(-1);
            }
        }
Ejemplo n.º 22
0
        public async Task OnLoadFile(string content)
        {
            try
            {
                var openApiDocument = await OpenApiDocument.FromJsonAsync(content);

                var openApiDiagramBuilder = new OpenApiDiagramBuilder(openApiDocument, new DiagramXmlBuilder());
                await _jsContract.LoadXml(openApiDiagramBuilder.BuildDiagram());
            }
            catch (Exception ex)
            {
                await _jsContract.ShowError(ex.Message);
            }
        }
Ejemplo n.º 23
0
        public static async void GenerateCode(CSharpClientGeneratorSettings settings, string serviceName)
        {
            System.Net.WebClient wclient = new System.Net.WebClient();

            string url = @"https://cloud.squidex.io/api/content/ilearn/swagger/v1/swagger.json";

            var document = await OpenApiDocument.FromJsonAsync(wclient.DownloadString(url));

            wclient.Dispose();

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

            File.WriteAllText(baseLocation + serviceName, allCode);
        }
Ejemplo n.º 24
0
        public async Task When_request_body_is_added_then_serialized_correctly_in_OpenApi()
        {
            //// Arrange
            var document = CreateDocument();

            //// Act
            var json = document.ToJson(SchemaType.OpenApi3);

            document = await OpenApiDocument.FromJsonAsync(json);

            //// Assert
            var requestBody = document.Paths["/baz"][OpenApiOperationMethod.Get].RequestBody;

            Assert.Equal("foo", requestBody.Name);
        }
Ejemplo n.º 25
0
        private OpenApiDocument LoadCachedOpenApiDoc(Settings settings, IFileSystem fileSystem)
        {
            if (!string.IsNullOrEmpty(settings.ConfigurationFile))
            {
                var openApiCacheFile = GetOpenApiCacheFileName(settings);
                if (fileSystem.File.Exists(openApiCacheFile))
                {
                    var fileContents = fileSystem.File.ReadAllText(openApiCacheFile);
                    var doc          = OpenApiDocument.FromJsonAsync(fileContents).Result;
                    return(doc);
                }
            }

            Log.Error("Your app seems to be off-line - the OpenApi spec could not be retried from {OpenApiUri}, and no cached copy of the OpenApi specification for your app could be found.", settings.OpenApiUri);
            return(null);
        }
Ejemplo n.º 26
0
        public async Task When_response_is_referenced_any_then_class_is_generated()
        {
            // Arrange
            var json     = @"{
  ""openapi"": ""3.0.0"",
  ""paths"": {
    ""/v1/exceptions/get"": {
      ""post"": {
        ""operationId"": ""Exceptions_GetException"",
        ""responses"": {
          ""200"": {
            ""content"": {
              ""application/json"": {
                ""schema"": {
                  ""$ref"": ""#/components/schemas/BusinessException""
                }
              }
            }
          }
        }
      }
    }
  }, 
  ""components"": {
    ""schemas"": {
      ""BusinessException"": {
        ""type"": ""object"",
        ""additionalProperties"": false
      }
    }
  }
}";
            var document = await OpenApiDocument.FromJsonAsync(json);

            // Act
            var settings = new CSharpClientGeneratorSettings {
                ClassName = "MyClass"
            };
            var generator = new CSharpClientGenerator(document, settings);
            var code      = generator.GenerateFile();

            // Assert
            Assert.Contains("System.Threading.Tasks.Task<BusinessException>", code);
            Assert.DoesNotContain("System.Threading.Tasks.Task<object>", code);
            Assert.Contains("class BusinessException", code);
        }
Ejemplo n.º 27
0
        public async Task When_specific_StatusCodeResult_then_renders_correctly()
        {
            // Arrange
            var executor = TestApiOperationExecutor.CreateHttp(o => o
                                                               .WithOperation <CreatedStatusCodeQuery>()
                                                               .AddOpenApi());

            // Act
            var result = await executor.ExecuteAsync <OpenApiQuery>();

            // Assert
            var plaintextResult = result.ShouldBeOperationResultType <PlainTextResult>();
            var openApiDocument = await OpenApiDocument.FromJsonAsync(plaintextResult.Content);

            openApiDocument.Paths.Should().NotBeEmpty();
            await Verifier.Verify(plaintextResult);
        }
Ejemplo n.º 28
0
        public async Task When_openapi3_has_nullable_schema_then_it_is_read_correctly()
        {
            var json = @"{
  ""openapi"": ""3.0.0"",
  ""info"": {
    ""title"": ""Swagger Petstore"",
    ""license"": {
      ""name"": ""MIT""
    },
    ""version"": ""1.0.0""
  },
  ""servers"": [
    {
      ""url"": ""http://petstore.swagger.io/v1""
    }
  ],
  ""paths"": { },
  ""components"": {
    ""schemas"": {
      ""PurchaseReadDto2"": {
        ""type"": ""object"",
        ""nullable"": true,
        ""additionalProperties"": false,
        ""properties"": {
          ""participantsParts"": {
            ""type"": ""object"",
            ""nullable"": true,
            ""additionalProperties"": {
              ""type"": ""number"",
              ""format"": ""decimal"",
              ""nullable"": true
            }
          }
        }
      }
    }
  }
}";
            // Act
            var document = await OpenApiDocument.FromJsonAsync(json);

            // Assert
            Assert.True(document.Components.Schemas["PurchaseReadDto2"].IsNullableRaw);
            Assert.True(document.Components.Schemas["PurchaseReadDto2"].Properties["participantsParts"].IsNullableRaw);
            Assert.True(document.Components.Schemas["PurchaseReadDto2"].Properties["participantsParts"].AdditionalPropertiesSchema.IsNullableRaw);
        }
Ejemplo n.º 29
0
        public async Task Generate()
        {
            var rig = await new SwaggerIntegration().Start();

            try
            {
                //System.Threading.Thread.Sleep(10000);
                var response = await rig.HttpTestClient.GetAsync("/swagger/v1/swagger.json");

                response.EnsureSuccessStatusCode();
                var responseString = await response.Content.ReadAsStringAsync();

                var document = await OpenApiDocument.FromJsonAsync(responseString);

                var settings = new CSharpClientGeneratorSettings
                {
                    ClassName = "{controller}Api",
                    AdditionalContractNamespaceUsages = new string[] { "" },
                    AdditionalNamespaceUsages         = new string[] { "Echo.Ecommerce.Host.Controllers", "Echo.Ecommerce.Host.Models", "Microsoft.AspNetCore.Mvc.ModelBinding", "Microsoft.AspNetCore.Mvc" },
                    CSharpGeneratorSettings           =
                    {
                        Namespace = "Echo.Ecommerce.Host.WebApi"
                    },
                    GenerateClientClasses   = true,
                    GenerateResponseClasses = false,
                    GenerateDtoTypes        = false
                };

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

                json = json.Replace("localhost", "swagger: 2.0");
                string path = System.IO.Path.Join(Environment.CurrentDirectory, "..//..//..//RestApi.cs");
                System.IO.File.WriteAllText(path, code);
                System.IO.File.WriteAllText(System.IO.Path.Join(Environment.CurrentDirectory, "..//..//..//..//Echo-Ecommerce-Web//swagger.json"), json);
            }
            catch (Exception ex)
            {
                Assert.Fail("Exception:" + ex.Message);
            }
            finally
            {
                rig.Stop();
            }
        }
        public static async Task <string> CreateNSwagStudioFileAsync(
            EnterOpenApiSpecDialogResult enterOpenApiSpecDialogResult,
            INSwagStudioOptions options = null,
            string outputNamespace      = null)
        {
            var specifications  = enterOpenApiSpecDialogResult.OpenApiSpecification;
            var outputFilename  = enterOpenApiSpecDialogResult.OutputFilename;
            var url             = enterOpenApiSpecDialogResult.Url;
            var openApiDocument = url.EndsWith("yaml") || url.EndsWith("yml")
                ? await OpenApiYamlDocument.FromUrlAsync(url)
                : await OpenApiDocument.FromJsonAsync(specifications);

            var className = options?.UseDocumentTitle ?? true
                ? openApiDocument.GenerateClassName()
                : outputFilename;

            return(new
            {
                Runtime = "Default",
                SwaggerGenerator = new
                {
                    FromSwagger = GetFromSwagger(enterOpenApiSpecDialogResult, specifications)
                },
                CodeGenerators = new
                {
                    SwaggerToCSharpClient = new
                    {
                        ClassName = className,
                        InjectHttpClient = options?.InjectHttpClient ?? true,
                        GenerateClientInterfaces = options?.GenerateClientInterfaces ?? true,
                        GenerateDtoTypes = options?.GenerateDtoTypes ?? true,
                        UseBaseUrl = options?.UseBaseUrl ?? false,
                        OperationGenerationMode = "MultipleClientsFromOperationId",
                        GenerateResponseClasses = options?.GenerateResponseClasses ?? true,
                        GenerateJsonMethods = options?.GenerateJsonMethods ?? true,
                        RequiredPropertiesMustBeDefined = options?.RequiredPropertiesMustBeDefined ?? true,
                        ClassStyle = options?.ClassStyle ?? CSharpClassStyle.Poco,
                        GenerateDefaultValues = options?.GenerateDefaultValues ?? true,
                        GenerateDataAnnotations = options?.GenerateDataAnnotations ?? true,
                        Namespace = outputNamespace ?? "GeneratedCode",
                        Output = $"{className}.cs"
                    }
                }
            }
                   .ToJson());
        }