Beispiel #1
0
        public string ToCSharpCodeClient(OpenApiDocument document, string _namespace, string className, string[] namespaceUsages)
        {
            //System.Net.WebClient wclient = new System.Net.WebClient();
            //var document = await OpenApiDocument.FromJsonAsync(wclient.DownloadString("Https://SwaggerSpecificationURL.json"));
            //wclient.Dispose();

            var settings = new CSharpClientGeneratorSettings
            {
                ClassName = className,//"AlibabaApiClient",
                CSharpGeneratorSettings =
                {
                    Namespace = _namespace//"AlibabaSDK"
                },
                GenerateSyncMethods        = true,
                GenerateDtoTypes           = false,
                GenerateClientInterfaces   = true,
                GenerateExceptionClasses   = false,
                GenerateOptionalParameters = true,
                AdditionalNamespaceUsages  = namespaceUsages//new[] { "AlibabaSDK.Models" }
            };

            //settings.CodeGeneratorSettings.TemplateDirectory = "";
            settings.CodeGeneratorSettings.GenerateDefaultValues = true;
            settings.CodeGeneratorSettings.PropertyNameGenerator = new MyCSharpPropertyNameGenerator();
            settings.CodeGeneratorSettings.TemplateDirectory     = @"D:\Users\mccj\Source\Repos\AlibabaSDKFor1688\src\tools\AlibabaSDKFor1688GenerationApp\Templates";

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

            return(code);
        }
Beispiel #2
0
        public string ToCSharpCode(OpenApiDocument document)
        {
            //System.Net.WebClient wclient = new System.Net.WebClient();
            //var document = await OpenApiDocument.FromJsonAsync(wclient.DownloadString("Https://SwaggerSpecificationURL.json"));
            //wclient.Dispose();

            var settings = new CSharpClientGeneratorSettings
            {
                ClassName = "AlibabaApiClient",
                CSharpGeneratorSettings =
                {
                    Namespace = "AlibabaSDK"
                },
                GenerateSyncMethods = true
            };

            //settings.CodeGeneratorSettings.TemplateDirectory = "";
            settings.CodeGeneratorSettings.GenerateDefaultValues = true;
            settings.CodeGeneratorSettings.PropertyNameGenerator = new MyCSharpPropertyNameGenerator();

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

            return(code);
        }
        public string ToCSharpCode(OpenApiDocument document, string _namespace)
        {
            var settings = new CSharpClientGeneratorSettings
            {
                CSharpGeneratorSettings =
                {
                    Namespace = _namespace,//"AlibabaSDK"
                },
                //GenerateSyncMethods = true,
                ////GenerateDtoTypes = false,
                //GenerateClientInterfaces = true,
                //GenerateExceptionClasses = false,
                //GenerateOptionalParameters = true,
            };

            //settings.CodeGeneratorSettings.TemplateDirectory = "";
            settings.CodeGeneratorSettings.GenerateDefaultValues             = true;
            settings.CodeGeneratorSettings.PropertyNameGenerator             = new MyCSharpPropertyNameGenerator();
            settings.CSharpGeneratorSettings.GenerateJsonMethods             = false;
            settings.CSharpGeneratorSettings.RequiredPropertiesMustBeDefined = false;

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

            return(code);
        }
Beispiel #4
0
        public void When_parameters_have_same_name_then_they_are_renamed()
        {
            //// Arrange
            var document = new OpenApiDocument();

            document.Paths["foo"] = new OpenApiPathItem
            {
                {
                    OpenApiOperationMethod.Get, new OpenApiOperation
                    {
                        Parameters =
                        {
                            new OpenApiParameter
                            {
                                Kind = OpenApiParameterKind.Query,
                                Name = "foo"
                            },
                            new OpenApiParameter
                            {
                                Kind = OpenApiParameterKind.Header,
                                Name = "foo"
                            },
                        }
                    }
                }
            };

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

            //// Assert
            Assert.Contains("FooAsync(object fooQuery, object fooHeader, System.Threading.CancellationToken cancellationToken)", code);
        }
