public async Task When_yaml_OpenAPI_spec_has_external_schema_refs_they_are_resolved(string relativePath, string docPath, string header) { var path = GetTestDirectory() + relativePath; //// Act OpenApiDocument doc = await OpenApiYamlDocument.FromFileAsync(path); IDictionary <string, OpenApiPathItem> docPaths = doc.Paths; OpenApiPathItem pathItem = docPaths[docPath]; OpenApiOperation operation = pathItem["get"]; IDictionary <string, OpenApiResponse> responses = operation.Responses; OpenApiResponse OK = responses["200"].ActualResponse; OpenApiHeaders OKheaders = OK.Headers; OpenApiResponse Unauthorized = responses["401"].ActualResponse; ////Assert // Header schema loaded correctly from headers.yaml Assert.True(OKheaders.ContainsKey(header)); Assert.NotNull(OKheaders[header]); //Response data loaded correctly from responses.yaml string problemType = "application/problem+json"; Assert.True(Unauthorized.Content.ContainsKey(problemType)); Assert.NotNull(Unauthorized.Content[problemType]); Assert.NotNull(Unauthorized.Schema); }
public async Task When_yaml_OpenAPI_spec_has__relative_external_schema_refs_in_subdirs__they_are_resolved(string relativePath) { var path = GetTestDirectory() + relativePath; OpenApiDocument doc = await OpenApiYamlDocument.FromFileAsync(path); IDictionary <string, OpenApiPathItem> docPaths = doc.Paths; OpenApiPathItem pathItem = docPaths["/life-cycles"]; OpenApiOperation operation = pathItem["get"]; IDictionary <string, OpenApiResponse> responses = operation.Responses; OpenApiResponse OK = responses["200"].ActualResponse; var schema = OK.Content["application/json"]; JsonSchemaProperty items = schema.Schema.ActualSchema.ActualProperties["items"]; var innerProperties = items.Item.ActualSchema.ActualProperties; string[] expectedProperties = new string[] { "id", "systemName", "name", "smallImageID", "helpText" }; foreach (string property in expectedProperties) { Assert.True(innerProperties.ContainsKey(property)); } pathItem = docPaths["/ad-hoc-tasks/{adhocTaskId}/execute"]; operation = pathItem["post"]; responses = operation.Responses; OK = responses["200"].ActualResponse; schema = OK.Content["application/json"]; Assert.Equal("status", schema.Schema.ActualDiscriminator); Assert.Equal("Completed", schema.Schema.ActualDiscriminatorObject.Mapping.Keys.First()); Assert.Equal(2, schema.Schema.ActualSchema.ActualProperties["status"].ActualSchema.Enumeration.Count); }
/// <summary> /// /// </summary> /// <param name="specification"></param> /// <returns></returns> public NSwagRunner FromYamlSpecification(FilePath specification) { string path = Context.MakeAbsolute(specification).FullPath; OpenApiDocument document = OpenApiYamlDocument.FromFileAsync(path).Result; return(new NSwagRunner(Context, document)); }
public async Task When_body_has_multiple_parameters_then_all_parameter_is_used_in_CSharp_ASPNetCore() { 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': description: 'something' content: application/json: schema: $ref: '#/components/schemas/FileToken' requestBody: content: multipart/form-data: schema: type: object required: - file properties: file: type: string format: binary id: type: string format: uuid components: schemas: FileToken: type: object required: - fileId properties: fileId: type: string format: uuid"; var document = await OpenApiYamlDocument.FromYamlAsync(yaml); //// Act CSharpControllerGeneratorSettings settings = new CSharpControllerGeneratorSettings(); settings.ControllerTarget = CSharpControllerTarget.AspNetCore; var codeGenerator = new CSharpControllerGenerator(document, settings); var code = codeGenerator.GenerateFile(); //// Assert Assert.Contains("id", code); Assert.DoesNotContain("FromBody]", code); }
public async Task When_yaml_with_custom_property_is_loaded_then_document_is_not_null() { //// Arrange var yaml = @"swagger: '2.0' info: title: foo version: '1.0' paths: /bar: x-swagger-router-controller: bar get: responses: '200': description: baz"; //// Act var document = await OpenApiYamlDocument.FromYamlAsync(yaml); yaml = document.ToYaml(); //// Assert Assert.NotNull(document); Assert.Equal("bar", document.Paths.First().Value.ExtensionData["x-swagger-router-controller"]); Assert.Contains("x-swagger-router-controller: bar", yaml); }
public static async Task Main(string[] args) { // Read the Open API YAML specification OpenApiDocument document = await OpenApiYamlDocument.FromUrlAsync("https://raw.githubusercontent.com/netlify/open-api/master/swagger.yml"); // Generate the code CSharpClientGeneratorSettings clientSettings = new CSharpClientGeneratorSettings { ClassName = nameof(NetlifyClient), CSharpGeneratorSettings = { Namespace = nameof(NetlifySharp), PropertyNameGenerator = new PascalCasePropertyNameGenerator() }, ParameterNameGenerator = new CamelCaseParameterNameGenerator(), ExceptionClass = nameof(NetlifyException), InjectHttpClient = false, UseHttpClientCreationMethod = true }; clientSettings.CSharpGeneratorSettings.TemplateFactory = new CustomTemplateFactory( clientSettings.CSharpGeneratorSettings.TemplateFactory, clientSettings); CSharpClientGenerator generator = new CSharpClientGenerator(document, clientSettings); string code = generator.GenerateFile(); // Make the constructor private so we can write our own code = code.Replace($"public {clientSettings.ClassName}(", $"private {clientSettings.ClassName}("); // Write to a file in the client project System.IO.File.WriteAllText($"../../src/NetlifySharp/{clientSettings.ClassName}.Generated.cs", code); }
/// <summary>Generates or gets the cached Swagger specification.</summary> /// <param name="context">The context.</param> /// <returns>The Swagger specification.</returns> protected virtual async Task <string> GetDocumentAsync(HttpContext context) { var documentKey = _settings.CreateDocumentCacheKey?.Invoke(context.Request) ?? string.Empty; Tuple <string, ExceptionDispatchInfo, DateTimeOffset> document; lock (_documentsCacheLock) { _documentsCache.TryGetValue(documentKey, out document); } if (document?.Item2 != null && document.Item3 + _settings.ExceptionCacheTime > DateTimeOffset.UtcNow) { document.Item2.Throw(); } var apiDescriptionGroups = _apiDescriptionGroupCollectionProvider.ApiDescriptionGroups; if (apiDescriptionGroups.Version == Volatile.Read(ref _version) && document?.Item1 != null) { return(document.Item1); } try { var openApiDocument = await GenerateDocumentAsync(context); var data = _path.ToLowerInvariant().Contains(".yaml") ? OpenApiYamlDocument.ToYaml(openApiDocument) : openApiDocument.ToJson(); XmlDocs.ClearCache(); CachedType.ClearCache(); _version = apiDescriptionGroups.Version; lock (_documentsCacheLock) { _documentsCache[documentKey] = new Tuple <string, ExceptionDispatchInfo, DateTimeOffset>( data, null, DateTimeOffset.UtcNow); } return(data); } catch (Exception exception) { lock (_documentsCacheLock) { _documentsCache[documentKey] = new Tuple <string, ExceptionDispatchInfo, DateTimeOffset>( null, ExceptionDispatchInfo.Capture(exception), DateTimeOffset.UtcNow); } throw; } }
/// <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)); }
public OpenApiDocument GetDocument(string swaggerFile) { return(swaggerFile.EndsWith("yaml") || swaggerFile.EndsWith("yml") ? OpenApiYamlDocument.FromFileAsync(swaggerFile) .GetAwaiter() .GetResult() : OpenApiDocument.FromFileAsync(swaggerFile) .GetAwaiter() .GetResult()); }
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 OpenApiYamlDocument.FromYamlAsync(yaml); // Act var codeGenerator = new TypeScriptClientGenerator(document, new TypeScriptClientGeneratorSettings()); 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); }
public async Task When_yaml_schema_has_references_it_works(string relativePath) { //// Arrange var path = GetTestDirectory() + relativePath; //// Act var document = await OpenApiYamlDocument.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); }
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 OpenApiYamlDocument.FromYamlAsync(yaml); //// Act var codeGenerator = new CSharpClientGenerator(document, new CSharpClientGeneratorSettings()); 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); }
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))); } }
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()); }
static async Task Generate(string source, string target, string name, bool repeat = false) { var document = await OpenApiYamlDocument.FromUrlAsync(source); var settings = new CSharpClientGeneratorSettings { ClassName = "{controller}Client", ExposeJsonSerializerSettings = true, CSharpGeneratorSettings = { Namespace = name } }; var generator = new CSharpClientGenerator(document, settings); var code = generator.GenerateFile(); File.WriteAllText(target, code); }
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()); } }
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)); } } }
protected override async Task OnInstallPackagesAsync( AsyncPackage package, Project project, EnterOpenApiSpecDialogResult dialogResult) { var url = dialogResult.Url; const StringComparison comparisonType = StringComparison.OrdinalIgnoreCase; var document = url.EndsWith("yaml", comparisonType) || url.EndsWith("yml", comparisonType) ? await OpenApiYamlDocument.FromYamlAsync(dialogResult.OpenApiSpecification) : await OpenApiDocument.FromJsonAsync(dialogResult.OpenApiSpecification); var codeGenerator = GetSupportedCodeGenerator(document); await project.InstallMissingPackagesAsync(package, codeGenerator); if (codeGenerator == SupportedCodeGenerator.AutoRestV3) { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); project.Save(); await project.UpdatePropertyGroupsAsync(AutoRestConstants.PropertyGroups); } }
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)); } }
public async Task When_yaml_with_description_is_loaded_then_document_is_not_null() { //// Arrange var yaml = @"info: title: Foo version: 1.0.0 paths: /something: description: foo get: responses: 200: description: get description"; //// Act var document = await OpenApiYamlDocument.FromYamlAsync(yaml); yaml = document.ToYaml(); //// Assert Assert.NotNull(document); Assert.Equal("foo", document.Paths.First().Value.Description); Assert.Contains("description: foo", yaml); }
public Task <OpenApiDocument> GetDocumentAsync(string swaggerFile) { return(swaggerFile.EndsWith("yaml") || swaggerFile.EndsWith("yml") ? OpenApiYamlDocument.FromFileAsync(swaggerFile) : OpenApiDocument.FromFileAsync(swaggerFile)); }
/// <summary> /// /// </summary> /// <param name="specification"></param> /// <returns></returns> public NSwagRunner FromYamlSpecification(Uri specification) { OpenApiDocument document = OpenApiYamlDocument.FromUrlAsync(specification.ToString()).Result; return(new NSwagRunner(Context, document)); }
public static Task <bool> TryWriteDocumentOutputAsync(this IOutputCommand command, IConsoleHost host, NewLineBehavior newLineBehavior, Func <OpenApiDocument> generator) { return(TryWriteFileOutputAsync(command, command.OutputFilePath, host, newLineBehavior, () => command.OutputFilePath.EndsWith(".yaml", StringComparison.OrdinalIgnoreCase) ? OpenApiYamlDocument.ToYaml(generator()) : generator().ToJson())); }
private static async Task Main(string[] args) { string baseDir = FindBaseDir(); string sourcepath = Path.Combine(baseDir, "api"); string destinationpath = Path.Combine(baseDir, "BlockM3.AEternity.SDK", "Generated"); string[] sources = Directory.GetFiles(sourcepath, "s*.yml"); if (sources.Length != 2) { throw new ArgumentException("Expecting only 2 swagger definitions in api directory (api and compiler)"); } CSharpClientGeneratorSettings apisettings = new CSharpClientGeneratorSettings { CSharpGeneratorSettings = { Namespace = "BlockM3.AEternity.SDK.Generated.Api", SchemaType = SchemaType.OpenApi3, PropertyNameGenerator = new CustomTypeScriptPropertyNameGenerator() }, AdditionalNamespaceUsages = new[] { "BlockM3.AEternity.SDK.Generated.Models", "System.Numerics" }, AdditionalContractNamespaceUsages = new[] { "System.Numerics" } }; apisettings.CSharpGeneratorSettings.ValueGenerator = new CustomValueGenerator(apisettings.CSharpGeneratorSettings); CSharpClientGeneratorSettings compilersettings = new CSharpClientGeneratorSettings { CSharpGeneratorSettings = { ExcludedTypeNames = new[] { "ByteCode", "Error" }, Namespace = "BlockM3.AEternity.SDK.Generated.Compiler", SchemaType = SchemaType.OpenApi3, PropertyNameGenerator = new CustomTypeScriptPropertyNameGenerator() }, AdditionalNamespaceUsages = new[] { "BlockM3.AEternity.SDK.Generated.Models", "System.Numerics" }, AdditionalContractNamespaceUsages = new[] { "System.Numerics" }, GenerateExceptionClasses = false, }; compilersettings.CSharpGeneratorSettings.ValueGenerator = new CustomValueGenerator(apisettings.CSharpGeneratorSettings); string compiler = sources.FirstOrDefault(a => a.Contains("compiler")); if (compiler == null) { throw new ArgumentException("Expecting compiler api definition in api"); } string api = sources.First(a => a != compiler); OpenApiDocument apidocument = await OpenApiYamlDocument.FromFileAsync(api); OpenApiDocument compilerdocument = await OpenApiYamlDocument.FromFileAsync(compiler); var apigenerator = new CSharpClientGenerator(apidocument, apisettings, CreateResolverWithExceptionSchema(apisettings.CSharpGeneratorSettings, apidocument)); var compilergenerator = new CSharpClientGenerator(compilerdocument, compilersettings, CreateResolverWithExceptionSchema(compilersettings.CSharpGeneratorSettings, compilerdocument)); string apiclient = apigenerator.GenerateFile(ClientGeneratorOutputType.Implementation); apigenerator.Settings.CSharpGeneratorSettings.Namespace = "BlockM3.AEternity.SDK.Generated.Models"; string apimodels = apigenerator.GenerateFile(ClientGeneratorOutputType.Contracts); string compilerclient = compilergenerator.GenerateFile(ClientGeneratorOutputType.Implementation); compilergenerator.Settings.CSharpGeneratorSettings.Namespace = "BlockM3.AEternity.SDK.Generated.Models"; string compilermodels = compilergenerator.GenerateFile(ClientGeneratorOutputType.Contracts); string apipath = Path.Combine(destinationpath, "Api"); string compilerpath = Path.Combine(destinationpath, "Compiler"); string modelpath = Path.Combine(destinationpath, "Models"); try { Directory.CreateDirectory(apipath); } catch { // ignored } try { Directory.CreateDirectory(compilerpath); } catch { //ignored } try { Directory.CreateDirectory(modelpath); } catch { //ignored } await File.WriteAllTextAsync(Path.Combine(apipath, "Client.cs"), apiclient, Encoding.UTF8); await File.WriteAllTextAsync(Path.Combine(compilerpath, "Client.cs"), compilerclient, Encoding.UTF8); await File.WriteAllTextAsync(Path.Combine(modelpath, "Models.cs"), apimodels, Encoding.UTF8); await File.WriteAllTextAsync(Path.Combine(modelpath, "ModelsCompiler.cs"), compilermodels, Encoding.UTF8); }