├── .github └── workflows │ ├── codeql-analysis.yml │ └── publish.yml ├── .gitignore ├── CODE_OF_CONDUCT.md ├── Compentio.Assets └── Logo.png ├── Compentio.SourceConfig ├── .editorconfig ├── Compentio.SourceConfig.App │ ├── Appsettings.Development.json │ ├── Appsettings.json │ ├── Compentio.SourceConfig.App.csproj │ ├── Config │ │ └── Statuses.json │ ├── Dto │ │ └── NoteDto.cs │ ├── Program.cs │ └── Services │ │ └── NotesService.cs ├── Compentio.SourceConfig.Generator │ ├── Compentio.SourceConfig.csproj │ ├── Context │ │ ├── ConfigurationContext.cs │ │ └── ConfigurationFileContext.cs │ ├── Extensions │ │ └── FormatingExtensions.cs │ ├── Generator.cs │ └── Generators │ │ └── ICodeGenerator.cs └── Compentio.SourceConfig.sln ├── LICENSE └── README.md /.github/workflows/codeql-analysis.yml: -------------------------------------------------------------------------------- 1 | # For most projects, this workflow file will not need changing; you simply need 2 | # to commit it to your repository. 3 | # 4 | # You may wish to alter this file to override the set of languages analyzed, 5 | # or to provide custom queries or build logic. 6 | # 7 | # ******** NOTE ******** 8 | # We have attempted to detect the languages in your repository. Please check 9 | # the `language` matrix defined below to confirm you have the correct set of 10 | # supported CodeQL languages. 11 | # 12 | name: "CodeQL" 13 | 14 | on: 15 | push: 16 | branches: [ main ] 17 | pull_request: 18 | # The branches below must be a subset of the branches above 19 | branches: [ main ] 20 | schedule: 21 | - cron: '31 19 * * 5' 22 | 23 | jobs: 24 | analyze: 25 | name: Analyze 26 | runs-on: ubuntu-latest 27 | permissions: 28 | actions: read 29 | contents: read 30 | security-events: write 31 | 32 | strategy: 33 | fail-fast: false 34 | matrix: 35 | language: [ 'csharp' ] 36 | # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ] 37 | # Learn more: 38 | # https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed 39 | 40 | steps: 41 | - name: Checkout repository 42 | uses: actions/checkout@v2 43 | 44 | # Initializes the CodeQL tools for scanning. 45 | - name: Initialize CodeQL 46 | uses: github/codeql-action/init@v1 47 | with: 48 | languages: ${{ matrix.language }} 49 | # If you wish to specify custom queries, you can do so here or in a config file. 50 | # By default, queries listed here will override any specified in a config file. 51 | # Prefix the list here with "+" to use these queries and those in the config file. 52 | # queries: ./path/to/local/query, your-org/your-repo/queries@main 53 | 54 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). 55 | # If this step fails, then you should remove it and run the build manually (see below) 56 | - name: Autobuild 57 | uses: github/codeql-action/autobuild@v1 58 | 59 | # ℹ️ Command-line programs to run using the OS shell. 60 | # 📚 https://git.io/JvXDl 61 | 62 | # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines 63 | # and modify them (or add more) to build your code if your project 64 | # uses a compiled language 65 | 66 | #- run: | 67 | # make bootstrap 68 | # make release 69 | 70 | - name: Perform CodeQL Analysis 71 | uses: github/codeql-action/analyze@v1 72 | -------------------------------------------------------------------------------- /.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.SourceConfig/Compentio.SourceConfig.Generator/Compentio.SourceConfig.csproj 27 | 28 | # NuGet package id, used for version detection & defaults to project name 29 | PACKAGE_NAME: Compentio.SourceConfig 30 | 31 | # Filepath with version info, relative to root of repository & defaults to PROJECT_FILE_PATH 32 | VERSION_FILE_PATH: Compentio.SourceConfig/Compentio.SourceConfig.Generator/Compentio.SourceConfig.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 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | * Demonstrating empathy and kindness toward other people 21 | * Being respectful of differing opinions, viewpoints, and experiences 22 | * Giving and gracefully accepting constructive feedback 23 | * Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | * Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | * The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | * Trolling, insulting or derogatory comments, and personal or political attacks 33 | * Public or private harassment 34 | * Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | * Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | aleksander.parkhomenko@compent.io. 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.0, available at 119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 120 | 121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct 122 | enforcement ladder](https://github.com/mozilla/diversity). 123 | 124 | [homepage]: https://www.contributor-covenant.org 125 | 126 | For answers to common questions about this code of conduct, see the FAQ at 127 | https://www.contributor-covenant.org/faq. Translations are available at 128 | https://www.contributor-covenant.org/translations. 129 | -------------------------------------------------------------------------------- /Compentio.Assets/Logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alekshura/SourceConfig/e32039ce54c3817ba1da7f79526de2c15c7ea54d/Compentio.Assets/Logo.png -------------------------------------------------------------------------------- /Compentio.SourceConfig/.editorconfig: -------------------------------------------------------------------------------- 1 | [*.cs] 2 | 3 | # CS8604: Possible null reference argument. 4 | dotnet_diagnostic.CS8604.severity = none 5 | -------------------------------------------------------------------------------- /Compentio.SourceConfig/Compentio.SourceConfig.App/Appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "ConnectionTimeout": "300", 3 | "DatabaseSize": "200" 4 | } -------------------------------------------------------------------------------- /Compentio.SourceConfig/Compentio.SourceConfig.App/Appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$NoteEmailAddresses": [ 3 | "admin@test.com", 4 | "technical.admin@test.com", 5 | "business.admin@test.com" 6 | ], 7 | "ConnectionTimeout": "30", 8 | "ConnectionHost": "https://test.com", //TODO 9 | "DefaultNote": { 10 | "Title": "DefaultTitle", 11 | "Description": "DefaultDescription" 12 | } 13 | } -------------------------------------------------------------------------------- /Compentio.SourceConfig/Compentio.SourceConfig.App/Compentio.SourceConfig.App.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net5.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | PreserveNewest 17 | 18 | 19 | PreserveNewest 20 | 21 | 22 | PreserveNewest 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | Never 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /Compentio.SourceConfig/Compentio.SourceConfig.App/Config/Statuses.json: -------------------------------------------------------------------------------- 1 | { 2 | "Status": [ 3 | "Pending", 4 | "Realized", 5 | "Rejected" 6 | ] 7 | } -------------------------------------------------------------------------------- /Compentio.SourceConfig/Compentio.SourceConfig.App/Dto/NoteDto.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics.CodeAnalysis; 2 | 3 | namespace Compentio.SourceConfig.App.Dto 4 | { 5 | [ExcludeFromCodeCoverage] 6 | public record NoteDto 7 | { 8 | public long Id { get; set; } 9 | public string Title { get; set; } 10 | public string Description { get; set; } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Compentio.SourceConfig/Compentio.SourceConfig.App/Program.cs: -------------------------------------------------------------------------------- 1 | using Compentio.SourceConfig.App.Services; 2 | using Microsoft.Extensions.Configuration; 3 | using Microsoft.Extensions.DependencyInjection; 4 | using Microsoft.Extensions.Hosting; 5 | using System; 6 | using System.Diagnostics.CodeAnalysis; 7 | using System.Threading.Tasks; 8 | 9 | namespace Compentio.SourceConfig.App 10 | { 11 | [ExcludeFromCodeCoverage] 12 | class Program 13 | { 14 | static async Task Main(string[] args) 15 | { 16 | using IHost host = CreateHostBuilder(args).Build(); 17 | using IServiceScope serviceScope = host.Services.CreateScope(); 18 | var notesService = serviceScope.ServiceProvider.GetRequiredService(); 19 | var result = notesService.GetNote(1); 20 | Console.WriteLine($"Note: '{result}'"); 21 | Console.ReadKey(); 22 | await host.RunAsync(); 23 | } 24 | 25 | static IHostBuilder CreateHostBuilder(string[] args) 26 | { 27 | var configuration = new ConfigurationBuilder() 28 | .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) 29 | .AddEnvironmentVariables() 30 | .Build(); 31 | 32 | return Host.CreateDefaultBuilder(args) 33 | .ConfigureServices((_, services) => 34 | services 35 | .Configure(configuration) 36 | .AddTransient()); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Compentio.SourceConfig/Compentio.SourceConfig.App/Services/NotesService.cs: -------------------------------------------------------------------------------- 1 | using Compentio.SourceConfig.App.Dto; 2 | using Microsoft.Extensions.Configuration; 3 | using System.Diagnostics.CodeAnalysis; 4 | 5 | namespace Compentio.SourceConfig.App.Services 6 | { 7 | public interface INotesService 8 | { 9 | NoteDto GetNote(long noteId); 10 | } 11 | 12 | [ExcludeFromCodeCoverage] 13 | public class NotesService : INotesService 14 | { 15 | private readonly IConfiguration _configuration; 16 | 17 | public NotesService(IConfiguration configuration) 18 | { 19 | _configuration = configuration; 20 | } 21 | 22 | 23 | public NoteDto GetNote(long noteId) 24 | { 25 | var appSettings = _configuration.Get(); 26 | 27 | return new NoteDto 28 | { 29 | Id = noteId, 30 | Description = appSettings.DefaultNote.Description, 31 | Title = appSettings.DefaultNote.Title 32 | }; 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Compentio.SourceConfig/Compentio.SourceConfig.Generator/Compentio.SourceConfig.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | all 7 | runtime; build; native; contentfiles; analyzers; buildtransitive 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | True 24 | 25 | 26 | 27 | 28 | 29 | 30 | netstandard2.0 31 | 9.0 32 | true 33 | enable 34 | 1.0.14 35 | Code generator for objects that are based on *.json configuration files: when developer adds some file or new properties to existng json configuration file the POCO objects for this configuration generated. 36 | Logo.png 37 | 38 | https://github.com/alekshura/SourceConfig 39 | CodeGenerator, Configuration 40 | Copyright (c) @alekshura Compentio 2021 41 | Aleksander Parchomenko 42 | Compentio 43 | MIT 44 | https://github.com/alekshura/SourceConfig 45 | Compentio.SourceConfig 46 | Compentio.SourceConfig 47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /Compentio.SourceConfig/Compentio.SourceConfig.Generator/Context/ConfigurationContext.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.CodeAnalysis; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | 5 | namespace Compentio.SourceConfig.Context 6 | { 7 | /// 8 | /// Contains for overall configurations that defined in json files in application 9 | /// 10 | interface IConfigurationContext 11 | { 12 | /// 13 | /// Collection of configuration files information 14 | /// 15 | IEnumerable Context { get; } 16 | } 17 | 18 | /// 19 | class ConfigurationContext : IConfigurationContext 20 | { 21 | private readonly GeneratorExecutionContext _generatorExecutionContext; 22 | private readonly IList _configFilesContext; 23 | 24 | public static IConfigurationContext CreateFromExecutionContext(GeneratorExecutionContext generatorExecutionContext) => new ConfigurationContext(generatorExecutionContext); 25 | 26 | private ConfigurationContext(GeneratorExecutionContext generatorExecutionContext) 27 | { 28 | _generatorExecutionContext = generatorExecutionContext; 29 | _configFilesContext = new List(); 30 | LoadConfigFiles(_configFilesContext); 31 | } 32 | 33 | /// 34 | public IEnumerable Context => _configFilesContext; 35 | 36 | private void LoadConfigFiles(IList configFilesContext) 37 | { 38 | foreach (var configFile in _generatorExecutionContext.AdditionalFiles.Where(file => file.Path.EndsWith(".json"))) 39 | { 40 | var content = configFile.GetText()?.ToString(); 41 | if (!string.IsNullOrEmpty(content)) 42 | { 43 | var fileContext = new ConfigurationFileContext(configFile.Path, _generatorExecutionContext.Compilation?.AssemblyName, content); 44 | var fileToMerge = configFilesContext.FirstOrDefault(file => file.ShouldBeMerged(configFile.Path)); 45 | if (fileToMerge is not null) 46 | { 47 | Merge(fileToMerge.FileContent, fileContext.FileContent); 48 | } 49 | else 50 | { 51 | configFilesContext.Add(fileContext); 52 | } 53 | } 54 | } 55 | } 56 | 57 | private void Merge(Dictionary result, Dictionary source) 58 | { 59 | foreach (var entry in source) 60 | { 61 | if (!result.ContainsKey(entry.Key)) 62 | { 63 | result.Add(entry.Key, entry.Value); 64 | } 65 | else 66 | { 67 | if (entry.Value is Dictionary existing) 68 | { 69 | int numberOfValuesInExistingObject = existing.Count; 70 | var numberOfValuesInNewObject = ((Dictionary)result[entry.Key]).Count; 71 | 72 | if (numberOfValuesInExistingObject < numberOfValuesInNewObject) 73 | { 74 | result[entry.Key] = entry.Value; 75 | Merge((Dictionary)result[entry.Key], (Dictionary)entry.Value); 76 | } 77 | } 78 | } 79 | } 80 | } 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /Compentio.SourceConfig/Compentio.SourceConfig.Generator/Context/ConfigurationFileContext.cs: -------------------------------------------------------------------------------- 1 | using Compentio.SourceConfig.Extensions; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.IO; 5 | using System.Linq; 6 | using System.Text.Json; 7 | 8 | namespace Compentio.SourceConfig.Context 9 | { 10 | /// 11 | /// Contains information about one configuration file in the application 12 | /// 13 | interface IConfigurationFileContext 14 | { 15 | /// 16 | /// Filename of generated POCO file. It is always has *.cs extension. 17 | /// 18 | string FileName { get; } 19 | /// 20 | /// Generated class name 21 | /// 22 | string ClassName { get; } 23 | /// 24 | /// Namespace of generated class. It is concatenation of main application namespaca and directories of configuration files. 25 | /// 26 | string Namespace { get; } 27 | /// 28 | /// Indicated when files should be merged. It is used, when there two or more configuration files defined for different environments: 29 | /// appsettings.json or appsettings.development.json etc. 30 | /// 31 | /// Path to another file that checked for merging 32 | /// Flag if two files should be merged 33 | bool ShouldBeMerged(string filePath); 34 | /// 35 | /// Deserialized to dictionary content of json file 36 | /// 37 | Dictionary FileContent { get; set; } 38 | /// 39 | /// List of top properties in a file 40 | /// 41 | IList> MainProperties { get; } 42 | /// 43 | /// List of objects (non primitives) from configuration file 44 | /// 45 | IList> ConfigClasses { get; } 46 | } 47 | 48 | /// 49 | class ConfigurationFileContext : IConfigurationFileContext 50 | { 51 | private Dictionary _fileContent; 52 | private readonly string _filePath; 53 | private readonly string _assemblyName; 54 | 55 | public ConfigurationFileContext(string filePath, string assemblyName, string fileContent) 56 | { 57 | _filePath = filePath; 58 | _fileContent = Deserialize(fileContent); 59 | _assemblyName = assemblyName; 60 | } 61 | 62 | /// 63 | public string ClassName => FormatClassName(Path.GetFileNameWithoutExtension(_filePath)); 64 | 65 | /// 66 | public string FileName => $"{ClassName}.cs"; 67 | 68 | /// 69 | public IList> MainProperties => _fileContent 70 | .Where(dict => !(dict.Value is Dictionary)) 71 | .ToList(); 72 | 73 | /// 74 | public IList> ConfigClasses => _fileContent.Except(MainProperties) 75 | .ToList(); 76 | 77 | /// 78 | public Dictionary FileContent 79 | { 80 | get => _fileContent; 81 | set => _fileContent = value; 82 | } 83 | 84 | /// 85 | public string Namespace 86 | { 87 | get 88 | { 89 | var assemlyRootDirectory = _filePath.Split(new string[] { _assemblyName }, StringSplitOptions.RemoveEmptyEntries)[1]; 90 | var namespaceName = string.Empty; 91 | foreach (var item in assemlyRootDirectory.Split(Path.DirectorySeparatorChar).Where(item => !string.IsNullOrWhiteSpace(item))) 92 | { 93 | if (item != Path.GetFileName(_filePath)) 94 | namespaceName += $".{item}"; 95 | } 96 | 97 | return $"{_assemblyName}{namespaceName}"; 98 | } 99 | } 100 | 101 | /// 102 | public bool ShouldBeMerged(string filePath) 103 | { 104 | var sourceFileName = Path.GetFileNameWithoutExtension(_filePath); 105 | var targetFileName = Path.GetFileNameWithoutExtension(filePath); 106 | var sorceOrigin = sourceFileName.Split('.')[0]; 107 | var targetOrigin = targetFileName.Split('.')[0]; 108 | return sorceOrigin.Equals(targetOrigin, StringComparison.InvariantCultureIgnoreCase); 109 | } 110 | 111 | private string FormatClassName(string className) 112 | { 113 | var originName = className.Split('.').Where(item => !string.IsNullOrWhiteSpace(item)).First(); 114 | return originName.FromatClassName(); 115 | } 116 | 117 | private Dictionary Deserialize(string content) 118 | { 119 | var jsonSerializerOptions = new JsonSerializerOptions 120 | { 121 | ReadCommentHandling = JsonCommentHandling.Skip 122 | }; 123 | 124 | var configValues = JsonSerializer.Deserialize>(content, jsonSerializerOptions); 125 | var result = new Dictionary(); 126 | 127 | if (configValues is null) 128 | return result; 129 | 130 | foreach (var configValue in configValues) 131 | { 132 | if (configValue.Value.ValueKind is JsonValueKind.Object) 133 | { 134 | result.Add(configValue.Key, Deserialize(configValue.Value.ToString())); 135 | } 136 | else 137 | { 138 | result.Add(configValue.Key, configValue.Value); 139 | } 140 | } 141 | 142 | return result; 143 | } 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /Compentio.SourceConfig/Compentio.SourceConfig.Generator/Extensions/FormatingExtensions.cs: -------------------------------------------------------------------------------- 1 | namespace Compentio.SourceConfig.Extensions 2 | { 3 | /// 4 | /// Helper extensions used for objects formattings 5 | /// 6 | static class FormatingExtensions 7 | { 8 | /// 9 | /// Builds class name with using of Pascal case for settings file name. 10 | /// 11 | /// File name 12 | /// 13 | public static string FromatClassName(this string input) 14 | { 15 | return ToPascalCase(input).Replace("settings", "Settings"); 16 | } 17 | 18 | /// 19 | /// Formats property name from settings file. It generates Pascal case names and replaces '.' and '$' characters from input string. 20 | /// 21 | /// Property name to be formatted 22 | /// 23 | public static string FromatPropertyName(this string input) 24 | { 25 | var underscore = "_"; 26 | var tmp = input 27 | .Replace(".", underscore) 28 | .Replace("$", underscore); 29 | 30 | if (tmp[0].Equals(underscore)) 31 | tmp.Replace(underscore, string.Empty); 32 | 33 | return ToPascalCase(tmp); 34 | } 35 | 36 | private static string ToPascalCase(string input) 37 | { 38 | if (string.IsNullOrWhiteSpace(input)) 39 | return string.Empty; 40 | 41 | if (input.Length == 1) 42 | return input.ToUpper(); 43 | 44 | return string.Concat(input[0].ToString().ToUpper(), input.Substring(1)); 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Compentio.SourceConfig/Compentio.SourceConfig.Generator/Generator.cs: -------------------------------------------------------------------------------- 1 | using Compentio.SourceConfig.Generators; 2 | using Compentio.SourceConfig.Context; 3 | using Microsoft.CodeAnalysis; 4 | using System.Diagnostics; 5 | 6 | namespace Compentio.SourceConfig 7 | { 8 | /// 9 | /// Main source generator 10 | /// 11 | [Generator] 12 | public class Generator : ISourceGenerator 13 | { 14 | public void Execute(GeneratorExecutionContext context) 15 | { 16 | var configurationContext= ConfigurationContext.CreateFromExecutionContext(context); 17 | 18 | foreach (var configFileContext in configurationContext.Context) 19 | { 20 | var generator = new CodeGenerator(configFileContext); 21 | context.AddSource(configFileContext.FileName, generator.GenerateSource()); 22 | } 23 | } 24 | 25 | public void Initialize(GeneratorInitializationContext context) 26 | { 27 | //#if DEBUG 28 | // if (!Debugger.IsAttached) 29 | // { 30 | // Debugger.Launch(); 31 | // } 32 | //#endif 33 | Debug.WriteLine($"'{typeof(Generator).FullName}' initalized."); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Compentio.SourceConfig/Compentio.SourceConfig.Generator/Generators/ICodeGenerator.cs: -------------------------------------------------------------------------------- 1 | using Compentio.SourceConfig.Context; 2 | using Compentio.SourceConfig.Extensions; 3 | using Microsoft.CodeAnalysis; 4 | using Microsoft.CodeAnalysis.CSharp; 5 | using Microsoft.CodeAnalysis.Text; 6 | using System; 7 | using System.Collections.Generic; 8 | using System.Diagnostics; 9 | using System.Linq; 10 | using System.Text; 11 | using System.Text.Json; 12 | 13 | namespace Compentio.SourceConfig.Generators 14 | { 15 | /// 16 | /// One class code generator 17 | /// 18 | interface ICodeGenerator 19 | { 20 | /// 21 | /// Generates configuration POCO object for one file 22 | /// 23 | /// Generated and formatted code 24 | SourceText GenerateSource(); 25 | } 26 | 27 | /// 28 | class CodeGenerator : ICodeGenerator 29 | { 30 | private readonly IConfigurationFileContext _configurationFileContext; 31 | 32 | public CodeGenerator(IConfigurationFileContext configurationFileContext) 33 | { 34 | _configurationFileContext = configurationFileContext; 35 | } 36 | 37 | /// 38 | public SourceText GenerateSource() 39 | { 40 | Debug.WriteLine($"Start generating sources for '{_configurationFileContext.ClassName}' class."); 41 | 42 | var configSectionClasses = new StringBuilder(); 43 | 44 | foreach (var configClass in _configurationFileContext.ConfigClasses) 45 | { 46 | BuildConfigClass(configClass, configSectionClasses); 47 | } 48 | 49 | var sourceBuilder = new StringBuilder($@" 50 | // 51 | // 52 | 53 | using System; 54 | using System.Collections.Generic; 55 | using System.Diagnostics.CodeAnalysis; 56 | 57 | namespace {_configurationFileContext.Namespace} 58 | {{ 59 | [ExcludeFromCodeCoverage] 60 | public class {_configurationFileContext.ClassName} 61 | {{ 62 | "); 63 | 64 | foreach (var item in _configurationFileContext.MainProperties) 65 | { 66 | var value = item.Value; 67 | var key = item.Key; 68 | 69 | if (value is JsonElement element && element.ValueKind == JsonValueKind.Array) 70 | { 71 | var propertyType = GetPropertyTypeName(element.EnumerateArray().FirstOrDefault()); 72 | sourceBuilder.Append($"public IEnumerable<{propertyType}> {key.FromatPropertyName()} {{ get; set; }}"); 73 | } 74 | else 75 | { 76 | sourceBuilder.Append($"public string {key.FromatPropertyName()} {{ get; set; }}"); 77 | } 78 | } 79 | 80 | foreach (var item in _configurationFileContext.ConfigClasses) 81 | { 82 | var key = item.Key; 83 | sourceBuilder.Append($"public {key.FromatPropertyName()} {key.FromatPropertyName()}{{ get; set; }}"); 84 | } 85 | 86 | sourceBuilder.Append("}"); 87 | sourceBuilder.Append(configSectionClasses.ToString()); 88 | sourceBuilder.Append("}"); 89 | 90 | var tree = CSharpSyntaxTree.ParseText(sourceBuilder.ToString()); 91 | 92 | Debug.WriteLine($"End generating sources for '{_configurationFileContext.ClassName}' class. Success!"); 93 | return SourceText.From(tree.GetRoot().NormalizeWhitespace().ToFullString(), Encoding.UTF8); 94 | } 95 | 96 | private void BuildConfigClass(KeyValuePair classInfo, StringBuilder stringBuilder) 97 | { 98 | var nestedClasses = new StringBuilder(); 99 | 100 | stringBuilder.Append("[ExcludeFromCodeCoverage]"); 101 | stringBuilder.Append($"public class {classInfo.Key.FromatClassName()}"); 102 | stringBuilder.Append("{"); 103 | 104 | foreach (var item in (Dictionary)classInfo.Value) 105 | { 106 | if (item.Value is Dictionary) 107 | { 108 | stringBuilder.Append($"public {item.Key} {item.Key.FromatPropertyName()} {{ get; set; }}"); 109 | BuildConfigClass(item, nestedClasses); 110 | } 111 | else 112 | { 113 | var prop = (JsonElement)item.Value; 114 | var propertyType = GetPropertyTypeName(prop); 115 | if (prop.ValueKind == JsonValueKind.Array) 116 | { 117 | stringBuilder.Append($"public IEnumerable<{propertyType}> {item.Key.FromatPropertyName()} {{ get; set; }}"); 118 | } 119 | else 120 | { 121 | stringBuilder.Append($"public {propertyType} {item.Key.FromatPropertyName()} {{ get; set; }}"); 122 | } 123 | } 124 | } 125 | 126 | stringBuilder.Append("}"); 127 | stringBuilder.AppendLine(nestedClasses.ToString()); 128 | } 129 | 130 | private string GetPropertyTypeName(JsonElement value) 131 | { 132 | return value.ValueKind switch 133 | { 134 | JsonValueKind.Number => "int", 135 | JsonValueKind.True or JsonValueKind.False => "bool", 136 | _ => "string", 137 | }; 138 | } 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /Compentio.SourceConfig/Compentio.SourceConfig.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("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Compentio.SourceConfig.App", "Compentio.SourceConfig.App\Compentio.SourceConfig.App.csproj", "{7786FADC-84C5-497F-A65D-DA226447D0C7}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Compentio.SourceConfig", "Compentio.SourceConfig.Generator\Compentio.SourceConfig.csproj", "{6B7251EC-671F-426A-A3D0-1F6E9A9893D8}" 9 | EndProject 10 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{E64FBD47-C288-4CE7-9D71-79422F54B44D}" 11 | ProjectSection(SolutionItems) = preProject 12 | .editorconfig = .editorconfig 13 | EndProjectSection 14 | EndProject 15 | Global 16 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 17 | Debug|Any CPU = Debug|Any CPU 18 | Release|Any CPU = Release|Any CPU 19 | EndGlobalSection 20 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 21 | {7786FADC-84C5-497F-A65D-DA226447D0C7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 22 | {7786FADC-84C5-497F-A65D-DA226447D0C7}.Debug|Any CPU.Build.0 = Debug|Any CPU 23 | {7786FADC-84C5-497F-A65D-DA226447D0C7}.Release|Any CPU.ActiveCfg = Release|Any CPU 24 | {7786FADC-84C5-497F-A65D-DA226447D0C7}.Release|Any CPU.Build.0 = Release|Any CPU 25 | {6B7251EC-671F-426A-A3D0-1F6E9A9893D8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 26 | {6B7251EC-671F-426A-A3D0-1F6E9A9893D8}.Debug|Any CPU.Build.0 = Debug|Any CPU 27 | {6B7251EC-671F-426A-A3D0-1F6E9A9893D8}.Release|Any CPU.ActiveCfg = Release|Any CPU 28 | {6B7251EC-671F-426A-A3D0-1F6E9A9893D8}.Release|Any CPU.Build.0 = Release|Any CPU 29 | EndGlobalSection 30 | GlobalSection(SolutionProperties) = preSolution 31 | HideSolutionNode = FALSE 32 | EndGlobalSection 33 | GlobalSection(ExtensibilityGlobals) = postSolution 34 | SolutionGuid = {232ABAA2-FA64-4A02-83C6-5494446B3AF0} 35 | EndGlobalSection 36 | EndGlobal 37 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Aleksander Parchomenko http://compent.io 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 | # SourceConfig 2 | 3 | 4 | [![NuGet](http://img.shields.io/nuget/v/Compentio.SourceConfig.svg)](https://www.nuget.org/packages/Compentio.SourceConfig) 5 | ![Nuget](https://img.shields.io/nuget/dt/Compentio.SourceConfig) 6 | ![GitHub](https://img.shields.io/github/license/alekshura/SourceConfig) 7 | ![GitHub top language](https://img.shields.io/github/languages/top/alekshura/SourceConfig) 8 | 9 | # Introduction 10 | `SourceConfig` is a code generator for objects that are built on `*.json` configuration files: 11 | when developer adds some file or new properties to existng json configuration file the POCO objects for this configuration generated. 12 | 13 | It is based on [Source Generators](https://github.com/dotnet/roslyn/blob/main/docs/features/source-generators.md) feature 14 | that has been intoduced with `C# 9.0` and brings a possibility to generate code during build time. 15 | 16 | 17 | # Installation 18 | Install using nuget package manager: 19 | 20 | ```console 21 | Install-Package Compentio.SourceConfig 22 | ``` 23 | 24 | or `.NET CLI`: 25 | 26 | ```console 27 | dotnet add package Compentio.SourceConfig 28 | ``` 29 | 30 | # How to use 31 | During creation of any `*json` file (any `json` files are treated as configuration files), e.g. `apsetting.json` 32 | the POCO representation of this json is generated: 33 | 34 | ```json 35 | { 36 | "NoteEmailAddresses": [ 37 | "admin@test.com", 38 | "technical.admin@test.com", 39 | "business.admin@test.com" 40 | ], 41 | "ConnectionTimeout": "30", 42 | "ConnectionHost": "https://test.com", 43 | "DefaultNote": { 44 | "Title": "DefaultTitle", 45 | "Description": "DefaultDescription" 46 | } 47 | } 48 | ``` 49 | in that case `SourceConfig` generates 50 | 51 | ```cs 52 | // 53 | // 54 | using System; 55 | using System.Collections.Generic; 56 | 57 | namespace Compentio.SourceConfig.App 58 | { 59 | public class AppSettings 60 | { 61 | public IEnumerable NoteEmailAddresses { get; set; } 62 | 63 | public string ConnectionTimeout { get; set; } 64 | 65 | public string ConnectionHost { get; set; } 66 | 67 | public string DatabaseSize { get; set; } 68 | 69 | public DefaultNote DefaultNote { get; set; } 70 | } 71 | 72 | public class DefaultNote 73 | { 74 | public string Title { get; set; } 75 | 76 | public string Description { get; set; } 77 | } 78 | } 79 | ``` 80 | `AppSettings` is taken from the filename, `Compentio.SourceConfig.App` namespace is inherited from configuration file directory (here, `appsettings.json` is in app root directory, thus main app namespace is used). 81 | 82 | >To enable processing `json` files, in `*.cproj` project the configs should be marked as `AdditionalFiles`: 83 | >```xml 84 | > 85 | > 86 | > PreserveNewest 87 | > 88 | > 89 | > PreserveNewest 90 | > 91 | > 92 | 93 | If there are few `appsettings` files used for different environments, e.g. `appsettings.development.json` or `appsettings.production.json` etc. 94 | they are merged into one generated class. Merge is based on first prefix in filename - here is `appsettings`. 95 | 96 | Now generated class can be used to retreive the configuration: 97 | 98 | ```cs 99 | var appSettings = _configuration.Get(); 100 | ``` 101 | and should be earlier added to container: 102 | 103 | ```cs 104 | static IHostBuilder CreateHostBuilder(string[] args) 105 | { 106 | var configuration = new ConfigurationBuilder() 107 | .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) 108 | .AddEnvironmentVariables() 109 | .Build(); 110 | 111 | return Host.CreateDefaultBuilder(args) 112 | .ConfigureServices((_, services) => 113 | services 114 | .Configure(configuration) 115 | .AddTransient()); 116 | } 117 | ``` 118 | 119 | --------------------------------------------------------------------------------