Beispiel #5
0
        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);
        }
Beispiel #6
0
        public Task <Dictionary <string, string> > RunAsync()
        {
            return(Task.Run(async() =>
            {
                var document = await GetInputSwaggerDocument().ConfigureAwait(false);
                var clientGenerator = new CSharpClientGenerator(document, Settings);

                if (GenerateContractsOutput)
                {
                    var result = new Dictionary <string, string>();
                    GenerateContracts(result, clientGenerator);
                    GenerateImplementation(result, clientGenerator);
                    return result;
                }
                else
                {
                    // when generating single file allow caching
                    Settings.OutputFilePath = OutputFilePath;
                    return new Dictionary <string, string>
                    {
                        { OutputFilePath ?? "Full", clientGenerator.GenerateFile(ClientGeneratorOutputType.Full) }
                    };
                }
            }));
        }
Beispiel #7
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}");
        }
Beispiel #8
0
        private static void GenerateCSharp(OpenApiDocument document)
        {
            var generatorSettings = new CSharpClientGeneratorSettings
            {
                ExceptionClass             = "NotifoException",
                GenerateOptionalParameters = true,
                GenerateClientInterfaces   = true,
                GenerateBaseUrlProperty    = true,
                OperationNameGenerator     = new TagNameGenerator(),
                UseBaseUrl = true
            };

            generatorSettings.CSharpGeneratorSettings.ExcludedTypeNames               = new[] { "JsonInheritanceConverter" };
            generatorSettings.CSharpGeneratorSettings.ArrayBaseType                   = "System.Collections.Generic.List";
            generatorSettings.CSharpGeneratorSettings.ArrayInstanceType               = "System.Collections.Generic.List";
            generatorSettings.CSharpGeneratorSettings.ArrayType                       = "System.Collections.Generic.List";
            generatorSettings.CSharpGeneratorSettings.DictionaryBaseType              = "System.Collections.Generic.Dictionary";
            generatorSettings.CSharpGeneratorSettings.DictionaryInstanceType          = "System.Collections.Generic.Dictionary";
            generatorSettings.CSharpGeneratorSettings.DictionaryType                  = "System.Collections.Generic.Dictionary";
            generatorSettings.CSharpGeneratorSettings.Namespace                       = "Notifo.SDK";
            generatorSettings.CSharpGeneratorSettings.RequiredPropertiesMustBeDefined = false;

            var codeGenerator = new CSharpClientGenerator(document, generatorSettings);

            var code = codeGenerator.GenerateFile();

            code = code.Replace("https://*****:*****@"..\..\..\..\Notifo.SDK\Generated.cs", code);
        }
Beispiel #9
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);
        }
Beispiel #10
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);
        }
Beispiel #11
0
        private static void GenerateClient(OpenApiDocument apiDocument, string outputDirectory, string apiClientClassName, string generatedClientFilePostfix, Func <CSharpClientGeneratorSettings> cSharpClientGeneratorSettingsCreator, out IReadOnlyDictionary <string, ModelNameWithNamespaceInfo> typeNameHintsModelWithNamespaceInfos)
        {
            Console.Write(InsertSpaces("Generating Api Client..."));

            var modelWithNamespaceTypeNameGenerator = new ModelWithNamespaceTypeNameGenerator();

            var settings = cSharpClientGeneratorSettingsCreator();

            settings.ClassName                  = apiClientClassName;
            settings.GenerateDtoTypes           = false;
            settings.GenerateClientClasses      = true;
            settings.GenerateOptionalParameters = true;

            settings.CSharpGeneratorSettings.TypeNameGenerator = modelWithNamespaceTypeNameGenerator;
            settings.HttpClientType = "OpenWater.ApiClient.OpenWaterHttpClient";

            var generator           = new CSharpClientGenerator(apiDocument, settings);
            var generatedClientFile = generator.GenerateFile();

            // there are no options to make constructor protected using generator settings
            generatedClientFile = generatedClientFile.Replace($"public {apiClientClassName}(", $"private {apiClientClassName}(");

            // sealed class doesn't contain virtual and protected methods
            generatedClientFile = generatedClientFile.Replace(" virtual ", " ");
            generatedClientFile = generatedClientFile.Replace("protected ", "private ");

            var path = Path.Combine(outputDirectory, $"{settings.ClassName}.{generatedClientFilePostfix}.cs");

            File.WriteAllText(path, generatedClientFile);

            typeNameHintsModelWithNamespaceInfos = modelWithNamespaceTypeNameGenerator.TypeNameHintsModelNameWithNamespaceInfos;

            Console.WriteLine("Done");
        }
