├── .github └── workflows │ └── publish.yml ├── .gitignore ├── Compentio.Assets ├── AdditionalFile.png ├── GeneratedFiles.png └── Logo.png ├── Compentio.SourceApi ├── Compentio.SourceApi.WebExample │ ├── Compentio.SourceApi.WebExample.csproj │ ├── Controllers │ │ ├── PetsController.cs │ │ ├── StoreController.cs │ │ └── UsersController.cs │ ├── OpenApi │ │ ├── Pets.yaml │ │ ├── Store.yaml │ │ └── Users.yaml │ ├── Program.cs │ ├── Properties │ │ └── launchSettings.json │ ├── Startup.cs │ ├── appsettings.Development.json │ └── appsettings.json ├── Compentio.SourceApi.sln └── Compentio.SourceApi │ ├── AnalyzerReleases.Shipped.md │ ├── AnalyzerReleases.Unshipped.md │ ├── Compentio.SourceApi.csproj │ ├── Context │ ├── ConfigurationContext.cs │ ├── OpenApiContext.cs │ ├── OpenApiFileContext.cs │ └── OpenApiFileFormat.cs │ ├── Diagnostics │ ├── DiagnosticInfo.cs │ └── SourceApiDescriptor.cs │ ├── Generator.cs │ ├── Generator.props │ └── Generators │ ├── GeneratorStrategy.cs │ ├── GeneratorStrategyFactory.cs │ ├── JsonGeneratorStrategy.cs │ ├── Result.cs │ └── YamlGeneratorStrategy.cs ├── LICENSE └── README.md /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | name: Publish 2 | on: 3 | push: 4 | branches: [ main ] 5 | pull_request: 6 | # The branches below must be a subset of the branches above 7 | branches: [ main ] 8 | jobs: 9 | publish: 10 | name: build, pack & publish 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions/checkout@v2 14 | 15 | - name: Setup dotnet 16 | uses: actions/setup-dotnet@v1 17 | with: 18 | dotnet-version: 5.0.x 19 | 20 | # Publish 21 | - name: publish on version change 22 | id: publish_nuget 23 | uses: rohith/publish-nuget@v2 24 | with: 25 | # Filepath of the project to be packaged, relative to root of repository 26 | PROJECT_FILE_PATH: Compentio.SourceApi/Compentio.SourceApi/Compentio.SourceApi.csproj 27 | 28 | # NuGet package id, used for version detection & defaults to project name 29 | PACKAGE_NAME: Compentio.SourceApi 30 | 31 | # Filepath with version info, relative to root of repository & defaults to PROJECT_FILE_PATH 32 | VERSION_FILE_PATH: Compentio.SourceApi/Compentio.SourceApi/Compentio.SourceApi.csproj 33 | 34 | # Regex pattern to extract version info in a capturing group 35 | VERSION_REGEX: ^\s*(.*)<\/Version>\s*$ 36 | 37 | # Useful with external providers like Nerdbank.GitVersioning, ignores VERSION_FILE_PATH & VERSION_REGEX 38 | # VERSION_STATIC: 1.0.0 39 | 40 | # Flag to toggle git tagging, enabled by default 41 | # TAG_COMMIT: true 42 | 43 | # Format of the git tag, [*] gets replaced with actual version 44 | # TAG_FORMAT: v* 45 | 46 | # API key to authenticate with NuGet server 47 | NUGET_KEY: ${{secrets.NUGET_API_KEY}} 48 | 49 | # NuGet server uri hosting the packages, defaults to https://api.nuget.org 50 | # NUGET_SOURCE: https://api.nuget.org 51 | 52 | # Flag to toggle pushing symbols along with nuget package to the server, disabled by default 53 | # INCLUDE_SYMBOLS: false 54 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Aa][Rr][Mm]/ 27 | [Aa][Rr][Mm]64/ 28 | bld/ 29 | [Bb]in/ 30 | [Oo]bj/ 31 | [Ll]og/ 32 | [Ll]ogs/ 33 | 34 | # Visual Studio 2015/2017 cache/options directory 35 | .vs/ 36 | # Uncomment if you have tasks that create the project's static files in wwwroot 37 | #wwwroot/ 38 | 39 | # Visual Studio 2017 auto generated files 40 | Generated\ Files/ 41 | 42 | # MSTest test Results 43 | [Tt]est[Rr]esult*/ 44 | [Bb]uild[Ll]og.* 45 | 46 | # NUnit 47 | *.VisualState.xml 48 | TestResult.xml 49 | nunit-*.xml 50 | 51 | # Build Results of an ATL Project 52 | [Dd]ebugPS/ 53 | [Rr]eleasePS/ 54 | dlldata.c 55 | 56 | # Benchmark Results 57 | BenchmarkDotNet.Artifacts/ 58 | 59 | # .NET Core 60 | project.lock.json 61 | project.fragment.lock.json 62 | artifacts/ 63 | 64 | # StyleCop 65 | StyleCopReport.xml 66 | 67 | # Files built by Visual Studio 68 | *_i.c 69 | *_p.c 70 | *_h.h 71 | *.ilk 72 | *.meta 73 | *.obj 74 | *.iobj 75 | *.pch 76 | *.pdb 77 | *.ipdb 78 | *.pgc 79 | *.pgd 80 | *.rsp 81 | *.sbr 82 | *.tlb 83 | *.tli 84 | *.tlh 85 | *.tmp 86 | *.tmp_proj 87 | *_wpftmp.csproj 88 | *.log 89 | *.vspscc 90 | *.vssscc 91 | .builds 92 | *.pidb 93 | *.svclog 94 | *.scc 95 | 96 | # Chutzpah Test files 97 | _Chutzpah* 98 | 99 | # Visual C++ cache files 100 | ipch/ 101 | *.aps 102 | *.ncb 103 | *.opendb 104 | *.opensdf 105 | *.sdf 106 | *.cachefile 107 | *.VC.db 108 | *.VC.VC.opendb 109 | 110 | # Visual Studio profiler 111 | *.psess 112 | *.vsp 113 | *.vspx 114 | *.sap 115 | 116 | # Visual Studio Trace Files 117 | *.e2e 118 | 119 | # TFS 2012 Local Workspace 120 | $tf/ 121 | 122 | # Guidance Automation Toolkit 123 | *.gpState 124 | 125 | # ReSharper is a .NET coding add-in 126 | _ReSharper*/ 127 | *.[Rr]e[Ss]harper 128 | *.DotSettings.user 129 | 130 | # TeamCity is a build add-in 131 | _TeamCity* 132 | 133 | # DotCover is a Code Coverage Tool 134 | *.dotCover 135 | 136 | # AxoCover is a Code Coverage Tool 137 | .axoCover/* 138 | !.axoCover/settings.json 139 | 140 | # Visual Studio code coverage results 141 | *.coverage 142 | *.coveragexml 143 | 144 | # NCrunch 145 | _NCrunch_* 146 | .*crunch*.local.xml 147 | nCrunchTemp_* 148 | 149 | # MightyMoose 150 | *.mm.* 151 | AutoTest.Net/ 152 | 153 | # Web workbench (sass) 154 | .sass-cache/ 155 | 156 | # Installshield output folder 157 | [Ee]xpress/ 158 | 159 | # DocProject is a documentation generator add-in 160 | DocProject/buildhelp/ 161 | DocProject/Help/*.HxT 162 | DocProject/Help/*.HxC 163 | DocProject/Help/*.hhc 164 | DocProject/Help/*.hhk 165 | DocProject/Help/*.hhp 166 | DocProject/Help/Html2 167 | DocProject/Help/html 168 | 169 | # Click-Once directory 170 | publish/ 171 | 172 | # Publish Web Output 173 | *.[Pp]ublish.xml 174 | *.azurePubxml 175 | # Note: Comment the next line if you want to checkin your web deploy settings, 176 | # but database connection strings (with potential passwords) will be unencrypted 177 | *.pubxml 178 | *.publishproj 179 | 180 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 181 | # checkin your Azure Web App publish settings, but sensitive information contained 182 | # in these scripts will be unencrypted 183 | PublishScripts/ 184 | 185 | # NuGet Packages 186 | *.nupkg 187 | # NuGet Symbol Packages 188 | *.snupkg 189 | # The packages folder can be ignored because of Package Restore 190 | **/[Pp]ackages/* 191 | # except build/, which is used as an MSBuild target. 192 | !**/[Pp]ackages/build/ 193 | # Uncomment if necessary however generally it will be regenerated when needed 194 | #!**/[Pp]ackages/repositories.config 195 | # NuGet v3's project.json files produces more ignorable files 196 | *.nuget.props 197 | *.nuget.targets 198 | 199 | # Microsoft Azure Build Output 200 | csx/ 201 | *.build.csdef 202 | 203 | # Microsoft Azure Emulator 204 | ecf/ 205 | rcf/ 206 | 207 | # Windows Store app package directories and files 208 | AppPackages/ 209 | BundleArtifacts/ 210 | Package.StoreAssociation.xml 211 | _pkginfo.txt 212 | *.appx 213 | *.appxbundle 214 | *.appxupload 215 | 216 | # Visual Studio cache files 217 | # files ending in .cache can be ignored 218 | *.[Cc]ache 219 | # but keep track of directories ending in .cache 220 | !?*.[Cc]ache/ 221 | 222 | # Others 223 | ClientBin/ 224 | ~$* 225 | *~ 226 | *.dbmdl 227 | *.dbproj.schemaview 228 | *.jfm 229 | *.pfx 230 | *.publishsettings 231 | orleans.codegen.cs 232 | 233 | # Including strong name files can present a security risk 234 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 235 | #*.snk 236 | 237 | # Since there are multiple workflows, uncomment next line to ignore bower_components 238 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 239 | #bower_components/ 240 | 241 | # RIA/Silverlight projects 242 | Generated_Code/ 243 | 244 | # Backup & report files from converting an old project file 245 | # to a newer Visual Studio version. Backup files are not needed, 246 | # because we have git ;-) 247 | _UpgradeReport_Files/ 248 | Backup*/ 249 | UpgradeLog*.XML 250 | UpgradeLog*.htm 251 | ServiceFabricBackup/ 252 | *.rptproj.bak 253 | 254 | # SQL Server files 255 | *.mdf 256 | *.ldf 257 | *.ndf 258 | 259 | # Business Intelligence projects 260 | *.rdl.data 261 | *.bim.layout 262 | *.bim_*.settings 263 | *.rptproj.rsuser 264 | *- [Bb]ackup.rdl 265 | *- [Bb]ackup ([0-9]).rdl 266 | *- [Bb]ackup ([0-9][0-9]).rdl 267 | 268 | # Microsoft Fakes 269 | FakesAssemblies/ 270 | 271 | # GhostDoc plugin setting file 272 | *.GhostDoc.xml 273 | 274 | # Node.js Tools for Visual Studio 275 | .ntvs_analysis.dat 276 | node_modules/ 277 | 278 | # Visual Studio 6 build log 279 | *.plg 280 | 281 | # Visual Studio 6 workspace options file 282 | *.opt 283 | 284 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 285 | *.vbw 286 | 287 | # Visual Studio LightSwitch build output 288 | **/*.HTMLClient/GeneratedArtifacts 289 | **/*.DesktopClient/GeneratedArtifacts 290 | **/*.DesktopClient/ModelManifest.xml 291 | **/*.Server/GeneratedArtifacts 292 | **/*.Server/ModelManifest.xml 293 | _Pvt_Extensions 294 | 295 | # Paket dependency manager 296 | .paket/paket.exe 297 | paket-files/ 298 | 299 | # FAKE - F# Make 300 | .fake/ 301 | 302 | # CodeRush personal settings 303 | .cr/personal 304 | 305 | # Python Tools for Visual Studio (PTVS) 306 | __pycache__/ 307 | *.pyc 308 | 309 | # Cake - Uncomment if you are using it 310 | # tools/** 311 | # !tools/packages.config 312 | 313 | # Tabs Studio 314 | *.tss 315 | 316 | # Telerik's JustMock configuration file 317 | *.jmconfig 318 | 319 | # BizTalk build output 320 | *.btp.cs 321 | *.btm.cs 322 | *.odx.cs 323 | *.xsd.cs 324 | 325 | # OpenCover UI analysis results 326 | OpenCover/ 327 | 328 | # Azure Stream Analytics local run output 329 | ASALocalRun/ 330 | 331 | # MSBuild Binary and Structured Log 332 | *.binlog 333 | 334 | # NVidia Nsight GPU debugger configuration file 335 | *.nvuser 336 | 337 | # MFractors (Xamarin productivity tool) working folder 338 | .mfractor/ 339 | 340 | # Local History for Visual Studio 341 | .localhistory/ 342 | 343 | # BeatPulse healthcheck temp database 344 | healthchecksdb 345 | 346 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 347 | MigrationBackup/ 348 | 349 | # Ionide (cross platform F# VS Code tools) working folder 350 | .ionide/ 351 | -------------------------------------------------------------------------------- /Compentio.Assets/AdditionalFile.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alekshura/SourceApi/afc45debc6ec98566778c34230adb33e4a34f359/Compentio.Assets/AdditionalFile.png -------------------------------------------------------------------------------- /Compentio.Assets/GeneratedFiles.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alekshura/SourceApi/afc45debc6ec98566778c34230adb33e4a34f359/Compentio.Assets/GeneratedFiles.png -------------------------------------------------------------------------------- /Compentio.Assets/Logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alekshura/SourceApi/afc45debc6ec98566778c34230adb33e4a34f359/Compentio.Assets/Logo.png -------------------------------------------------------------------------------- /Compentio.SourceApi/Compentio.SourceApi.WebExample/Compentio.SourceApi.WebExample.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net5.0 5 | true 6 | $(NoWarn);1591 7 | Compentio.SourceApi.WebExample.Controllers 8 | false 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /Compentio.SourceApi/Compentio.SourceApi.WebExample/Controllers/PetsController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | using Microsoft.AspNetCore.Mvc.ModelBinding; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Threading.Tasks; 6 | 7 | namespace Compentio.SourceApi.WebExample.Controllers 8 | { 9 | [ApiController] 10 | [ApiConventionType(typeof(DefaultApiConventions))] 11 | public class PetsController : PetsControllerBase 12 | { 13 | /// 14 | public override Task AddPet([BindRequired, FromBody] Pet body) 15 | { 16 | throw new NotImplementedException(); 17 | } 18 | 19 | /// 20 | public override Task DeletePet([BindRequired] long petId, [FromHeader] string api_key = null) 21 | { 22 | throw new NotImplementedException(); 23 | } 24 | 25 | /// 26 | public override Task>> FindPetsByStatus([BindRequired, FromQuery] IEnumerable status) 27 | { 28 | throw new NotImplementedException(); 29 | } 30 | 31 | /// 32 | public override Task>> FindPetsByTags([BindRequired, FromQuery] IEnumerable tags) 33 | { 34 | throw new NotImplementedException(); 35 | } 36 | 37 | /// 38 | public override Task> GetPetById([BindRequired] long petId) 39 | { 40 | throw new NotImplementedException(); 41 | } 42 | 43 | /// 44 | public override Task UpdatePet([BindRequired, FromBody] Pet body) 45 | { 46 | throw new NotImplementedException(); 47 | } 48 | 49 | /// 50 | public override Task UpdatePetWithForm([BindRequired] long petId, [FromBody] Body body = null) 51 | { 52 | throw new NotImplementedException(); 53 | } 54 | 55 | /// 56 | public override Task> UploadFile([BindRequired] long petId, string additionalMetadata = null, FileParameter file = null) 57 | { 58 | throw new NotImplementedException(); 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /Compentio.SourceApi/Compentio.SourceApi.WebExample/Controllers/StoreController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | using Microsoft.AspNetCore.Mvc.ModelBinding; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Net; 6 | using System.Threading.Tasks; 7 | 8 | namespace Compentio.SourceApi.WebExample.Controllers 9 | { 10 | [ApiController] 11 | [ApiConventionType(typeof(DefaultApiConventions))] 12 | public class StoreController : StoreControllerBase 13 | { 14 | /// 15 | public async override Task DeleteOrder([BindRequired] long orderId) 16 | { 17 | // Implement your async code here 18 | return Accepted(); 19 | } 20 | 21 | /// 22 | public async override Task>> GetInventory() 23 | { 24 | // Implement your async code here 25 | return Ok(); 26 | } 27 | 28 | /// 29 | public async override Task> GetOrderById([BindRequired] long orderId) 30 | { 31 | // Implement your async code here 32 | return Accepted(); 33 | } 34 | 35 | /// 36 | public async override Task> PlaceOrder([BindRequired, FromBody] Order body) 37 | { 38 | // Implement your async code here 39 | return Accepted(); 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Compentio.SourceApi/Compentio.SourceApi.WebExample/Controllers/UsersController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | using Microsoft.AspNetCore.Mvc.ModelBinding; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Threading.Tasks; 6 | 7 | namespace Compentio.SourceApi.WebExample.Controllers 8 | { 9 | [ApiController] 10 | [ApiConventionType(typeof(DefaultApiConventions))] 11 | public class UsersController : UsersControllerBase 12 | { 13 | /// 14 | public override Task CreateUser([BindRequired, FromBody] User body) 15 | { 16 | throw new NotImplementedException(); 17 | } 18 | 19 | /// 20 | public override Task CreateUsersWithArrayInput([BindRequired, FromBody] IEnumerable body) 21 | { 22 | throw new NotImplementedException(); 23 | } 24 | 25 | /// 26 | public override Task CreateUsersWithListInput([BindRequired, FromBody] IEnumerable body) 27 | { 28 | throw new NotImplementedException(); 29 | } 30 | 31 | /// 32 | public override Task DeleteUser([BindRequired] string username) 33 | { 34 | throw new NotImplementedException(); 35 | } 36 | 37 | /// 38 | public override Task> GetUserByName([BindRequired] string username) 39 | { 40 | throw new NotImplementedException(); 41 | } 42 | 43 | /// 44 | public override Task> LoginUser([BindRequired, FromQuery] string username, [BindRequired, FromQuery] string password) 45 | { 46 | throw new NotImplementedException(); 47 | } 48 | 49 | /// 50 | public override Task LogoutUser() 51 | { 52 | throw new NotImplementedException(); 53 | } 54 | 55 | /// 56 | public override Task UpdateUser([BindRequired] string username, [BindRequired, FromBody] User body) 57 | { 58 | throw new NotImplementedException(); 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /Compentio.SourceApi/Compentio.SourceApi.WebExample/OpenApi/Pets.yaml: -------------------------------------------------------------------------------- 1 | openapi: 3.0.1 2 | info: 3 | title: Swagger Petstore 4 | description: 'This is a sample server Petstore server. You can find out more about Swagger 5 | at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For 6 | this sample, you can use the api key `special-key` to test the authorization filters.' 7 | termsOfService: http://swagger.io/terms/ 8 | contact: 9 | email: apiteam@swagger.io 10 | license: 11 | name: Apache 2.0 12 | url: http://www.apache.org/licenses/LICENSE-2.0.html 13 | version: 1.0.0 14 | externalDocs: 15 | description: Find out more about Swagger 16 | url: http://swagger.io 17 | servers: 18 | - url: https://petstore.swagger.io/api/v1 19 | - url: http://petstore.swagger.io/api/v1 20 | paths: 21 | /pet: 22 | put: 23 | summary: Update an existing pet 24 | operationId: updatePet 25 | requestBody: 26 | description: Pet object that needs to be added to the store 27 | content: 28 | application/json: 29 | schema: 30 | $ref: '#/components/schemas/Pet' 31 | application/xml: 32 | schema: 33 | $ref: '#/components/schemas/Pet' 34 | required: true 35 | responses: 36 | 400: 37 | description: Invalid ID supplied 38 | content: {} 39 | 404: 40 | description: Pet not found 41 | content: {} 42 | 405: 43 | description: Validation exception 44 | content: {} 45 | security: 46 | - petstore_auth: 47 | - write:pets 48 | - read:pets 49 | x-codegen-request-body-name: body 50 | post: 51 | summary: Add a new pet to the store 52 | operationId: addPet 53 | requestBody: 54 | description: Pet object that needs to be added to the store 55 | content: 56 | application/json: 57 | schema: 58 | $ref: '#/components/schemas/Pet' 59 | application/xml: 60 | schema: 61 | $ref: '#/components/schemas/Pet' 62 | required: true 63 | responses: 64 | 405: 65 | description: Invalid input 66 | content: {} 67 | security: 68 | - petstore_auth: 69 | - write:pets 70 | - read:pets 71 | x-codegen-request-body-name: body 72 | /pet/findByStatus: 73 | get: 74 | summary: Finds Pets by status 75 | description: Multiple status values can be provided with comma separated strings 76 | operationId: findPetsByStatus 77 | parameters: 78 | - name: status 79 | in: query 80 | description: Status values that need to be considered for filter 81 | required: true 82 | style: form 83 | explode: true 84 | schema: 85 | type: array 86 | items: 87 | type: string 88 | default: available 89 | enum: 90 | - available 91 | - pending 92 | - sold 93 | responses: 94 | 200: 95 | description: successful operation 96 | content: 97 | application/xml: 98 | schema: 99 | type: array 100 | items: 101 | $ref: '#/components/schemas/Pet' 102 | application/json: 103 | schema: 104 | type: array 105 | items: 106 | $ref: '#/components/schemas/Pet' 107 | 400: 108 | description: Invalid status value 109 | content: {} 110 | security: 111 | - petstore_auth: 112 | - write:pets 113 | - read:pets 114 | /pet/findByTags: 115 | get: 116 | summary: Finds Pets by tags 117 | description: Muliple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. 118 | operationId: findPetsByTags 119 | parameters: 120 | - name: tags 121 | in: query 122 | description: Tags to filter by 123 | required: true 124 | style: form 125 | explode: true 126 | schema: 127 | type: array 128 | items: 129 | type: string 130 | responses: 131 | 200: 132 | description: successful operation 133 | content: 134 | application/xml: 135 | schema: 136 | type: array 137 | items: 138 | $ref: '#/components/schemas/Pet' 139 | application/json: 140 | schema: 141 | type: array 142 | items: 143 | $ref: '#/components/schemas/Pet' 144 | 400: 145 | description: Invalid tag value 146 | content: {} 147 | deprecated: true 148 | security: 149 | - petstore_auth: 150 | - write:pets 151 | - read:pets 152 | /pet/{petId}: 153 | get: 154 | summary: Find pet by ID 155 | description: Returns a single pet 156 | operationId: getPetById 157 | parameters: 158 | - name: petId 159 | in: path 160 | description: ID of pet to return 161 | required: true 162 | schema: 163 | type: integer 164 | format: int64 165 | responses: 166 | 200: 167 | description: successful operation 168 | content: 169 | application/xml: 170 | schema: 171 | $ref: '#/components/schemas/Pet' 172 | application/json: 173 | schema: 174 | $ref: '#/components/schemas/Pet' 175 | 400: 176 | description: Invalid ID supplied 177 | content: {} 178 | 404: 179 | description: Pet not found 180 | content: {} 181 | security: 182 | - api_key: [] 183 | post: 184 | summary: Updates a pet in the store with form data 185 | operationId: updatePetWithForm 186 | parameters: 187 | - name: petId 188 | in: path 189 | description: ID of pet that needs to be updated 190 | required: true 191 | schema: 192 | type: integer 193 | format: int64 194 | requestBody: 195 | content: 196 | application/x-www-form-urlencoded: 197 | schema: 198 | properties: 199 | name: 200 | type: string 201 | description: Updated name of the pet 202 | status: 203 | type: string 204 | description: Updated status of the pet 205 | responses: 206 | 405: 207 | description: Invalid input 208 | content: {} 209 | security: 210 | - petstore_auth: 211 | - write:pets 212 | - read:pets 213 | delete: 214 | summary: Deletes a pet 215 | operationId: deletePet 216 | parameters: 217 | - name: api_key 218 | in: header 219 | schema: 220 | type: string 221 | - name: petId 222 | in: path 223 | description: Pet id to delete 224 | required: true 225 | schema: 226 | type: integer 227 | format: int64 228 | responses: 229 | 400: 230 | description: Invalid ID supplied 231 | content: {} 232 | 404: 233 | description: Pet not found 234 | content: {} 235 | security: 236 | - petstore_auth: 237 | - write:pets 238 | - read:pets 239 | /pet/{petId}/uploadImage: 240 | post: 241 | tags: 242 | - pet 243 | summary: uploads an image 244 | operationId: uploadFile 245 | parameters: 246 | - name: petId 247 | in: path 248 | description: ID of pet to update 249 | required: true 250 | schema: 251 | type: integer 252 | format: int64 253 | requestBody: 254 | content: 255 | multipart/form-data: 256 | schema: 257 | properties: 258 | additionalMetadata: 259 | type: string 260 | description: Additional data to pass to server 261 | file: 262 | type: string 263 | description: file to upload 264 | format: binary 265 | responses: 266 | 200: 267 | description: successful operation 268 | content: 269 | application/json: 270 | schema: 271 | $ref: '#/components/schemas/ApiResponse' 272 | security: 273 | - petstore_auth: 274 | - write:pets 275 | - read:pets 276 | 277 | components: 278 | schemas: 279 | Tag: 280 | type: object 281 | additionalProperties: false 282 | properties: 283 | id: 284 | type: integer 285 | format: int64 286 | name: 287 | type: string 288 | xml: 289 | name: Tag 290 | Pet: 291 | required: 292 | - name 293 | - photoUrls 294 | type: object 295 | additionalProperties: false 296 | properties: 297 | id: 298 | type: integer 299 | format: int64 300 | category: 301 | $ref: '#/components/schemas/Category' 302 | name: 303 | type: string 304 | example: doggie 305 | photoUrls: 306 | type: array 307 | xml: 308 | name: photoUrl 309 | wrapped: true 310 | items: 311 | type: string 312 | tags: 313 | type: array 314 | xml: 315 | name: tag 316 | wrapped: true 317 | items: 318 | $ref: '#/components/schemas/Tag' 319 | status: 320 | type: string 321 | description: pet status in the store 322 | enum: 323 | - available 324 | - pending 325 | - sold 326 | xml: 327 | name: Pet 328 | Category: 329 | type: object 330 | additionalProperties: false 331 | properties: 332 | id: 333 | type: integer 334 | format: int64 335 | name: 336 | type: string 337 | xml: 338 | name: Category 339 | ApiResponse: 340 | type: object 341 | additionalProperties: false 342 | properties: 343 | code: 344 | type: integer 345 | format: int32 346 | type: 347 | type: string 348 | message: 349 | type: string 350 | securitySchemes: 351 | petstore_auth: 352 | type: oauth2 353 | flows: 354 | implicit: 355 | authorizationUrl: http://petstore.swagger.io/oauth/dialog 356 | scopes: 357 | write:pets: modify pets in your account 358 | read:pets: read your pets 359 | api_key: 360 | type: apiKey 361 | name: api_key 362 | in: header 363 | -------------------------------------------------------------------------------- /Compentio.SourceApi/Compentio.SourceApi.WebExample/OpenApi/Store.yaml: -------------------------------------------------------------------------------- 1 | openapi: 3.0.1 2 | info: 3 | title: Swagger Petstore 4 | description: 'This is a sample server Petstore server. You can find out more about Swagger 5 | at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For 6 | this sample, you can use the api key `special-key` to test the authorization filters.' 7 | termsOfService: http://swagger.io/terms/ 8 | contact: 9 | email: apiteam@swagger.io 10 | license: 11 | name: Apache 2.0 12 | url: http://www.apache.org/licenses/LICENSE-2.0.html 13 | version: 1.0.0 14 | externalDocs: 15 | description: Find out more about Swagger 16 | url: http://swagger.io 17 | servers: 18 | - url: https://petstore.swagger.io/api/v1 19 | - url: http://petstore.swagger.io/api/v1 20 | paths: 21 | /store/inventory: 22 | get: 23 | summary: Returns pet inventories by status 24 | description: Returns a map of status codes to quantities 25 | operationId: getInventory 26 | responses: 27 | 200: 28 | description: successful operation 29 | content: 30 | application/json: 31 | schema: 32 | type: object 33 | additionalProperties: 34 | type: integer 35 | format: int32 36 | security: 37 | - api_key: [] 38 | /store/order: 39 | post: 40 | summary: Place an order for a pet 41 | operationId: placeOrder 42 | requestBody: 43 | description: order placed for purchasing the pet 44 | content: 45 | '*/*': 46 | schema: 47 | $ref: '#/components/schemas/Order' 48 | required: true 49 | responses: 50 | 200: 51 | description: successful operation 52 | content: 53 | application/xml: 54 | schema: 55 | $ref: '#/components/schemas/Order' 56 | application/json: 57 | schema: 58 | $ref: '#/components/schemas/Order' 59 | 400: 60 | description: Invalid Order 61 | content: {} 62 | x-codegen-request-body-name: body 63 | /store/order/{orderId}: 64 | get: 65 | summary: Find purchase order by ID 66 | description: For valid response try integer IDs with value >= 1 and <= 10. Other 67 | values will generated exceptions 68 | operationId: getOrderById 69 | parameters: 70 | - name: orderId 71 | in: path 72 | description: ID of pet that needs to be fetched 73 | required: true 74 | schema: 75 | maximum: 10.0 76 | minimum: 1.0 77 | type: integer 78 | format: int64 79 | responses: 80 | 200: 81 | description: successful operation 82 | content: 83 | application/xml: 84 | schema: 85 | $ref: '#/components/schemas/Order' 86 | application/json: 87 | schema: 88 | $ref: '#/components/schemas/Order' 89 | 400: 90 | description: Invalid ID supplied 91 | content: {} 92 | 404: 93 | description: Order not found 94 | content: {} 95 | delete: 96 | summary: Delete purchase order by ID 97 | description: For valid response try integer IDs with positive integer value. Negative 98 | or non-integer values will generate API errors 99 | operationId: deleteOrder 100 | parameters: 101 | - name: orderId 102 | in: path 103 | description: ID of the order that needs to be deleted 104 | required: true 105 | schema: 106 | minimum: 1.0 107 | type: integer 108 | format: int64 109 | responses: 110 | 400: 111 | description: Invalid ID supplied 112 | content: {} 113 | 404: 114 | description: Order not found 115 | content: {} 116 | components: 117 | schemas: 118 | Order: 119 | type: object 120 | additionalProperties: false 121 | properties: 122 | id: 123 | type: integer 124 | format: int64 125 | petId: 126 | type: integer 127 | format: int64 128 | quantity: 129 | type: integer 130 | format: int32 131 | shipDate: 132 | type: string 133 | format: date-time 134 | status: 135 | type: string 136 | description: Order Status 137 | enum: 138 | - placed 139 | - approved 140 | - delivered 141 | complete: 142 | type: boolean 143 | default: false 144 | xml: 145 | name: Order 146 | -------------------------------------------------------------------------------- /Compentio.SourceApi/Compentio.SourceApi.WebExample/OpenApi/Users.yaml: -------------------------------------------------------------------------------- 1 | openapi: 3.0.1 2 | info: 3 | title: Swagger Petstore 4 | description: 'This is a sample server Petstore server. You can find out more about Swagger 5 | at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For 6 | this sample, you can use the api key `special-key` to test the authorization filters.' 7 | termsOfService: http://swagger.io/terms/ 8 | contact: 9 | email: apiteam@swagger.io 10 | license: 11 | name: Apache 2.0 12 | url: http://www.apache.org/licenses/LICENSE-2.0.html 13 | version: 1.0.0 14 | externalDocs: 15 | description: Find out more about Swagger 16 | url: http://swagger.io 17 | servers: 18 | - url: https://petstore.swagger.io/api/v1 19 | - url: http://petstore.swagger.io/api/v1 20 | paths: 21 | /user: 22 | post: 23 | tags: 24 | - user 25 | summary: Create user 26 | description: This can only be done by the logged in user. 27 | operationId: createUser 28 | requestBody: 29 | description: Created user object 30 | content: 31 | '*/*': 32 | schema: 33 | $ref: '#/components/schemas/User' 34 | required: true 35 | responses: 36 | default: 37 | description: successful operation 38 | content: {} 39 | x-codegen-request-body-name: body 40 | /user/createWithArray: 41 | post: 42 | tags: 43 | - user 44 | summary: Creates list of users with given input array 45 | operationId: createUsersWithArrayInput 46 | requestBody: 47 | description: List of user object 48 | content: 49 | '*/*': 50 | schema: 51 | type: array 52 | items: 53 | $ref: '#/components/schemas/User' 54 | required: true 55 | responses: 56 | default: 57 | description: successful operation 58 | content: {} 59 | x-codegen-request-body-name: body 60 | /user/createWithList: 61 | post: 62 | tags: 63 | - user 64 | summary: Creates list of users with given input array 65 | operationId: createUsersWithListInput 66 | requestBody: 67 | description: List of user object 68 | content: 69 | '*/*': 70 | schema: 71 | type: array 72 | items: 73 | $ref: '#/components/schemas/User' 74 | required: true 75 | responses: 76 | default: 77 | description: successful operation 78 | content: {} 79 | x-codegen-request-body-name: body 80 | /user/login: 81 | get: 82 | tags: 83 | - user 84 | summary: Logs user into the system 85 | operationId: loginUser 86 | parameters: 87 | - name: username 88 | in: query 89 | description: The user name for login 90 | required: true 91 | schema: 92 | type: string 93 | - name: password 94 | in: query 95 | description: The password for login in clear text 96 | required: true 97 | schema: 98 | type: string 99 | responses: 100 | 200: 101 | description: successful operation 102 | headers: 103 | X-Rate-Limit: 104 | description: calls per hour allowed by the user 105 | schema: 106 | type: integer 107 | format: int32 108 | X-Expires-After: 109 | description: date in UTC when token expires 110 | schema: 111 | type: string 112 | format: date-time 113 | content: 114 | application/xml: 115 | schema: 116 | type: string 117 | application/json: 118 | schema: 119 | type: string 120 | 400: 121 | description: Invalid username/password supplied 122 | content: {} 123 | /user/logout: 124 | get: 125 | tags: 126 | - user 127 | summary: Logs out current logged in user session 128 | operationId: logoutUser 129 | responses: 130 | default: 131 | description: successful operation 132 | content: {} 133 | /user/{username}: 134 | get: 135 | tags: 136 | - user 137 | summary: Get user by user name 138 | operationId: getUserByName 139 | parameters: 140 | - name: username 141 | in: path 142 | description: 'The name that needs to be fetched. Use user1 for testing. ' 143 | required: true 144 | schema: 145 | type: string 146 | responses: 147 | 200: 148 | description: successful operation 149 | content: 150 | application/xml: 151 | schema: 152 | $ref: '#/components/schemas/User' 153 | application/json: 154 | schema: 155 | $ref: '#/components/schemas/User' 156 | 400: 157 | description: Invalid username supplied 158 | content: {} 159 | 404: 160 | description: User not found 161 | content: {} 162 | put: 163 | tags: 164 | - user 165 | summary: Updated user 166 | description: This can only be done by the logged in user. 167 | operationId: updateUser 168 | parameters: 169 | - name: username 170 | in: path 171 | description: name that need to be updated 172 | required: true 173 | schema: 174 | type: string 175 | requestBody: 176 | description: Updated user object 177 | content: 178 | '*/*': 179 | schema: 180 | $ref: '#/components/schemas/User' 181 | required: true 182 | responses: 183 | 400: 184 | description: Invalid user supplied 185 | content: {} 186 | 404: 187 | description: User not found 188 | content: {} 189 | x-codegen-request-body-name: body 190 | delete: 191 | tags: 192 | - user 193 | summary: Delete user 194 | description: This can only be done by the logged in user. 195 | operationId: deleteUser 196 | parameters: 197 | - name: username 198 | in: path 199 | description: The name that needs to be deleted 200 | required: true 201 | schema: 202 | type: string 203 | responses: 204 | 400: 205 | description: Invalid username supplied 206 | content: {} 207 | 404: 208 | description: User not found 209 | content: {} 210 | components: 211 | schemas: 212 | User: 213 | type: object 214 | additionalProperties: false 215 | properties: 216 | id: 217 | type: integer 218 | format: int64 219 | username: 220 | type: string 221 | firstName: 222 | type: string 223 | lastName: 224 | type: string 225 | email: 226 | type: string 227 | password: 228 | type: string 229 | phone: 230 | type: string 231 | userStatus: 232 | type: integer 233 | description: User Status 234 | format: int32 235 | xml: 236 | name: User 237 | -------------------------------------------------------------------------------- /Compentio.SourceApi/Compentio.SourceApi.WebExample/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Hosting; 2 | using Microsoft.Extensions.Hosting; 3 | 4 | namespace Compentio.SourceApi.WebExample 5 | { 6 | public class Program 7 | { 8 | public static void Main(string[] args) 9 | { 10 | CreateHostBuilder(args).Build().Run(); 11 | } 12 | 13 | public static IHostBuilder CreateHostBuilder(string[] args) => 14 | Host.CreateDefaultBuilder(args) 15 | .ConfigureWebHostDefaults(webBuilder => 16 | { 17 | webBuilder.UseStartup(); 18 | }); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Compentio.SourceApi/Compentio.SourceApi.WebExample/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:16177", 8 | "sslPort": 44323 9 | } 10 | }, 11 | "profiles": { 12 | "IIS Express": { 13 | "commandName": "IISExpress", 14 | "launchBrowser": true, 15 | "launchUrl": "swagger", 16 | "environmentVariables": { 17 | "ASPNETCORE_ENVIRONMENT": "Development" 18 | } 19 | }, 20 | "Compentio.SourceApi.WebExample": { 21 | "commandName": "Project", 22 | "dotnetRunMessages": "true", 23 | "launchBrowser": true, 24 | "launchUrl": "swagger", 25 | "applicationUrl": "https://localhost:5001;http://localhost:5000", 26 | "environmentVariables": { 27 | "ASPNETCORE_ENVIRONMENT": "Development" 28 | } 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Compentio.SourceApi/Compentio.SourceApi.WebExample/Startup.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Builder; 2 | using Microsoft.AspNetCore.Hosting; 3 | using Microsoft.Extensions.Configuration; 4 | using Microsoft.Extensions.DependencyInjection; 5 | using Microsoft.Extensions.Hosting; 6 | 7 | namespace Compentio.SourceApi.WebExample 8 | { 9 | public class Startup 10 | { 11 | public Startup(IConfiguration configuration) 12 | { 13 | Configuration = configuration; 14 | } 15 | 16 | public IConfiguration Configuration { get; } 17 | 18 | // This method gets called by the runtime. Use this method to add services to the container. 19 | public void ConfigureServices(IServiceCollection services) 20 | { 21 | 22 | services.AddControllers(); 23 | 24 | services.AddOpenApiDocument(configure => 25 | { 26 | configure.Title = "Open Api Pets documentation"; 27 | configure.Description = "This is example description"; 28 | configure.DocumentName = "Pets controller"; 29 | configure.GenerateExamples = true; 30 | configure.UseControllerSummaryAsTagDescription = true; 31 | configure.FlattenInheritanceHierarchy = true; 32 | configure.Version = "v1.0"; 33 | }); 34 | } 35 | 36 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 37 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 38 | { 39 | if (env.IsDevelopment()) 40 | { 41 | app.UseDeveloperExceptionPage(); 42 | app.UseOpenApi(); 43 | app.UseSwaggerUi3(); 44 | } 45 | 46 | app.UseHttpsRedirection(); 47 | 48 | app.UseRouting(); 49 | 50 | app.UseAuthorization(); 51 | 52 | app.UseEndpoints(endpoints => 53 | { 54 | endpoints.MapControllers(); 55 | }); 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /Compentio.SourceApi/Compentio.SourceApi.WebExample/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /Compentio.SourceApi/Compentio.SourceApi.WebExample/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | }, 9 | "AllowedHosts": "*" 10 | } 11 | -------------------------------------------------------------------------------- /Compentio.SourceApi/Compentio.SourceApi.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.31624.102 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Compentio.SourceApi", "Compentio.SourceApi\Compentio.SourceApi.csproj", "{8EEA987C-D85D-4AF8-A91C-B7CD1D05792E}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Compentio.SourceApi.WebExample", "Compentio.SourceApi.WebExample\Compentio.SourceApi.WebExample.csproj", "{0B7EA186-3549-4C33-8EDC-240B25A5FFDE}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {8EEA987C-D85D-4AF8-A91C-B7CD1D05792E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 17 | {8EEA987C-D85D-4AF8-A91C-B7CD1D05792E}.Debug|Any CPU.Build.0 = Debug|Any CPU 18 | {8EEA987C-D85D-4AF8-A91C-B7CD1D05792E}.Release|Any CPU.ActiveCfg = Release|Any CPU 19 | {8EEA987C-D85D-4AF8-A91C-B7CD1D05792E}.Release|Any CPU.Build.0 = Release|Any CPU 20 | {0B7EA186-3549-4C33-8EDC-240B25A5FFDE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {0B7EA186-3549-4C33-8EDC-240B25A5FFDE}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {0B7EA186-3549-4C33-8EDC-240B25A5FFDE}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {0B7EA186-3549-4C33-8EDC-240B25A5FFDE}.Release|Any CPU.Build.0 = Release|Any CPU 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | GlobalSection(ExtensibilityGlobals) = postSolution 29 | SolutionGuid = {991C7477-993B-4F86-9CEE-7CCE7F70A1C6} 30 | EndGlobalSection 31 | EndGlobal 32 | -------------------------------------------------------------------------------- /Compentio.SourceApi/Compentio.SourceApi/AnalyzerReleases.Shipped.md: -------------------------------------------------------------------------------- 1 | ; Shipped analyzer releases 2 | ; https://github.com/dotnet/roslyn-analyzers/blob/main/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md 3 | 4 | -------------------------------------------------------------------------------- /Compentio.SourceApi/Compentio.SourceApi/AnalyzerReleases.Unshipped.md: -------------------------------------------------------------------------------- 1 | ; Unshipped analyzer release 2 | ; https://github.com/dotnet/roslyn-analyzers/blob/main/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md 3 | 4 | ### New Rules 5 | 6 | Rule ID | Category | Severity | Notes 7 | --------|----------|----------|------- 8 | SAPI0099 | Design | Error | SourceApiDescriptor -------------------------------------------------------------------------------- /Compentio.SourceApi/Compentio.SourceApi/Compentio.SourceApi.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netstandard2.0 5 | 9.0 6 | true 7 | 1.1.1 8 | API first code generator based on json or yaml Open API definitions. 9 | CodeGenerator, OpenApi 10 | Copyright (c) @alekshura Compentio 2021 11 | Aleksander Parchomenko 12 | Compentio 13 | MIT 14 | Compentio.SourceApi 15 | Compentio.SourceApi 16 | 17 | 18 | 19 | 20 | True 21 | 22 | 23 | 24 | all 25 | runtime; build; native; contentfiles; analyzers; buildtransitive 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | $(GetTargetPathDependsOn);GetDependencyTargetPaths 60 | Logo.png 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | -------------------------------------------------------------------------------- /Compentio.SourceApi/Compentio.SourceApi/Context/ConfigurationContext.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.CodeAnalysis.Diagnostics; 2 | 3 | namespace Compentio.SourceApi.Context 4 | { 5 | /// 6 | /// Configuration for Open API generators 7 | /// 8 | interface IConfigurationContext 9 | { 10 | /// 11 | /// Controllers and DTO's namespace 12 | /// 13 | public string Namespace { get; } 14 | /// 15 | /// Indicates when to generate only DTO's 16 | /// 17 | public bool GenerateOnlyContracts { get; } 18 | } 19 | 20 | /// 21 | abstract class ConfigurationContext : IConfigurationContext 22 | { 23 | protected readonly AnalyzerConfigOptions _options; 24 | protected const string BuldProperty = "build_property"; 25 | protected const string BuldMetadata = "build_metadata"; 26 | protected const string Name = "SourceApi"; 27 | protected const string NamespaceParameterName = "GeneratorNamespace"; 28 | protected const string GenerateOnlyContractsParameterName = "GenerateOnlyContracts"; 29 | 30 | public ConfigurationContext(AnalyzerConfigOptions options) 31 | { 32 | _options = options; 33 | } 34 | 35 | /// 36 | public virtual string Namespace { get; } 37 | 38 | /// 39 | public virtual bool GenerateOnlyContracts { get; } 40 | 41 | protected bool GetBoolParameter(string key) 42 | { 43 | if (_options.TryGetValue(key, out var stringValue)) 44 | { 45 | bool.TryParse(stringValue, out var boolValue); 46 | return boolValue; 47 | } 48 | 49 | return false; 50 | } 51 | 52 | protected string GetStringParameter(string key) 53 | { 54 | if (_options.TryGetValue(key, out var stringValue)) 55 | { 56 | return stringValue; 57 | } 58 | 59 | return string.Empty; 60 | } 61 | } 62 | 63 | /// 64 | class GlobalConfigurationContext : ConfigurationContext 65 | { 66 | public GlobalConfigurationContext(AnalyzerConfigOptions options) : base(options) 67 | { 68 | } 69 | 70 | /// 71 | public override string Namespace => GetStringParameter($"{BuldProperty}.{Name}_{NamespaceParameterName}"); 72 | 73 | /// 74 | public override bool GenerateOnlyContracts => GetBoolParameter($"{BuldProperty}.{Name}_{GenerateOnlyContractsParameterName}"); 75 | } 76 | 77 | class FileConfigurationContext : ConfigurationContext 78 | { 79 | private readonly IConfigurationContext _globalConfiguration; 80 | 81 | public FileConfigurationContext(AnalyzerConfigOptions options, IConfigurationContext globalConfiguration) 82 | : base(options) 83 | { 84 | _globalConfiguration = globalConfiguration; 85 | } 86 | 87 | /// 88 | public override string Namespace 89 | { 90 | get 91 | { 92 | var namespaceName = GetStringParameter($"{BuldMetadata}.AdditionalFiles.{Name}_{NamespaceParameterName}"); 93 | 94 | if (string.IsNullOrWhiteSpace(namespaceName)) 95 | { 96 | return _globalConfiguration.Namespace; 97 | } 98 | 99 | return namespaceName; 100 | } 101 | } 102 | 103 | /// 104 | public override bool GenerateOnlyContracts 105 | { 106 | get 107 | { 108 | var onlyContracts = GetBoolParameter($"{BuldMetadata}.AdditionalFiles.{Name}_{GenerateOnlyContractsParameterName}"); 109 | 110 | if (!onlyContracts) 111 | { 112 | return _globalConfiguration.GenerateOnlyContracts; 113 | } 114 | 115 | return onlyContracts; 116 | } 117 | } 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /Compentio.SourceApi/Compentio.SourceApi/Context/OpenApiContext.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.CodeAnalysis; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | 5 | namespace Compentio.SourceApi.Context 6 | { 7 | /// 8 | /// Contains for overall OpenApi files defined in application 9 | /// 10 | interface IOpenApiContext 11 | { 12 | /// 13 | /// Collection of Open API definitions files 14 | /// 15 | IEnumerable Context { get; } 16 | 17 | /// 18 | /// Global configuration for all Open Api files in context 19 | /// 20 | IConfigurationContext Configuration { get; } 21 | } 22 | 23 | /// 24 | class OpenApiContext : IOpenApiContext 25 | { 26 | private readonly GeneratorExecutionContext _generatorExecutionContext; 27 | private readonly IList _openApiFilesContext; 28 | private readonly IConfigurationContext _configurationContext; 29 | 30 | public static IOpenApiContext CreateFromExecutionContext(GeneratorExecutionContext generatorExecutionContext) => new OpenApiContext(generatorExecutionContext); 31 | 32 | private OpenApiContext(GeneratorExecutionContext generatorExecutionContext) 33 | { 34 | _generatorExecutionContext = generatorExecutionContext; 35 | _openApiFilesContext = new List(); 36 | _configurationContext = new GlobalConfigurationContext(_generatorExecutionContext.AnalyzerConfigOptions.GlobalOptions); 37 | LoadOpenApiFiles(_openApiFilesContext); 38 | } 39 | 40 | /// 41 | public IEnumerable Context => _openApiFilesContext; 42 | 43 | /// 44 | public IConfigurationContext Configuration => _configurationContext; 45 | 46 | private void LoadOpenApiFiles(IList openApiFilesContext) 47 | { 48 | foreach (var file in _generatorExecutionContext.AdditionalFiles.Where(file => IsOpenApiSchemeExtension(file.Path))) 49 | { 50 | var content = file.GetText()?.ToString(); 51 | if (!string.IsNullOrEmpty(content)) 52 | { 53 | var fileContext = new OpenApiFileContext(file.Path, 54 | _generatorExecutionContext.Compilation?.AssemblyName, 55 | _generatorExecutionContext.AnalyzerConfigOptions.GetOptions(file), 56 | _configurationContext); 57 | 58 | openApiFilesContext.Add(fileContext); 59 | } 60 | } 61 | } 62 | 63 | private bool IsOpenApiSchemeExtension(string filePath) 64 | { 65 | return filePath.EndsWith(".json", System.StringComparison.InvariantCultureIgnoreCase) || 66 | filePath.EndsWith(".yaml", System.StringComparison.InvariantCultureIgnoreCase) || 67 | filePath.EndsWith(".yml", System.StringComparison.InvariantCultureIgnoreCase); 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /Compentio.SourceApi/Compentio.SourceApi/Context/OpenApiFileContext.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.CodeAnalysis.Diagnostics; 2 | using System; 3 | using System.IO; 4 | using System.Linq; 5 | 6 | namespace Compentio.SourceApi.Context 7 | { 8 | /// 9 | /// Contains one file Open API information 10 | /// 11 | interface IOpenApiFileContext 12 | { 13 | string FilePath { get; } 14 | /// 15 | /// Filename of generated POCO file. It is always has *.cs extension. 16 | /// 17 | string FileName { get; } 18 | /// 19 | /// Generated class name 20 | /// 21 | string ClassName { get; } 22 | /// 23 | /// Namespace of generated class. If configuration for in *.cproj file is defined it is used otherwise the 24 | /// concatenation of main application namespace and directories of open api files locations. 25 | /// 26 | string Namespace { get; } 27 | /// 28 | /// File format. For Open API definition used yaml or json format 29 | /// 30 | OpenApiFileFormat FileFormat { get; } 31 | /// 32 | /// Configuration for single open API file gnerator processing 33 | /// 34 | IConfigurationContext Configuration { get; } 35 | } 36 | 37 | /// 38 | class OpenApiFileContext : IOpenApiFileContext 39 | { 40 | private readonly string _filePath; 41 | private readonly string _assemblyName; 42 | private readonly AnalyzerConfigOptions _options; 43 | private readonly IConfigurationContext _globalConfiguration; 44 | 45 | public OpenApiFileContext(string filePath, string assemblyName, AnalyzerConfigOptions options, IConfigurationContext globalConfiguration) 46 | { 47 | _filePath = filePath; 48 | _assemblyName = assemblyName; 49 | _options = options; 50 | _globalConfiguration = globalConfiguration; 51 | } 52 | 53 | /// 54 | public string FilePath => _filePath; 55 | 56 | /// 57 | public string ClassName => Path.GetFileNameWithoutExtension(_filePath); 58 | 59 | /// 60 | public string FileName => $"{ClassName}.cs"; 61 | 62 | /// 63 | public string Namespace 64 | { 65 | get 66 | { 67 | if (!string.IsNullOrEmpty(Configuration.Namespace)) 68 | { 69 | return Configuration.Namespace; 70 | } 71 | 72 | var assemlyRootDirectory = _filePath.Split(new string[] { _assemblyName }, StringSplitOptions.RemoveEmptyEntries)[1]; 73 | var namespaceName = string.Empty; 74 | foreach (var item in assemlyRootDirectory.Split(Path.DirectorySeparatorChar).Where(item => !string.IsNullOrWhiteSpace(item))) 75 | { 76 | if (item != Path.GetFileName(_filePath)) 77 | namespaceName += $".{item}"; 78 | } 79 | 80 | return $"{_assemblyName}{namespaceName}"; 81 | } 82 | } 83 | 84 | /// 85 | public OpenApiFileFormat FileFormat 86 | { 87 | get 88 | { 89 | var extension = Path.GetExtension(_filePath); 90 | return IsYaml(extension) ? OpenApiFileFormat.Yaml : OpenApiFileFormat.Json; 91 | } 92 | } 93 | 94 | /// 95 | public IConfigurationContext Configuration => new FileConfigurationContext(_options, _globalConfiguration); 96 | 97 | private bool IsYaml(string fileExtension) 98 | { 99 | return fileExtension.Equals(".yaml", StringComparison.OrdinalIgnoreCase) || fileExtension.Equals(".yml", StringComparison.OrdinalIgnoreCase); 100 | } 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /Compentio.SourceApi/Compentio.SourceApi/Context/OpenApiFileFormat.cs: -------------------------------------------------------------------------------- 1 | namespace Compentio.SourceApi.Context 2 | { 3 | /// 4 | /// File format for Open API definition 5 | /// 6 | enum OpenApiFileFormat 7 | { 8 | Yaml, Json 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Compentio.SourceApi/Compentio.SourceApi/Diagnostics/DiagnosticInfo.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.CodeAnalysis; 2 | using System; 3 | 4 | namespace Compentio.SourceApi.Diagnostics 5 | { 6 | /// 7 | /// stores information about problems or warnings during code generation. 8 | /// It is used to report it at the end of the process. 9 | /// 10 | internal class DiagnosticInfo 11 | { 12 | /// 13 | /// Descriptior of particular diagnostics proble 14 | /// 15 | internal DiagnosticDescriptor DiagnosticDescriptor { get; set; } 16 | /// 17 | /// Exception thrown during code generation 18 | /// 19 | internal Exception Exception { get; set; } 20 | /// 21 | /// Formatted message that is shoun in build console 22 | /// 23 | internal string Message => $"Message: {Exception.Message}, StackTrace: {Exception.StackTrace}"; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Compentio.SourceApi/Compentio.SourceApi/Diagnostics/SourceApiDescriptor.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.CodeAnalysis; 2 | 3 | namespace Compentio.SourceApi.Diagnostics 4 | { 5 | /// 6 | /// Source API generator diagnostics descriptors 7 | /// 8 | class SourceApiDescriptor 9 | { 10 | public static readonly DiagnosticDescriptor UnexpectedError = 11 | new("SAPI0099", "Unexpected error", "Unexpected error ocured with message: '{0}'", "Design", DiagnosticSeverity.Error, true, 12 | "Unexpected exception occured during code generation."); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Compentio.SourceApi/Compentio.SourceApi/Generator.cs: -------------------------------------------------------------------------------- 1 | using Compentio.SourceApi.Context; 2 | using Compentio.SourceApi.Generators; 3 | using Microsoft.CodeAnalysis; 4 | using System.Diagnostics; 5 | 6 | namespace Compentio.SourceApi 7 | { 8 | /// 9 | /// Main controllers source generator 10 | /// 11 | [Generator] 12 | public class Generator : ISourceGenerator 13 | { 14 | /// 15 | public void Execute(GeneratorExecutionContext context) 16 | { 17 | Trace.WriteLine($"Start generating your base controllers."); 18 | 19 | var openApiContext = OpenApiContext.CreateFromExecutionContext(context); 20 | 21 | foreach (var openApiFileContext in openApiContext.Context) 22 | { 23 | var generatorStrategy = GeneratorStrategyFactory.GetStrategy(openApiFileContext); 24 | var result = generatorStrategy.GenerateCode(openApiFileContext).Result; 25 | 26 | if (result.IsSuccess) 27 | { 28 | context.AddSource(openApiFileContext.FileName, result.GeneratedCode); 29 | } 30 | else 31 | { 32 | Trace.TraceError(result.Diagnostic.Message); 33 | context.ReportDiagnostic(Diagnostic.Create(result.Diagnostic.DiagnosticDescriptor, null, result.Diagnostic.Message)); 34 | } 35 | } 36 | 37 | Trace.WriteLine($"Code generating ended succesfully."); 38 | } 39 | 40 | /// 41 | public void Initialize(GeneratorInitializationContext context) 42 | { 43 | //#if DEBUG 44 | // if (!Debugger.IsAttached) 45 | // { 46 | // Debugger.Launch(); 47 | // } 48 | //#endif 49 | Trace.WriteLine($"'{typeof(Generator).FullName}' initalized."); 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /Compentio.SourceApi/Compentio.SourceApi/Generator.props: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Compentio.SourceApi/Compentio.SourceApi/Generators/GeneratorStrategy.cs: -------------------------------------------------------------------------------- 1 | using Compentio.SourceApi.Context; 2 | using NSwag; 3 | using NSwag.CodeGeneration.CSharp; 4 | using System; 5 | using System.Threading.Tasks; 6 | 7 | namespace Compentio.SourceApi.Generators 8 | { 9 | /// 10 | /// Open API code generation strategy. 11 | /// Json or Yaml Opean API schema is used for code generation. 12 | /// 13 | interface IGeneratorStrategy 14 | { 15 | /// 16 | /// Generates base controller with routes and DTO's and documentation 17 | /// 18 | /// Open API file 19 | /// Generated and formatted code with execution result. See: 20 | Task GenerateCode(IOpenApiFileContext context); 21 | } 22 | 23 | /// 24 | abstract class GeneratorStrategy : IGeneratorStrategy 25 | { 26 | /// 27 | public async Task GenerateCode(IOpenApiFileContext context) 28 | { 29 | try 30 | { 31 | var openApiDocument = await GetOpenApiDocumentAsync(context.FilePath); 32 | 33 | CSharpGeneratorBase generator = context.Configuration.GenerateOnlyContracts ? 34 | new CSharpClientGenerator(openApiDocument, CreateClientGeneratorSettings(context.Namespace)) : 35 | new CSharpControllerGenerator(openApiDocument, CreateControllerGeneratorSettings(context.ClassName, context.Namespace)); 36 | 37 | var code = generator.GenerateFile(); 38 | return Result.Ok(code); 39 | } 40 | catch (Exception e) 41 | { 42 | return Result.Error(e); 43 | } 44 | } 45 | 46 | /// 47 | /// Retreives Open API document for json or yaml schema definition 48 | /// 49 | /// Path to the file with Open API document 50 | /// 51 | protected abstract Task GetOpenApiDocumentAsync(string filePath); 52 | 53 | private CSharpControllerGeneratorSettings CreateControllerGeneratorSettings(string className, string classesNamespace) 54 | { 55 | return new CSharpControllerGeneratorSettings 56 | { 57 | ClassName = className, 58 | CSharpGeneratorSettings = 59 | { 60 | Namespace = classesNamespace, 61 | SchemaType = NJsonSchema.SchemaType.OpenApi3, 62 | GenerateDefaultValues = true, 63 | GenerateDataAnnotations = false 64 | }, 65 | ControllerStyle = NSwag.CodeGeneration.CSharp.Models.CSharpControllerStyle.Abstract, 66 | ControllerTarget = NSwag.CodeGeneration.CSharp.Models.CSharpControllerTarget.AspNetCore, 67 | GenerateOptionalParameters = true, 68 | GenerateModelValidationAttributes = true, 69 | RouteNamingStrategy = NSwag.CodeGeneration.CSharp.Models.CSharpControllerRouteNamingStrategy.None, 70 | UseActionResultType = true 71 | }; 72 | } 73 | 74 | private CSharpClientGeneratorSettings CreateClientGeneratorSettings(string classesNamespace) 75 | { 76 | return new CSharpClientGeneratorSettings() 77 | { 78 | CSharpGeneratorSettings = 79 | { 80 | Namespace = classesNamespace, 81 | SchemaType = NJsonSchema.SchemaType.OpenApi3, 82 | GenerateDefaultValues = true, 83 | GenerateDataAnnotations = false 84 | }, 85 | GenerateClientClasses = false, 86 | GenerateExceptionClasses = false, 87 | GenerateOptionalParameters = true 88 | }; 89 | } 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /Compentio.SourceApi/Compentio.SourceApi/Generators/GeneratorStrategyFactory.cs: -------------------------------------------------------------------------------- 1 | using Compentio.SourceApi.Context; 2 | using System.Collections.Generic; 3 | 4 | namespace Compentio.SourceApi.Generators 5 | { 6 | /// 7 | /// Code generator strategy factory that returns proper processor for yaml or json schema definitions 8 | /// 9 | internal static class GeneratorStrategyFactory 10 | { 11 | private readonly static Dictionary _strategies = new() 12 | { 13 | { OpenApiFileFormat.Json, new JsonGeneratorStrategy()}, 14 | { OpenApiFileFormat.Yaml, new YamlGeneratorStrategy() } 15 | }; 16 | 17 | /// 18 | /// Returns appropriate generator strategy based on open API schema type: json or yaml: 19 | /// 20 | /// Open API file info. File extension used to return appropriate strategy: 21 | /// 22 | internal static IGeneratorStrategy GetStrategy(IOpenApiFileContext context) 23 | { 24 | if (!_strategies.ContainsKey(context.FileFormat)) 25 | { 26 | return new JsonGeneratorStrategy(); 27 | } 28 | 29 | return _strategies[context.FileFormat]; 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Compentio.SourceApi/Compentio.SourceApi/Generators/JsonGeneratorStrategy.cs: -------------------------------------------------------------------------------- 1 | using NSwag; 2 | using System.Threading.Tasks; 3 | 4 | namespace Compentio.SourceApi.Generators 5 | { 6 | /// 7 | class JsonGeneratorStrategy : GeneratorStrategy 8 | { 9 | /// 10 | /// Retreives Open API document for json schema definition 11 | /// 12 | /// Path to the json file with Open API document 13 | /// 14 | protected override async Task GetOpenApiDocumentAsync(string filePath) 15 | { 16 | return await OpenApiDocument.FromFileAsync(filePath); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Compentio.SourceApi/Compentio.SourceApi/Generators/Result.cs: -------------------------------------------------------------------------------- 1 | using Compentio.SourceApi.Diagnostics; 2 | using Microsoft.CodeAnalysis; 3 | using Microsoft.CodeAnalysis.CSharp; 4 | using System; 5 | 6 | 7 | namespace Compentio.SourceApi.Generators 8 | { 9 | /// 10 | /// Result of API code generation 11 | /// 12 | interface IResult 13 | { 14 | /// 15 | /// Formatted controller and DTO's code 16 | /// 17 | string GeneratedCode { get; } 18 | /// 19 | /// Success flag of code generation process 20 | /// 21 | bool IsSuccess { get; } 22 | /// 23 | /// Warning or error that appeared during code generation process 24 | /// 25 | DiagnosticInfo Diagnostic { get; } 26 | } 27 | 28 | /// 29 | internal class Result : IResult 30 | { 31 | private readonly string _code = string.Empty; 32 | private readonly DiagnosticInfo _diagnostics; 33 | 34 | private Result(string code) 35 | { 36 | _code = code; 37 | } 38 | private Result(Exception exception) 39 | { 40 | _diagnostics = new DiagnosticInfo 41 | { 42 | DiagnosticDescriptor = SourceApiDescriptor.UnexpectedError, 43 | Exception = exception 44 | }; 45 | } 46 | internal static IResult Ok(string code) 47 | { 48 | return new Result(code); 49 | } 50 | internal static IResult Error(Exception exception) 51 | { 52 | return new Result(exception); 53 | } 54 | 55 | /// 56 | public string GeneratedCode => FormatCode(_code); 57 | 58 | /// 59 | public DiagnosticInfo Diagnostic => _diagnostics; 60 | 61 | /// 62 | public bool IsSuccess => _diagnostics is null; 63 | 64 | private string FormatCode(string code) 65 | { 66 | var tree = CSharpSyntaxTree.ParseText(code); 67 | var root = tree.GetRoot().NormalizeWhitespace(); 68 | return root.ToFullString(); 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /Compentio.SourceApi/Compentio.SourceApi/Generators/YamlGeneratorStrategy.cs: -------------------------------------------------------------------------------- 1 | using NSwag; 2 | using System.Threading.Tasks; 3 | 4 | namespace Compentio.SourceApi.Generators 5 | { 6 | /// 7 | class YamlGeneratorStrategy : GeneratorStrategy 8 | { 9 | /// 10 | /// Retreives Open API document for yaml schema definition 11 | /// 12 | /// Path to the yaml file with Open API document 13 | /// 14 | protected override async Task GetOpenApiDocumentAsync(string filePath) 15 | { 16 | return await OpenApiYamlDocument.FromFileAsync(filePath); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Aleksander Parchomenko 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SourceApi 2 | 3 | [![NuGet](http://img.shields.io/nuget/v/Compentio.SourceApi.svg)](https://www.nuget.org/packages/Compentio.SourceApi) 4 | ![Nuget](https://img.shields.io/nuget/dt/Compentio.SourceApi) 5 | ![GitHub](https://img.shields.io/github/license/alekshura/SourceApi) 6 | ![GitHub top language](https://img.shields.io/github/languages/top/alekshura/SourceApi) 7 | 8 | # Introduction 9 | Two different approaches for Web API implementation often used by development teams: `code first` and `API first`. 10 | During the `code first` approach Web API Controllers are implemented, Swagger/Open API libraries are added to the application and finnaly it deployed. 11 | Open API libraries actually adds a middlewares to application which serve Open API definitions, 12 | Swagger UI thus the clients can use this definitions to generate code or use test API using UI. 13 | 14 | In second, `API First` approach, API defined in `json` or `yaml` files using [Open API standard](https://swagger.io/specification/) first and after that 15 | server or client code, interfaces or DTO's are generated in application. 16 | 17 | This approach is technology agnostic: API can be disigned independently from technologies used in cloud native architecture with a wide tech stack, then 18 | shared between defferent teams (`Java`, `.NET`, `NodeJS`, `Frontend`, ect.) and ech team can decide about what has to be done with it: to generate only DTO's, or 19 | create base abstract controllers, with routes, documentation and DTO's or to generate client code for consume the API. 20 | 21 | `SourceApi` is a code generator that helps to use `API First` approach for .NET Core 3+ (also .NET 5+) Web API applications: 22 | during design time in Visual Studio IDE it generates abstract base Controllers classes and DTO's that can be used by developer to implement the target functionality. 23 | 24 | It is based on [Source Generators Additional File Transaformation](https://github.com/dotnet/roslyn/blob/main/docs/features/source-generators.cookbook.md#additional-file-transformation) feature 25 | where it is possible to be able to transform an external non-C# file into an equivalent C# representation. 26 | 27 | Rico Suter's [NSwag](https://github.com/RicoSuter/NSwag) is used underhood: 28 | - [CSharpControllerGenerator](https://github.com/RicoSuter/NSwag/wiki/CSharpControllerGenerator) is used for abstract base controllers code generation 29 | - [CSharpClientGenerator](https://github.com/RicoSuter/NSwag/wiki/CSharpClientGenerator) used for DTO's only code generation mode. 30 | 31 | # Installation 32 | Install using nuget package manager: 33 | 34 | ```console 35 | Install-Package Compentio.SourceApi 36 | ``` 37 | 38 | or `.NET CLI`: 39 | 40 | ```console 41 | dotnet add package Compentio.SourceApi 42 | ``` 43 | 44 | # How to use 45 | In basic and most simple scenario: add Open API definition file or files (`*.json` and `*.yaml` formats are supported) to you project as `AdditionalFiles`: 46 | 47 | >```xml 48 | > 49 | > 50 | > PreserveNewest 51 | > 52 | > 53 | > PreserveNewest 54 | > 55 | > 56 | 57 | or in file properties in Visual Studio: 58 | 59 | 60 | 61 | You will see generated abstract controllers in 62 | > Dependencies -> Analyzers -> Compentio.SourceApi > Compentio.SourceApi.Generator. 63 | 64 |