Beispiel #12
0
        public static void Main()
        {
            var document = OpenApiDocument.FromUrlAsync("https://*****:*****@"..\..\..\..\Squidex.ClientLibrary\Management\Generated.cs", code);
        }
Beispiel #13
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
                }));
            }
        }
        private static string GenerateNSwagTemplateFromDocument(OpenApiDocument document)
        {
            var settings = new CSharpClientGeneratorSettings
            {
                ClassName = UrsaApplication.PackingParameters.ClassName,
                GenerateClientInterfaces = true,
                CSharpGeneratorSettings  =
                {
                    Namespace         = UrsaApplication.PackingParameters.Namespace,
                    TypeNameGenerator = new DefaultTypeNameGenerator
                    {
                        ReservedTypeNames                = new[]
                        {
                            UrsaApplication.PackingParameters.Namespace,
                            UrsaApplication.PackingParameters.ClassName
                        },
                    },
                    GenerateOptionalPropertiesAsNullable = false
                }
            };

            var generator = new CSharpClientGenerator(document, settings);

            return(generator.GenerateFile());
        }
        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);
        }
Beispiel #16
0
        public void When_original_name_is_defined_then_csharp_parameter_is_the_same()
        {
            // Arrange
            var document = new OpenApiDocument();

            document.Paths["foo"] = new OpenApiPathItem
            {
                {
                    OpenApiOperationMethod.Get, new OpenApiOperation
                    {
                        Parameters =
                        {
                            new OpenApiParameter
                            {
                                Kind         = OpenApiParameterKind.Query,
                                Name         = "foo",
                                OriginalName = "bar",
                                Schema       = new JsonSchema
                                {
                                    Type = JsonObjectType.String
                                }
                            }
                        }
                    }
                }
            };

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

            // Assert
            Assert.Contains("FooAsync(string bar,", code);
            Assert.Contains("EscapeDataString(\"foo\")", code);
        }
Beispiel #17
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);
        }
Beispiel #18
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="outputFile"></param>
        /// <param name="settings"></param>
        /// <returns></returns>
        public NSwagRunner GenerateCSharpClient(FilePath outputFile, CSharpClientGeneratorSettings settings = null)
        {
            settings = settings ?? new CSharpClientGeneratorSettings();
            var generator = new CSharpClientGenerator(Document, settings);

            WriteToFile(outputFile, generator.GenerateFile());
            return(this);
        }
Beispiel #19
0
        private void GenerateContracts(Dictionary <string, string> result, CSharpClientGenerator clientGenerator)
        {
            var savedNamespace = Settings.CSharpGeneratorSettings.Namespace;

            Settings.CSharpGeneratorSettings.Namespace     = ContractsNamespace;
            result[ContractsOutputFilePath ?? "Contracts"] = clientGenerator.GenerateFile(ClientGeneratorOutputType.Contracts);
            Settings.CSharpGeneratorSettings.Namespace     = savedNamespace;
        }
Beispiel #20
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);
        }
Beispiel #21
0
        private void GenerateImplementation(Dictionary <string, string> result, CSharpClientGenerator clientGenerator)
        {
            var savedAdditionalNamespaceUsages = Settings.AdditionalNamespaceUsages?.ToArray();

            Settings.AdditionalNamespaceUsages =
                Settings.AdditionalNamespaceUsages?.Concat(new[] { ContractsNamespace }).ToArray() ?? new[] { ContractsNamespace };
            result[OutputFilePath ?? "Implementation"] = clientGenerator.GenerateFile(ClientGeneratorOutputType.Implementation);
            Settings.AdditionalNamespaceUsages         = savedAdditionalNamespaceUsages;
        }
Beispiel #22
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
        }
Beispiel #23
0
        public async Task When_operation_is_HTTP_head_then_no_content_is_not_used()
        {
            // Arrange
            var generator = new WebApiOpenApiDocumentGenerator(new WebApiOpenApiDocumentGeneratorSettings());
            var document  = await generator.GenerateForControllerAsync <HeadRequestController>();

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

            // Assert
            Assert.DoesNotContain("System.Net.Http.StringContent", code);
        }
Beispiel #24
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);
            }
        }
        public async Task When_parameter_name_is_reserved_keyword_then_it_is_appended_with_at()
        {
            //// Arrange
            var swaggerGenerator = new WebApiOpenApiDocumentGenerator(new WebApiOpenApiDocumentGeneratorSettings());
            var document         = await swaggerGenerator.GenerateForControllerAsync <FooController>();

            var generator = new CSharpClientGenerator(document, new CSharpClientGeneratorSettings());

            //// Act
            var code = generator.GenerateFile();

            //// Assert
            Assert.Contains("Task<object> GetPersonAsync(bool? @override, ", code);
        }
Beispiel #26
0
        public async Task When_action_has_file_parameter_then_Stream_is_generated_in_CSharp_code()
        {
            // Arrange
            var generator = new WebApiOpenApiDocumentGenerator(new WebApiOpenApiDocumentGeneratorSettings());
            var document  = await generator.GenerateForControllerAsync <FileUploadController>();

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

            // Assert
            Assert.Contains("FileParameter file", code);
            Assert.Contains("var content_file_ = new System.Net.Http.StreamContent(file.Data);", code);
            Assert.Contains("content_.Add(content_file_, \"file\", file.FileName ??", code);
        }
        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);
        }
Beispiel #28
0
        public async Task When_body_is_xml_then_correct_csharp_is_generated()
        {
            //// Arrange
            var generator = new WebApiOpenApiDocumentGenerator(new WebApiOpenApiDocumentGeneratorSettings());
            var document  = await generator.GenerateForControllerAsync <MyXmlController>();

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

            //// Assert
            Assert.IsTrue(code.Contains("(string xmlDocument, "));
            Assert.IsTrue(code.Contains("var content_ = new System.Net.Http.StringContent(xmlDocument);"));
            Assert.IsTrue(code.Contains("content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse(\"application/xml\");"));
        }
Beispiel #29
0
        public async Task When_body_is_binary_then_stream_is_used_as_parameter_in_CSharp()
        {
            var yaml = @"openapi: 3.0.0
servers:
  - url: https://www.example.com/
info:
  version: '2.0.0'
  title: 'Test API'   
paths:
  /files:
    post:
      tags:
        - Files
      summary: 'Add File'
      operationId: addFile
      responses:
        '200':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/FileToken'
      requestBody:
        content:
          image/png:
            schema:
              type: string
              format: binary
components:
  schemas:
    FileToken:
      type: object
      required:
        - fileId    
      properties:  
        fileId:
          type: string
          format: uuid";

            var document = await 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);
        }
Beispiel #30
0
        public void When_generating_CSharp_code_with_SystemTextJson_then_output_contains_expected_code()
        {
            // Arrange
            var document = CreateDocument();

            // Act
            var settings = new CSharpClientGeneratorSettings();

            settings.CSharpGeneratorSettings.JsonLibrary = NJsonSchema.CodeGeneration.CSharp.CSharpJsonLibrary.SystemTextJson;

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

            // Assert
            Assert.Contains("new System.Text.Json.JsonSerializerOptions()", code);
        }