65 | 66 |

67 | 68 | >! For now use one Open API file per controller. [Open API Tags](https://swagger.io/docs/specification/grouping-operations-with-tags/) are not supported. 69 | 70 | Now you can use these base controllers during implementation of you Web API. The DTO's are generated, routes are defined, documentation for the API methods also used from 71 | Open API definitions: 72 | 73 | ```cs 74 | [ApiController] 75 | [ApiConventionType(typeof(DefaultApiConventions))] 76 | public class StoreController : StoreControllerBase 77 | { 78 | /// 79 | public override Task DeleteOrder([BindRequired] long orderId) 80 | { 81 | throw new NotImplementedException(); 82 | } 83 | 84 | /// 85 | public override Task>> GetInventory() 86 | { 87 | throw new NotImplementedException(); 88 | } 89 | 90 | /// 91 | public override Task> GetOrderById([BindRequired] long orderId) 92 | { 93 | throw new NotImplementedException(); 94 | } 95 | 96 | /// 97 | public override Task> PlaceOrder([BindRequired, FromBody] Order body) 98 | { 99 | throw new NotImplementedException(); 100 | } 101 | } 102 | ``` 103 | 104 | >! You need to add `` tag to show documentation from base class in Swagger. 105 | 106 | And example of generated code for base controller class: 107 | 108 | ```cs 109 | 110 | //---------------------- 111 | // 112 | // Generated using the NSwag toolchain v13.13.2.0 (NJsonSchema v10.5.2.0 (Newtonsoft.Json v12.0.0.2)) (http://NSwag.org) 113 | // 114 | //---------------------- 115 | #pragma warning disable 108 // Disable "CS0108 '{derivedDto}.ToJson()' hides inherited member '{dtoBase}.ToJson()'. Use the new keyword if hiding was intended." 116 | 117 | #pragma warning disable 114 // Disable "CS0114 '{derivedDto}.RaisePropertyChanged(String)' hides inherited member 'dtoBase.RaisePropertyChanged(String)'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword." 118 | 119 | #pragma warning disable 472 // Disable "CS0472 The result of the expression is always 'false' since a value of type 'Int32' is never equal to 'null' of type 'Int32?' 120 | 121 | #pragma warning disable 1573 // Disable "CS1573 Parameter '...' has no matching param tag in the XML comment for ... 122 | 123 | #pragma warning disable 1591 // Disable "CS1591 Missing XML comment for publicly visible type or member ..." 124 | 125 | #pragma warning disable 8073 // Disable "CS8073 The result of the expression is always 'false' since a value of type 'T' is never equal to 'null' of type 'T?'" 126 | 127 | #pragma warning disable 3016 // Disable "CS3016 Arrays as attribute arguments is not CLS-compliant" 128 | 129 | namespace Compentio.SourceApi.WebExample.Controllers 130 | { 131 | using System = global::System; 132 | 133 | [System.CodeDom.Compiler.GeneratedCode("NSwag", "13.13.2.0 (NJsonSchema v10.5.2.0 (Newtonsoft.Json v12.0.0.2))")] 134 | [Microsoft.AspNetCore.Mvc.Route("api/v1")] 135 | public abstract class StoreControllerBase : Microsoft.AspNetCore.Mvc.ControllerBase 136 | { 137 | /// Returns pet inventories by status 138 | /// successful operation 139 | [Microsoft.AspNetCore.Mvc.HttpGet, Microsoft.AspNetCore.Mvc.Route("store/inventory")] 140 | public abstract System.Threading.Tasks.Task>> GetInventory(); 141 | /// Place an order for a pet 142 | /// order placed for purchasing the pet 143 | /// successful operation 144 | [Microsoft.AspNetCore.Mvc.HttpPost, Microsoft.AspNetCore.Mvc.Route("store/order")] 145 | public abstract System.Threading.Tasks.Task> PlaceOrder([Microsoft.AspNetCore.Mvc.FromBody][Microsoft.AspNetCore.Mvc.ModelBinding.BindRequired] Order body); 146 | /// Find purchase order by ID 147 | /// ID of pet that needs to be fetched 148 | /// successful operation 149 | [Microsoft.AspNetCore.Mvc.HttpGet, Microsoft.AspNetCore.Mvc.Route("store/order/{orderId}")] 150 | public abstract System.Threading.Tasks.Task> GetOrderById([Microsoft.AspNetCore.Mvc.ModelBinding.BindRequired] long orderId); 151 | /// Delete purchase order by ID 152 | /// ID of the order that needs to be deleted 153 | [Microsoft.AspNetCore.Mvc.HttpDelete, Microsoft.AspNetCore.Mvc.Route("store/order/{orderId}")] 154 | public abstract System.Threading.Tasks.Task DeleteOrder([Microsoft.AspNetCore.Mvc.ModelBinding.BindRequired] long orderId); 155 | } 156 | 157 | [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.5.2.0 (Newtonsoft.Json v12.0.0.2)")] 158 | public partial class Order 159 | { 160 | [Newtonsoft.Json.JsonProperty("id", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] 161 | public long Id { get; set; } 162 | 163 | [Newtonsoft.Json.JsonProperty("petId", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] 164 | public long PetId { get; set; } 165 | 166 | [Newtonsoft.Json.JsonProperty("quantity", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] 167 | public int Quantity { get; set; } 168 | 169 | [Newtonsoft.Json.JsonProperty("shipDate", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] 170 | public System.DateTimeOffset ShipDate { get; set; } 171 | 172 | /// Order Status 173 | [Newtonsoft.Json.JsonProperty("status", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] 174 | [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] 175 | public OrderStatus Status { get; set; } 176 | 177 | [Newtonsoft.Json.JsonProperty("complete", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] 178 | public bool Complete { get; set; } = false; 179 | } 180 | 181 | [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.5.2.0 (Newtonsoft.Json v12.0.0.2)")] 182 | public enum OrderStatus 183 | { 184 | [System.Runtime.Serialization.EnumMember(Value = @"placed")] 185 | Placed = 0, 186 | [System.Runtime.Serialization.EnumMember(Value = @"approved")] 187 | Approved = 1, 188 | [System.Runtime.Serialization.EnumMember(Value = @"delivered")] 189 | Delivered = 2, 190 | } 191 | } 192 | #pragma warning restore 1591 193 | #pragma warning restore 1573 194 | #pragma warning restore 472 195 | #pragma warning restore 114 196 | #pragma warning restore 108 197 | #pragma warning restore 3016 198 | 199 | ``` 200 | > The default namespace here is concatenation of you project name and directory of Open API definitions. 201 | > To change namespace see `Configuration` 202 | 203 | # Configuration 204 | 205 | To customize the generated code and override defaults `SourceApi` 206 | [consumes MSBuild properties and metadata](https://github.com/dotnet/roslyn/blob/main/docs/features/source-generators.cookbook.md#consume-msbuild-properties-and-metadata). 207 | 208 | Two configuration properies you can dafine in `*.cproj` file to customize SourceApi generator: 209 | - SourceApi_GeneratorNamespace - you can define namespace for generated classes 210 | - SourceApi_GenerateOnlyContracts - you can generate only DTO's without Controller base classes. 211 | 212 | >In a case if properties are not added, default values are used: `SourceApi_GenerateOnlyContracts` is set to `False` and for `SourceApi_GeneratorNamespace` 213 | >concatenation of you project name and directory of Open API definitions is used 214 | 215 | For global configuration (used for all added Open API files) define these parameters in ` section: 216 | 217 | ```xml 218 | 219 | net5.0 220 | true 221 | $(NoWarn);1591 222 | ... 223 | Compentio.SourceApi.WebExample.Controllers 224 | false 225 | 226 | ``` 227 | 228 | 229 | You can also define these parameters per file in ``: 230 | 231 | ```xml 232 | 233 | 234 | 235 | 236 | 237 | 238 | ``` 239 | 240 | Here in a case global configuration exists, for `Pets.yaml` global config is used, for `Store.yaml` namespace is overriden and for `Users.yaml` 241 | `SourceApi_GeneratorNamespace` and `SourceApi_GenerateOnlyContracts` are overriden. 242 | 243 | --------------------------------------------------------------------------------