├── .gitignore ├── LICENSE ├── README.md ├── af-userapi.sln ├── af-userapi ├── .gitignore ├── BaseFunction.cs ├── GlobalUsing.cs ├── Properties │ ├── serviceDependencies.json │ └── serviceDependencies.local.json ├── Startup.cs ├── UserAPI.cs ├── af-userapi.csproj └── host.json ├── user.application ├── Common │ ├── BaseClass │ │ └── ApplicationBase.cs │ ├── Behaviors │ │ ├── UnhandledExceptionBehaviour.cs │ │ └── ValidationBehaviour.cs │ ├── DTO │ │ └── UserDTO.cs │ ├── Exceptions │ │ ├── NotFoundException.cs │ │ └── ValidationException.cs │ ├── Interfaces │ │ └── IConfigConstants.cs │ ├── Mappings │ │ ├── IMapFrom.cs │ │ └── MappingProfile.cs │ └── VM │ │ └── UserVM.cs ├── GlobalUsing.cs ├── RegisterService.cs ├── User │ ├── Commands │ │ ├── AddUserCommand.cs │ │ ├── AddUserCommandValidator.cs │ │ ├── UpdateUserCommand.cs │ │ ├── UpdateUserCommandValidator.cs │ │ └── UpdateUserStatusCommand.cs │ └── Queries │ │ ├── GetAllUserQuery.cs │ │ ├── GetSingleUserQuery.cs │ │ └── GetSingleUserQueryValidator.cs └── user.application.csproj ├── user.domain ├── Entities │ ├── Audit.cs │ ├── BaseEntity.cs │ └── User.cs ├── Enum │ └── Enum.cs ├── Exceptions │ ├── EntityAlreadyExistsException.cs │ ├── EntityNotFoundException.cs │ └── InvalidCredentialsException.cs ├── GlobalUsing.cs ├── Interfaces │ └── Persistense │ │ ├── IAuditRepository.cs │ │ ├── IRepository.cs │ │ └── IUserRepository.cs ├── Specifications │ ├── AuditFilterSpecification.cs │ ├── Base │ │ └── CosmosDbSpecificationEvaluator.cs │ ├── Interfaces │ │ └── ISearchQuery.cs │ ├── UserGetAllSpecification.cs │ ├── UserGetSingleSpecification.cs │ ├── UserSearchAggregationSpecification.cs │ └── UserSearchSpecification.cs └── user.domain.csproj └── user.infrastructure ├── AppSettings └── CosmosDbSettings.cs ├── CosmosDbData ├── Constants │ └── ConfigConstants.cs ├── CosmosDbContainer.cs ├── CosmosDbContainerFactory.cs ├── Interfaces │ ├── IContainerContext.cs │ ├── ICosmosDbContainer.cs │ └── ICosmosDbContainerFactory.cs └── Repository │ ├── AuditRepository.cs │ ├── CosmosDbRepository.cs │ └── UserRepository.cs ├── GlobalUsing.cs ├── RegisterService.cs └── user.infrastructure.csproj /.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 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Fullstack Hub 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 | # HTTP Trigger Azure Function with CosmosDB Clean Architecture 2 | - In Azure Portal, Create new Azure CosmosDB account Go to Data 3 | Explorer, create new database "famspotdb" 4 | 5 | - Create two containers in database "Audit" (Partition Key: EntityId) 6 | and "User" (Partition Key: UserType & Unique Key: Email). 7 | 8 | - Go to "Keys" in "Settings" section, Get the "URI" and "PRIMARY KEY" and replace the values in af-userapi -> local.settings.json file's ConnectionString section. 9 | 10 | ``` 11 | "ConnectionStrings": { 12 | "FamspotDB": { 13 | "EndpointUrl": "https://XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX:443/", 14 | "PrimaryKey": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", 15 | "DatabaseName": "famspotdb", 16 | "Containers": [ 17 | { 18 | "Name": "Audit", 19 | "PartitionKey": "/EntityId" 20 | }, 21 | { 22 | "Name": "User", 23 | "PartitionKey": "/UserType" 24 | } 25 | ] 26 | } 27 | } 28 | ``` 29 | -------------------------------------------------------------------------------- /af-userapi.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.3.32929.385 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "af-userapi", "af-userapi\af-userapi.csproj", "{EFC6AA69-3AF2-43B4-AD4A-4460264074E6}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "user.application", "user.application\user.application.csproj", "{1EE45AAB-A601-4FD3-A65C-FF09EB1C76A0}" 9 | EndProject 10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "user.domain", "user.domain\user.domain.csproj", "{2804A3A5-3447-41B8-BD23-588306AB8ED1}" 11 | EndProject 12 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "user.infrastructure", "user.infrastructure\user.infrastructure.csproj", "{ACEB65ED-1EA7-449B-973B-192D380BB8FF}" 13 | EndProject 14 | Global 15 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 16 | Debug|Any CPU = Debug|Any CPU 17 | Release|Any CPU = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 20 | {EFC6AA69-3AF2-43B4-AD4A-4460264074E6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {EFC6AA69-3AF2-43B4-AD4A-4460264074E6}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {EFC6AA69-3AF2-43B4-AD4A-4460264074E6}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {EFC6AA69-3AF2-43B4-AD4A-4460264074E6}.Release|Any CPU.Build.0 = Release|Any CPU 24 | {1EE45AAB-A601-4FD3-A65C-FF09EB1C76A0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 25 | {1EE45AAB-A601-4FD3-A65C-FF09EB1C76A0}.Debug|Any CPU.Build.0 = Debug|Any CPU 26 | {1EE45AAB-A601-4FD3-A65C-FF09EB1C76A0}.Release|Any CPU.ActiveCfg = Release|Any CPU 27 | {1EE45AAB-A601-4FD3-A65C-FF09EB1C76A0}.Release|Any CPU.Build.0 = Release|Any CPU 28 | {2804A3A5-3447-41B8-BD23-588306AB8ED1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 29 | {2804A3A5-3447-41B8-BD23-588306AB8ED1}.Debug|Any CPU.Build.0 = Debug|Any CPU 30 | {2804A3A5-3447-41B8-BD23-588306AB8ED1}.Release|Any CPU.ActiveCfg = Release|Any CPU 31 | {2804A3A5-3447-41B8-BD23-588306AB8ED1}.Release|Any CPU.Build.0 = Release|Any CPU 32 | {ACEB65ED-1EA7-449B-973B-192D380BB8FF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 33 | {ACEB65ED-1EA7-449B-973B-192D380BB8FF}.Debug|Any CPU.Build.0 = Debug|Any CPU 34 | {ACEB65ED-1EA7-449B-973B-192D380BB8FF}.Release|Any CPU.ActiveCfg = Release|Any CPU 35 | {ACEB65ED-1EA7-449B-973B-192D380BB8FF}.Release|Any CPU.Build.0 = Release|Any CPU 36 | EndGlobalSection 37 | GlobalSection(SolutionProperties) = preSolution 38 | HideSolutionNode = FALSE 39 | EndGlobalSection 40 | GlobalSection(ExtensibilityGlobals) = postSolution 41 | SolutionGuid = {34239254-9185-4CBD-BC83-A9A3DE19A94E} 42 | EndGlobalSection 43 | EndGlobal 44 | -------------------------------------------------------------------------------- /af-userapi/.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # Azure Functions localsettings file 5 | local.settings.json 6 | 7 | # User-specific files 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Build results 17 | [Dd]ebug/ 18 | [Dd]ebugPublic/ 19 | [Rr]elease/ 20 | [Rr]eleases/ 21 | x64/ 22 | x86/ 23 | bld/ 24 | [Bb]in/ 25 | [Oo]bj/ 26 | [Ll]og/ 27 | 28 | # Visual Studio 2015 cache/options directory 29 | .vs/ 30 | # Uncomment if you have tasks that create the project's static files in wwwroot 31 | #wwwroot/ 32 | 33 | # MSTest test Results 34 | [Tt]est[Rr]esult*/ 35 | [Bb]uild[Ll]og.* 36 | 37 | # NUNIT 38 | *.VisualState.xml 39 | TestResult.xml 40 | 41 | # Build Results of an ATL Project 42 | [Dd]ebugPS/ 43 | [Rr]eleasePS/ 44 | dlldata.c 45 | 46 | # DNX 47 | project.lock.json 48 | project.fragment.lock.json 49 | artifacts/ 50 | 51 | *_i.c 52 | *_p.c 53 | *_i.h 54 | *.ilk 55 | *.meta 56 | *.obj 57 | *.pch 58 | *.pdb 59 | *.pgc 60 | *.pgd 61 | *.rsp 62 | *.sbr 63 | *.tlb 64 | *.tli 65 | *.tlh 66 | *.tmp 67 | *.tmp_proj 68 | *.log 69 | *.vspscc 70 | *.vssscc 71 | .builds 72 | *.pidb 73 | *.svclog 74 | *.scc 75 | 76 | # Chutzpah Test files 77 | _Chutzpah* 78 | 79 | # Visual C++ cache files 80 | ipch/ 81 | *.aps 82 | *.ncb 83 | *.opendb 84 | *.opensdf 85 | *.sdf 86 | *.cachefile 87 | *.VC.db 88 | *.VC.VC.opendb 89 | 90 | # Visual Studio profiler 91 | *.psess 92 | *.vsp 93 | *.vspx 94 | *.sap 95 | 96 | # TFS 2012 Local Workspace 97 | $tf/ 98 | 99 | # Guidance Automation Toolkit 100 | *.gpState 101 | 102 | # ReSharper is a .NET coding add-in 103 | _ReSharper*/ 104 | *.[Rr]e[Ss]harper 105 | *.DotSettings.user 106 | 107 | # JustCode is a .NET coding add-in 108 | .JustCode 109 | 110 | # TeamCity is a build add-in 111 | _TeamCity* 112 | 113 | # DotCover is a Code Coverage Tool 114 | *.dotCover 115 | 116 | # NCrunch 117 | _NCrunch_* 118 | .*crunch*.local.xml 119 | nCrunchTemp_* 120 | 121 | # MightyMoose 122 | *.mm.* 123 | AutoTest.Net/ 124 | 125 | # Web workbench (sass) 126 | .sass-cache/ 127 | 128 | # Installshield output folder 129 | [Ee]xpress/ 130 | 131 | # DocProject is a documentation generator add-in 132 | DocProject/buildhelp/ 133 | DocProject/Help/*.HxT 134 | DocProject/Help/*.HxC 135 | DocProject/Help/*.hhc 136 | DocProject/Help/*.hhk 137 | DocProject/Help/*.hhp 138 | DocProject/Help/Html2 139 | DocProject/Help/html 140 | 141 | # Click-Once directory 142 | publish/ 143 | 144 | # Publish Web Output 145 | *.[Pp]ublish.xml 146 | *.azurePubxml 147 | # TODO: Comment the next line if you want to checkin your web deploy settings 148 | # but database connection strings (with potential passwords) will be unencrypted 149 | #*.pubxml 150 | *.publishproj 151 | 152 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 153 | # checkin your Azure Web App publish settings, but sensitive information contained 154 | # in these scripts will be unencrypted 155 | PublishScripts/ 156 | 157 | # NuGet Packages 158 | *.nupkg 159 | # The packages folder can be ignored because of Package Restore 160 | **/packages/* 161 | # except build/, which is used as an MSBuild target. 162 | !**/packages/build/ 163 | # Uncomment if necessary however generally it will be regenerated when needed 164 | #!**/packages/repositories.config 165 | # NuGet v3's project.json files produces more ignoreable files 166 | *.nuget.props 167 | *.nuget.targets 168 | 169 | # Microsoft Azure Build Output 170 | csx/ 171 | *.build.csdef 172 | 173 | # Microsoft Azure Emulator 174 | ecf/ 175 | rcf/ 176 | 177 | # Windows Store app package directories and files 178 | AppPackages/ 179 | BundleArtifacts/ 180 | Package.StoreAssociation.xml 181 | _pkginfo.txt 182 | 183 | # Visual Studio cache files 184 | # files ending in .cache can be ignored 185 | *.[Cc]ache 186 | # but keep track of directories ending in .cache 187 | !*.[Cc]ache/ 188 | 189 | # Others 190 | ClientBin/ 191 | ~$* 192 | *~ 193 | *.dbmdl 194 | *.dbproj.schemaview 195 | *.jfm 196 | *.pfx 197 | *.publishsettings 198 | node_modules/ 199 | orleans.codegen.cs 200 | 201 | # Since there are multiple workflows, uncomment next line to ignore bower_components 202 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 203 | #bower_components/ 204 | 205 | # RIA/Silverlight projects 206 | Generated_Code/ 207 | 208 | # Backup & report files from converting an old project file 209 | # to a newer Visual Studio version. Backup files are not needed, 210 | # because we have git ;-) 211 | _UpgradeReport_Files/ 212 | Backup*/ 213 | UpgradeLog*.XML 214 | UpgradeLog*.htm 215 | 216 | # SQL Server files 217 | *.mdf 218 | *.ldf 219 | 220 | # Business Intelligence projects 221 | *.rdl.data 222 | *.bim.layout 223 | *.bim_*.settings 224 | 225 | # Microsoft Fakes 226 | FakesAssemblies/ 227 | 228 | # GhostDoc plugin setting file 229 | *.GhostDoc.xml 230 | 231 | # Node.js Tools for Visual Studio 232 | .ntvs_analysis.dat 233 | 234 | # Visual Studio 6 build log 235 | *.plg 236 | 237 | # Visual Studio 6 workspace options file 238 | *.opt 239 | 240 | # Visual Studio LightSwitch build output 241 | **/*.HTMLClient/GeneratedArtifacts 242 | **/*.DesktopClient/GeneratedArtifacts 243 | **/*.DesktopClient/ModelManifest.xml 244 | **/*.Server/GeneratedArtifacts 245 | **/*.Server/ModelManifest.xml 246 | _Pvt_Extensions 247 | 248 | # Paket dependency manager 249 | .paket/paket.exe 250 | paket-files/ 251 | 252 | # FAKE - F# Make 253 | .fake/ 254 | 255 | # JetBrains Rider 256 | .idea/ 257 | *.sln.iml 258 | 259 | # CodeRush 260 | .cr/ 261 | 262 | # Python Tools for Visual Studio (PTVS) 263 | __pycache__/ 264 | *.pyc -------------------------------------------------------------------------------- /af-userapi/BaseFunction.cs: -------------------------------------------------------------------------------- 1 | namespace af_userapi; 2 | 3 | public class BaseFunction 4 | { 5 | private IMediator mediator; 6 | private readonly HttpContext httpContext; 7 | 8 | public BaseFunction(IHttpContextAccessor httpContextAccessor) 9 | { 10 | httpContext = httpContextAccessor.HttpContext; 11 | } 12 | 13 | /// 14 | /// Gets the Mediator. 15 | /// 16 | protected IMediator Mediator => this.mediator ??= httpContext.RequestServices.GetService(); 17 | } 18 | -------------------------------------------------------------------------------- /af-userapi/GlobalUsing.cs: -------------------------------------------------------------------------------- 1 | global using af_userapi; 2 | global using MediatR; 3 | global using Microsoft.AspNetCore.Http; 4 | global using Microsoft.AspNetCore.Mvc; 5 | global using Microsoft.Azure.Functions.Extensions.DependencyInjection; 6 | global using Microsoft.Azure.WebJobs; 7 | global using Microsoft.Extensions.Configuration; 8 | global using Microsoft.Extensions.DependencyInjection; 9 | global using Microsoft.Extensions.Logging; 10 | global using Newtonsoft.Json; 11 | global using System.IO; 12 | global using System.Threading.Tasks; 13 | global using user.application; 14 | global using user.application.Common.DTO; 15 | global using user.application.Common.VM; 16 | global using user.application.User.Commands; 17 | global using user.application.User.Queries; 18 | global using user.domain.Interfaces.Persistense; 19 | global using user.infrastructure; 20 | global using user.infrastructure.AppSettings; 21 | global using user.infrastructure.CosmosDbData.Repository; 22 | global using Microsoft.Azure.WebJobs.Extensions.Http; -------------------------------------------------------------------------------- /af-userapi/Properties/serviceDependencies.json: -------------------------------------------------------------------------------- 1 | { 2 | "dependencies": { 3 | "appInsights1": { 4 | "type": "appInsights" 5 | }, 6 | "storage1": { 7 | "type": "storage", 8 | "connectionId": "AzureWebJobsStorage" 9 | } 10 | } 11 | } -------------------------------------------------------------------------------- /af-userapi/Properties/serviceDependencies.local.json: -------------------------------------------------------------------------------- 1 | { 2 | "dependencies": { 3 | "appInsights1": { 4 | "type": "appInsights.sdk" 5 | }, 6 | "storage1": { 7 | "type": "storage.emulator", 8 | "connectionId": "AzureWebJobsStorage" 9 | } 10 | } 11 | } -------------------------------------------------------------------------------- /af-userapi/Startup.cs: -------------------------------------------------------------------------------- 1 | [assembly: FunctionsStartup(typeof(Startup))] 2 | 3 | namespace af_userapi; 4 | 5 | public class Startup : FunctionsStartup 6 | { 7 | public override void Configure(IFunctionsHostBuilder builder) 8 | { 9 | IConfigurationRoot configuration = new ConfigurationBuilder() 10 | .SetBasePath(Directory.GetCurrentDirectory()) 11 | .AddJsonFile($"local.settings.json", optional: true, reloadOnChange: true) 12 | .AddEnvironmentVariables() 13 | .Build(); 14 | 15 | builder.Services.AddSingleton(configuration); 16 | 17 | CosmosDbSettings cosmosDbConfig = configuration.GetSection("ConnectionStrings:FamspotDB").Get(); 18 | builder.Services.AddInfrastructure(cosmosDbConfig.EndpointUrl, 19 | cosmosDbConfig.PrimaryKey, 20 | cosmosDbConfig.DatabaseName, 21 | cosmosDbConfig.Containers); 22 | 23 | builder.Services.AddScoped(); 24 | 25 | builder.Services.AddApplication(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /af-userapi/UserAPI.cs: -------------------------------------------------------------------------------- 1 | namespace af_userapi 2 | { 3 | public class UserAPI 4 | { 5 | private readonly IMediator mediator; 6 | 7 | public UserAPI(IHttpContextAccessor httpContextAccessor) 8 | { 9 | this.mediator = httpContextAccessor.HttpContext.RequestServices.GetService(); 10 | } 11 | 12 | [FunctionName("Get")] 13 | public async Task> Get( 14 | [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "Get/{email}")] HttpRequest req, 15 | ILogger log, string email) 16 | { 17 | return await this.mediator.Send(new GetSingleUserQuery { Email = email }); 18 | } 19 | 20 | [FunctionName("GetAll")] 21 | public async Task> GetAllUser( 22 | [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "GetAll/{userStatus}")] HttpRequest req, 23 | ILogger log, int userStatus) 24 | { 25 | log.LogInformation("C# HTTP trigger function processed a request."); 26 | var status = (UserStatus)userStatus; 27 | return await this.mediator.Send(new GetAllUserQuery { Status = status }); 28 | } 29 | 30 | [FunctionName("Add")] 31 | public async Task> AddUser( 32 | [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, 33 | ILogger log) 34 | { 35 | log.LogInformation("C# HTTP trigger function processed a request."); 36 | string requestData = await new StreamReader(req.Body).ReadToEndAsync(); 37 | var user = JsonConvert.DeserializeObject(requestData); 38 | return await this.mediator.Send(user); 39 | } 40 | 41 | [FunctionName("Update")] 42 | public async Task> UpdateUser( 43 | [HttpTrigger(AuthorizationLevel.Anonymous, "put", Route = null)] HttpRequest req, 44 | ILogger log) 45 | { 46 | log.LogInformation("C# HTTP trigger function processed a request."); 47 | string requestData = await new StreamReader(req.Body).ReadToEndAsync(); 48 | var user = JsonConvert.DeserializeObject(requestData); 49 | return await this.mediator.Send(user); 50 | } 51 | 52 | [FunctionName("UpdateStatus")] 53 | public async Task> UpdateUserStatus( 54 | [HttpTrigger(AuthorizationLevel.Anonymous, "put", Route = null)] HttpRequest req, 55 | ILogger log) 56 | { 57 | log.LogInformation("C# HTTP trigger function processed a request."); 58 | string requestData = await new StreamReader(req.Body).ReadToEndAsync(); 59 | var user = JsonConvert.DeserializeObject(requestData); 60 | return await this.mediator.Send(user); 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /af-userapi/af-userapi.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | net6.0 4 | v4 5 | af_userapi 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | PreserveNewest 21 | 22 | 23 | PreserveNewest 24 | Never 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /af-userapi/host.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0", 3 | "logging": { 4 | "applicationInsights": { 5 | "samplingSettings": { 6 | "isEnabled": true, 7 | "excludedTypes": "Request" 8 | } 9 | } 10 | } 11 | } -------------------------------------------------------------------------------- /user.application/Common/BaseClass/ApplicationBase.cs: -------------------------------------------------------------------------------- 1 | namespace user.application.Common.BaseClass; 2 | 3 | public abstract class ApplicationBase 4 | { 5 | public IMapper Mapper { get; set; } 6 | public IUserRepository UserRepository { get; set; } 7 | 8 | public ApplicationBase(IUserRepository userRepository, IMapper mapper) 9 | { 10 | UserRepository = userRepository; 11 | Mapper = mapper; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /user.application/Common/Behaviors/UnhandledExceptionBehaviour.cs: -------------------------------------------------------------------------------- 1 | namespace user.application.Common.Behaviors; 2 | 3 | public class UnhandledExceptionBehaviour : IPipelineBehavior, TResponse> where TRequest : IRequest 4 | { 5 | private readonly ILogger _logger; 6 | 7 | public UnhandledExceptionBehaviour(ILogger logger) 8 | { 9 | _logger = logger; 10 | } 11 | 12 | public async Task Handle(IRequest request, RequestHandlerDelegate next, CancellationToken cancellationToken) 13 | { 14 | try 15 | { 16 | return await next(); 17 | } 18 | catch (Exception ex) 19 | { 20 | var requestName = typeof(TRequest).Name; 21 | 22 | _logger.LogError(ex, "User Request: Unhandled Exception for Request {Name} {@Request}", requestName, request); 23 | 24 | throw; 25 | } 26 | } 27 | } -------------------------------------------------------------------------------- /user.application/Common/Behaviors/ValidationBehaviour.cs: -------------------------------------------------------------------------------- 1 | namespace user.application.Common.Behaviors; 2 | 3 | public class ValidationBehaviour : IPipelineBehavior 4 | where TRequest : IRequest 5 | { 6 | private readonly IEnumerable> _validators; 7 | 8 | public ValidationBehaviour(IEnumerable> validators) 9 | { 10 | _validators = validators; 11 | } 12 | 13 | public async Task Handle(TRequest request, RequestHandlerDelegate next, CancellationToken cancellationToken) 14 | { 15 | if (_validators.Any()) 16 | { 17 | var context = new ValidationContext(request); 18 | 19 | var validationResults = await Task.WhenAll(_validators.Select(v => v.ValidateAsync(context, cancellationToken))); 20 | var failures = validationResults.SelectMany(r => r.Errors).Where(f => f != null).ToList(); 21 | 22 | if (failures.Count != 0) 23 | throw new ValidationException(failures); 24 | } 25 | return await next(); 26 | } 27 | } -------------------------------------------------------------------------------- /user.application/Common/DTO/UserDTO.cs: -------------------------------------------------------------------------------- 1 | namespace user.application.Common.DTO; 2 | 3 | public class UserDTO : IMapFrom 4 | { 5 | public string? FirstName { get; set; } 6 | public string? LastName { get; set; } 7 | public string? Email { get; set; } 8 | public string? PhoneNumber { get; set; } 9 | public string? Password { get; set; } 10 | public string? Gender { get; set; } 11 | public DateTime? DateOfBirth { get; set; } 12 | public UserStatus? Status { get; set; } 13 | public UserType? UserType { get; set; } 14 | public string? Address1 { get; set; } 15 | public string? Address2 { get; set; } 16 | public string? City { get; set; } 17 | public string? State { get; set; } 18 | public string? Zip { get; set; } 19 | public string? Country { get; set; } 20 | 21 | public string? Salutation { get; set; } 22 | public int? Age { get; set; } 23 | 24 | public void Mapping(Profile profile) 25 | { 26 | profile.CreateMap() 27 | .ForMember(d => d.Salutation, opt => opt.MapFrom(s => s.Gender.ToUpper() == "M" ? "Hi Sir!" : "Hi Ma'am!")) 28 | .ForMember(d => d.Age, opt => opt.MapFrom(s => DateTime.Today.Year - s.DateOfBirth.Value.Year)); 29 | profile.CreateMap(); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /user.application/Common/Exceptions/NotFoundException.cs: -------------------------------------------------------------------------------- 1 | namespace user.application.Common.Exceptions; 2 | 3 | public class NotFoundException : Exception 4 | { 5 | public NotFoundException() 6 | : base() 7 | { 8 | } 9 | 10 | public NotFoundException(string message) 11 | : base(message) 12 | { 13 | } 14 | 15 | public NotFoundException(string message, Exception innerException) 16 | : base(message, innerException) 17 | { 18 | } 19 | 20 | public NotFoundException(string name, object key) 21 | : base($"Entity \"{name}\" ({key}) was not found.") 22 | { 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /user.application/Common/Exceptions/ValidationException.cs: -------------------------------------------------------------------------------- 1 | namespace user.application.Common.Exceptions; 2 | 3 | public class ValidationException : Exception 4 | { 5 | public ValidationException() 6 | : base("One or more validation failures have occurred.") 7 | { 8 | Errors = new Dictionary(); 9 | } 10 | 11 | public ValidationException(IEnumerable failures) 12 | : this() 13 | { 14 | Errors = failures 15 | .GroupBy(e => e.PropertyName, e => e.ErrorMessage) 16 | .ToDictionary(failureGroup => failureGroup.Key, failureGroup => failureGroup.ToArray()); 17 | } 18 | 19 | public IDictionary Errors { get; } 20 | } -------------------------------------------------------------------------------- /user.application/Common/Interfaces/IConfigConstants.cs: -------------------------------------------------------------------------------- 1 | namespace user.application.Common.Interfaces; 2 | 3 | public interface IConfigConstants 4 | { 5 | string AUDIT_CONTAINER { get; } 6 | string USER_CONTAINER { get; } 7 | } 8 | -------------------------------------------------------------------------------- /user.application/Common/Mappings/IMapFrom.cs: -------------------------------------------------------------------------------- 1 | namespace user.application.Common.Mappings; 2 | 3 | public interface IMapFrom 4 | { 5 | void Mapping(Profile profile) => profile.CreateMap(typeof(T), GetType()).ReverseMap(); 6 | } -------------------------------------------------------------------------------- /user.application/Common/Mappings/MappingProfile.cs: -------------------------------------------------------------------------------- 1 | namespace user.application.Common.Mappings; 2 | 3 | public class MappingProfile : Profile 4 | { 5 | public MappingProfile() 6 | { 7 | ApplyMappingsFromAssembly(Assembly.GetExecutingAssembly()); 8 | } 9 | 10 | private void ApplyMappingsFromAssembly(Assembly assembly) 11 | { 12 | var types = assembly.GetExportedTypes() 13 | .Where(t => t.GetInterfaces().Any(i => 14 | i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IMapFrom<>))) 15 | .ToList(); 16 | 17 | foreach (var type in types) 18 | { 19 | var instance = Activator.CreateInstance(type); 20 | 21 | var methodInfo = type.GetMethod("Mapping") 22 | ?? type.GetInterface("IMapFrom`1").GetMethod("Mapping"); 23 | 24 | methodInfo?.Invoke(instance, new object[] { this }); 25 | 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /user.application/Common/VM/UserVM.cs: -------------------------------------------------------------------------------- 1 | namespace user.application.Common.VM; 2 | 3 | public class UserVM 4 | { 5 | public IList? UserList { get; set; } 6 | } 7 | -------------------------------------------------------------------------------- /user.application/GlobalUsing.cs: -------------------------------------------------------------------------------- 1 | global using AutoMapper; 2 | global using FluentValidation; 3 | global using FluentValidation.Results; 4 | global using MediatR; 5 | global using Microsoft.Extensions.DependencyInjection; 6 | global using Microsoft.Extensions.Logging; 7 | global using System.Reflection; 8 | global using user.application.Common.BaseClass; 9 | global using user.application.Common.DTO; 10 | global using user.application.Common.Mappings; 11 | global using user.application.Common.VM; 12 | global using user.domain.Exceptions; 13 | global using user.domain.Interfaces.Persistense; 14 | global using user.domain.Specifications; 15 | -------------------------------------------------------------------------------- /user.application/RegisterService.cs: -------------------------------------------------------------------------------- 1 | namespace user.application; 2 | 3 | public static class RegisterService 4 | { 5 | public static IServiceCollection AddApplication(this IServiceCollection services) 6 | { 7 | services.AddAutoMapper(Assembly.GetExecutingAssembly()); 8 | services.AddValidatorsFromAssembly(Assembly.GetExecutingAssembly()); 9 | services.AddMediatR(Assembly.GetExecutingAssembly()); 10 | return services; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /user.application/User/Commands/AddUserCommand.cs: -------------------------------------------------------------------------------- 1 | namespace user.application.User.Commands; 2 | 3 | public class AddUserCommand : IRequest 4 | { 5 | public string? FirstName { get; set; } 6 | public string? LastName { get; set; } 7 | public string? Email { get; set; } 8 | public string? PhoneNumber { get; set; } 9 | public string? Gender { get; set; } 10 | public DateTime? DateOfBirth { get; set; } 11 | public UserType? UserType { get; set; } 12 | public string? Address1 { get; set; } 13 | public string? Address2 { get; set; } 14 | public string? City { get; set; } 15 | public string? State { get; set; } 16 | public string? Zip { get; set; } 17 | public string? Country { get; set; } 18 | 19 | public class AddNewUserHandler : ApplicationBase, IRequestHandler 20 | { 21 | public AddNewUserHandler(IUserRepository userRepository, IMapper mapper) 22 | : base(userRepository: userRepository, mapper: mapper) { } 23 | 24 | public async Task Handle(AddUserCommand request, CancellationToken cancellationToken) 25 | { 26 | domain.Entities.User entity = new() 27 | { 28 | FirstName = request.FirstName, 29 | LastName = request.LastName, 30 | Email = request.Email, 31 | PhoneNumber = request.PhoneNumber, 32 | Gender = request.Gender, 33 | DateOfBirth = request.DateOfBirth, 34 | Status = UserStatus.PENDING, 35 | UserType = request.UserType.ToString(), 36 | Address1 = request.Address1, 37 | Address2 = request.Address2, 38 | City = request.City, 39 | State = request.State, 40 | Zip = request.Zip, 41 | Country = request.Country 42 | }; 43 | 44 | await this.UserRepository.AddItemAsync(entity); 45 | 46 | 47 | return entity.Id; 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /user.application/User/Commands/AddUserCommandValidator.cs: -------------------------------------------------------------------------------- 1 | namespace user.application.User.Commands; 2 | 3 | public class AddUserCommandValidator : AbstractValidator 4 | { 5 | public AddUserCommandValidator() 6 | { 7 | this.RuleFor(v => v.FirstName).NotEmpty().WithMessage("Enter first name"); 8 | this.RuleFor(v => v.LastName).NotEmpty().WithMessage("Enter last name"); 9 | this.RuleFor(v => v.DateOfBirth).NotEmpty().WithMessage("Enter date of birth"); 10 | this.RuleFor(v => v.Gender).Must(x => (new string[] { "M", "F", "m", "f" }).Contains(x)).WithMessage("Select gender"); 11 | this.RuleFor(v => v.Email).NotEmpty().WithMessage("Enter email"); 12 | this.RuleFor(v => v.PhoneNumber).NotEmpty().WithMessage("Enter phone #"); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /user.application/User/Commands/UpdateUserCommand.cs: -------------------------------------------------------------------------------- 1 | namespace user.application.User.Commands; 2 | 3 | public class UpdateUserCommand : IRequest 4 | { 5 | public string? ID { get; set; } 6 | public string? PhoneNumber { get; set; } 7 | public string? Address1 { get; set; } 8 | public string? Address2 { get; set; } 9 | public string? City { get; set; } 10 | public string? State { get; set; } 11 | public string? Zip { get; set; } 12 | public string? Country { get; set; } 13 | 14 | public class UpdateUserCommandHandler : ApplicationBase, IRequestHandler 15 | { 16 | public UpdateUserCommandHandler(IUserRepository userRepository, IMapper mapper) 17 | : base(userRepository: userRepository, mapper: mapper) { } 18 | 19 | public async Task Handle(UpdateUserCommand request, CancellationToken cancellationToken) 20 | { 21 | var entity = await this.UserRepository.GetItemAsync(request.ID); 22 | if (entity == null) 23 | { 24 | throw new EntityNotFoundException(nameof(domain.Entities.User), request.ID); 25 | } 26 | 27 | entity.PhoneNumber = request.PhoneNumber; 28 | entity.Address1 = request.Address1; 29 | entity.Address2 = request.Address2; 30 | entity.City = request.City; 31 | entity.State = request.State; 32 | entity.Zip = request.Zip; 33 | entity.Country = request.Country; 34 | 35 | await this.UserRepository.UpdateItemAsync(request.ID, entity); 36 | 37 | return true; 38 | } 39 | } 40 | } 41 | 42 | -------------------------------------------------------------------------------- /user.application/User/Commands/UpdateUserCommandValidator.cs: -------------------------------------------------------------------------------- 1 | namespace user.application.User.Commands; 2 | 3 | public class UpdateUserCommandValidator 4 | { 5 | } 6 | -------------------------------------------------------------------------------- /user.application/User/Commands/UpdateUserStatusCommand.cs: -------------------------------------------------------------------------------- 1 | namespace user.application.User.Commands; 2 | 3 | public class UpdateUserStatusCommand : IRequest 4 | { 5 | public string? ID { get; set; } 6 | public UserStatus Status { get; set; } 7 | 8 | public class UpdateUserStatusCommandHandler : ApplicationBase, IRequestHandler 9 | { 10 | public UpdateUserStatusCommandHandler(IUserRepository userRepository, IMapper mapper) 11 | : base(userRepository: userRepository, mapper: mapper) { } 12 | 13 | public async Task Handle(UpdateUserStatusCommand request, CancellationToken cancellationToken) 14 | { 15 | var entity = await this.UserRepository.GetItemAsync(request.ID); 16 | if (entity == null) 17 | { 18 | throw new EntityNotFoundException(nameof(domain.Entities.User), request.ID); 19 | } 20 | 21 | entity.Status = request.Status; 22 | 23 | await this.UserRepository.UpdateItemAsync(request.ID, entity); 24 | 25 | return true; 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /user.application/User/Queries/GetAllUserQuery.cs: -------------------------------------------------------------------------------- 1 | namespace user.application.User.Queries; 2 | 3 | public class GetAllUserQuery : IRequest 4 | { 5 | public UserStatus Status { get; set; } 6 | public class GetAllUserHandler : ApplicationBase, IRequestHandler 7 | { 8 | public GetAllUserHandler(IUserRepository userRepository, IMapper mapper) 9 | : base(userRepository: userRepository, mapper: mapper) { } 10 | 11 | public async Task Handle(GetAllUserQuery request, CancellationToken cancellationToken) 12 | { 13 | UserGetAllSpecification specification = new(request.Status); 14 | var data = await this.UserRepository.GetItemsAsync(specification); 15 | var res = Mapper.Map(data, new List()); 16 | 17 | return await Task.FromResult(new UserVM() { UserList = res }); 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /user.application/User/Queries/GetSingleUserQuery.cs: -------------------------------------------------------------------------------- 1 | namespace user.application.User.Queries; 2 | 3 | public class GetSingleUserQuery : IRequest 4 | { 5 | public string Email { get; set; } 6 | public class GetSingleUserHandler : ApplicationBase, IRequestHandler 7 | { 8 | public GetSingleUserHandler(IUserRepository userRepository, IMapper mapper) 9 | : base(userRepository: userRepository, mapper: mapper) { } 10 | 11 | public async Task Handle(GetSingleUserQuery request, CancellationToken cancellationToken) 12 | { 13 | UserGetSingleSpecification specification = new(request.Email); 14 | var data = await this.UserRepository.GetItemsAsync(specification); 15 | var res = Mapper.Map(data.FirstOrDefault(), new UserDTO()); 16 | return await Task.FromResult(res); 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /user.application/User/Queries/GetSingleUserQueryValidator.cs: -------------------------------------------------------------------------------- 1 | namespace user.application.User.Queries; 2 | 3 | public class GetSingleUserQueryValidator 4 | { 5 | } 6 | -------------------------------------------------------------------------------- /user.application/user.application.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /user.domain/Entities/Audit.cs: -------------------------------------------------------------------------------- 1 | namespace user.domain.Entities; 2 | 3 | public class Audit : BaseEntity 4 | { 5 | public Audit(string entityType, 6 | string entityId, 7 | string entity) 8 | { 9 | this.EntityType = entityType; 10 | this.EntityId = entityId; 11 | this.Entity = entity; 12 | this.DateCreatedUTC = DateTime.UtcNow; 13 | } 14 | 15 | /// 16 | /// Type of the entity, e.g., ToDoItem 17 | /// 18 | public string EntityType { get; set; } 19 | 20 | /// 21 | /// Entity Id. 22 | /// Use this as the Partition Key, so that all the auditing records for the same entity are stored in the same logical partition. 23 | /// 24 | public string EntityId { get; set; } 25 | 26 | /// 27 | /// Entity itself 28 | /// 29 | public string Entity { get; set; } 30 | 31 | /// 32 | /// Date audit record created 33 | /// 34 | public DateTime DateCreatedUTC { get; set; } 35 | 36 | } -------------------------------------------------------------------------------- /user.domain/Entities/BaseEntity.cs: -------------------------------------------------------------------------------- 1 | namespace user.domain.Entities; 2 | 3 | public abstract class BaseEntity 4 | { 5 | [JsonProperty(PropertyName = "id")] 6 | public virtual string? Id { get; set; } 7 | } 8 | -------------------------------------------------------------------------------- /user.domain/Entities/User.cs: -------------------------------------------------------------------------------- 1 | namespace user.domain.Entities; 2 | 3 | public class User : BaseEntity 4 | { 5 | public string? FirstName { get; set; } 6 | public string? LastName { get; set; } 7 | public string? Email { get; set; } 8 | public string? PhoneNumber { get; set; } 9 | public string? Gender { get; set; } 10 | public DateTime? DateOfBirth { get; set; } 11 | public UserStatus? Status { get; set; } 12 | [JsonProperty(PropertyName = "UserType")] 13 | public string? UserType { get; set; } 14 | public string? Address1 { get; set; } 15 | public string? Address2 { get; set; } 16 | public string? City { get; set; } 17 | public string? State { get; set; } 18 | public string? Zip { get; set; } 19 | public string? Country { get; set; } 20 | } -------------------------------------------------------------------------------- /user.domain/Enum/Enum.cs: -------------------------------------------------------------------------------- 1 | public enum UserStatus 2 | { 3 | ACTIVE = 1, 4 | INACTIVE = 2, 5 | PENDING = 3, 6 | BLACKlIST = 4, 7 | } 8 | 9 | public enum UserType 10 | { 11 | Worker = 1, 12 | User = 2 13 | } -------------------------------------------------------------------------------- /user.domain/Exceptions/EntityAlreadyExistsException.cs: -------------------------------------------------------------------------------- 1 | namespace user.domain.Exceptions; 2 | 3 | public class EntityAlreadyExistsException : Exception 4 | { 5 | public EntityAlreadyExistsException() { } 6 | 7 | public EntityAlreadyExistsException(string message) : base(message) { } 8 | 9 | public EntityAlreadyExistsException(string message, Exception inner) : base(message, inner) 10 | { } 11 | } 12 | -------------------------------------------------------------------------------- /user.domain/Exceptions/EntityNotFoundException.cs: -------------------------------------------------------------------------------- 1 | namespace user.domain.Exceptions; 2 | 3 | public class EntityNotFoundException : Exception 4 | { 5 | public EntityNotFoundException() { } 6 | public EntityNotFoundException(string message) : base(message) { } 7 | public EntityNotFoundException(string message, Exception innerException) : base(message, innerException) 8 | { } 9 | 10 | public EntityNotFoundException(string name, object key) 11 | : base($"Entity \"{name}\" ({key}) was not found.") 12 | { 13 | } 14 | } -------------------------------------------------------------------------------- /user.domain/Exceptions/InvalidCredentialsException.cs: -------------------------------------------------------------------------------- 1 | namespace user.domain.Exceptions; 2 | 3 | public class InvalidCredentialsException : Exception 4 | { 5 | public InvalidCredentialsException() : base("Invalid Username and/or Password. Please try again.") 6 | { } 7 | public InvalidCredentialsException(string message) : base(message) { } 8 | public InvalidCredentialsException(string message, Exception innerException) : base(message, innerException) 9 | { } 10 | } 11 | -------------------------------------------------------------------------------- /user.domain/GlobalUsing.cs: -------------------------------------------------------------------------------- 1 | global using Ardalis.Specification; 2 | global using Microsoft.Azure.Cosmos; 3 | global using Newtonsoft.Json; 4 | global using user.domain.Entities; 5 | global using user.domain.Specifications.Interfaces; 6 | -------------------------------------------------------------------------------- /user.domain/Interfaces/Persistense/IAuditRepository.cs: -------------------------------------------------------------------------------- 1 | namespace user.domain.Interfaces.Persistense; 2 | 3 | public interface IAuditRepository : IRepository 4 | { 5 | } -------------------------------------------------------------------------------- /user.domain/Interfaces/Persistense/IRepository.cs: -------------------------------------------------------------------------------- 1 | namespace user.domain.Interfaces.Persistense; 2 | 3 | public interface IRepository where T : BaseEntity 4 | { 5 | /// 6 | /// Get items given a string SQL query directly. 7 | /// Likely in production, you may want to use alternatives like Parameterized Query or LINQ to avoid SQL Injection and avoid having to work with strings directly. 8 | /// This is kept here for demonstration purpose. 9 | /// 10 | /// 11 | /// 12 | Task> GetItemsAsync(string query); 13 | /// 14 | /// Get items given a specification. 15 | /// 16 | /// 17 | /// 18 | Task> GetItemsAsync(ISpecification specification); 19 | 20 | /// 21 | /// Get the count on items that match the specification 22 | /// 23 | /// 24 | /// 25 | Task> GetItemsCountAsync(ISpecification specification); 26 | 27 | /// 28 | /// Get one item by Id 29 | /// 30 | /// 31 | /// 32 | Task GetItemAsync(string id); 33 | Task AddItemAsync(T item); 34 | Task UpdateItemAsync(string id, T item); 35 | Task DeleteItemAsync(string id); 36 | 37 | } -------------------------------------------------------------------------------- /user.domain/Interfaces/Persistense/IUserRepository.cs: -------------------------------------------------------------------------------- 1 | namespace user.domain.Interfaces.Persistense; 2 | 3 | public interface IUserRepository : IRepository 4 | { 5 | } -------------------------------------------------------------------------------- /user.domain/Specifications/AuditFilterSpecification.cs: -------------------------------------------------------------------------------- 1 | namespace user.domain.Specifications; 2 | 3 | public class AuditFilterSpecification : Specification 4 | { 5 | /// 6 | /// Search by a matching entity Id 7 | /// 8 | /// 9 | public AuditFilterSpecification(string entityId) 10 | { 11 | Query.Where(audit => 12 | // Must include EntityId, because it is part of the Partition Key 13 | audit.EntityId == entityId) 14 | .OrderByDescending(audit => audit.DateCreatedUTC); 15 | } 16 | 17 | } -------------------------------------------------------------------------------- /user.domain/Specifications/Base/CosmosDbSpecificationEvaluator.cs: -------------------------------------------------------------------------------- 1 | namespace user.domain.Specifications.Base; 2 | 3 | public class CosmosDbSpecificationEvaluator : SpecificationEvaluatorBase where T : class 4 | { 5 | } -------------------------------------------------------------------------------- /user.domain/Specifications/Interfaces/ISearchQuery.cs: -------------------------------------------------------------------------------- 1 | namespace user.domain.Specifications.Interfaces; 2 | 3 | public interface ISearchQuery 4 | { 5 | int Start { get; set; } 6 | int PageSize { get; set; } 7 | string SortColumn { get; set; } 8 | SortDirection? SortDirection { get; set; } 9 | } 10 | 11 | public enum SortDirection 12 | { 13 | Ascending = 0, 14 | Descending = 1 15 | } -------------------------------------------------------------------------------- /user.domain/Specifications/UserGetAllSpecification.cs: -------------------------------------------------------------------------------- 1 | using User = user.domain.Entities.User; 2 | 3 | namespace user.domain.Specifications; 4 | 5 | public class UserGetAllSpecification : Specification 6 | { 7 | public UserGetAllSpecification(UserStatus status) 8 | { 9 | Query.Where(item => 10 | item.Status == status 11 | ); 12 | } 13 | } -------------------------------------------------------------------------------- /user.domain/Specifications/UserGetSingleSpecification.cs: -------------------------------------------------------------------------------- 1 | using User = user.domain.Entities.User; 2 | 3 | namespace user.domain.Specifications; 4 | 5 | public class UserGetSingleSpecification : Specification 6 | { 7 | public UserGetSingleSpecification(string email) 8 | { 9 | Query.Where(item => item.Email == email); 10 | } 11 | } -------------------------------------------------------------------------------- /user.domain/Specifications/UserSearchAggregationSpecification.cs: -------------------------------------------------------------------------------- 1 | using User = user.domain.Entities.User; 2 | 3 | namespace user.domain.Specifications; 4 | 5 | public class UserSearchAggregationSpecification : Specification 6 | { 7 | public UserSearchAggregationSpecification(string email = "", 8 | int pageStart = 0, 9 | int pageSize = 50, 10 | string sortColumn = "title", 11 | SortDirection sortDirection = SortDirection.Ascending, 12 | bool exactSearch = false 13 | ) 14 | { 15 | if (!string.IsNullOrWhiteSpace(email)) 16 | { 17 | if (exactSearch) 18 | { 19 | Query.Where(item => item.Email.ToLower() == email.ToLower()); 20 | } 21 | else 22 | { 23 | Query.Where(item => item.Email.ToLower().Contains(email.ToLower())); 24 | } 25 | } 26 | 27 | } 28 | } -------------------------------------------------------------------------------- /user.domain/Specifications/UserSearchSpecification.cs: -------------------------------------------------------------------------------- 1 | namespace user.domain.Specifications; 2 | 3 | public class UserSearchSpecification : Specification 4 | { 5 | public UserSearchSpecification(string id, 6 | int pageStart = 0, 7 | int pageSize = 50, 8 | string sortColumn = "FirstName", 9 | SortDirection sortDirection = SortDirection.Ascending, 10 | bool exactSearch = false) 11 | { 12 | if (!string.IsNullOrWhiteSpace(id)) 13 | { 14 | if (exactSearch) 15 | { 16 | Query.Where(item => item.Id.ToLower() == id.ToLower()); 17 | } 18 | else 19 | { 20 | Query.Where(item => item.Id.ToLower().Contains(id.ToLower())); 21 | } 22 | } 23 | 24 | // Pagination 25 | if (pageSize != -1) //Display all entries and disable pagination 26 | { 27 | Query.Skip(pageStart).Take(pageSize); 28 | } 29 | 30 | // Sort 31 | switch (sortColumn.ToLower()) 32 | { 33 | case ("FirstName"): 34 | { 35 | if (sortDirection == SortDirection.Ascending) 36 | { 37 | Query.OrderBy(x => x.FirstName); 38 | } 39 | else 40 | { 41 | Query.OrderByDescending(x => x.FirstName); 42 | } 43 | } 44 | break; 45 | default: 46 | break; 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /user.domain/user.domain.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /user.infrastructure/AppSettings/CosmosDbSettings.cs: -------------------------------------------------------------------------------- 1 | namespace user.infrastructure.AppSettings; 2 | 3 | public class CosmosDbSettings 4 | { 5 | /// 6 | /// CosmosDb Account - The Azure Cosmos DB endpoint 7 | /// 8 | public string? EndpointUrl { get; set; } 9 | /// 10 | /// Key - The primary key for the Azure DocumentDB account. 11 | /// 12 | public string? PrimaryKey { get; set; } 13 | /// 14 | /// Database name 15 | /// 16 | public string? DatabaseName { get; set; } 17 | 18 | /// 19 | /// List of containers in the database 20 | /// 21 | public List? Containers { get; set; } 22 | 23 | } 24 | public class ContainerInfo 25 | { 26 | /// 27 | /// Container Name 28 | /// 29 | public string? Name { get; set; } 30 | /// 31 | /// Container partition Key 32 | /// 33 | public string? PartitionKey { get; set; } 34 | } -------------------------------------------------------------------------------- /user.infrastructure/CosmosDbData/Constants/ConfigConstants.cs: -------------------------------------------------------------------------------- 1 | namespace user.infrastructure.CosmosDbData.Constants; 2 | 3 | public class ConfigConstants : IConfigConstants 4 | { 5 | public IConfiguration Configuration { get; } 6 | private readonly CosmosDbSettings cosmosDbConfig; 7 | 8 | public ConfigConstants(IConfiguration configuration) 9 | { 10 | this.Configuration = configuration; 11 | this.cosmosDbConfig = this.Configuration.GetSection("ConnectionStrings:FamspotDB").Get(); 12 | } 13 | 14 | public string AUDIT_CONTAINER => this.cosmosDbConfig?.Containers[0]?.Name; 15 | 16 | public string USER_CONTAINER => this.cosmosDbConfig?.Containers[1]?.Name; 17 | } 18 | -------------------------------------------------------------------------------- /user.infrastructure/CosmosDbData/CosmosDbContainer.cs: -------------------------------------------------------------------------------- 1 | namespace user.infrastructure.CosmosDbData; 2 | 3 | public class CosmosDbContainer : ICosmosDbContainer 4 | { 5 | public Container _container { get; } 6 | 7 | public CosmosDbContainer(CosmosClient cosmosClient, 8 | string databaseName, 9 | string containerName) 10 | { 11 | this._container = cosmosClient.GetContainer(databaseName, containerName); 12 | } 13 | } -------------------------------------------------------------------------------- /user.infrastructure/CosmosDbData/CosmosDbContainerFactory.cs: -------------------------------------------------------------------------------- 1 | namespace user.infrastructure.CosmosDbData; 2 | 3 | public class CosmosDbContainerFactory : ICosmosDbContainerFactory 4 | { 5 | /// 6 | /// Azure Cosmos DB Client 7 | /// 8 | private readonly CosmosClient _cosmosClient; 9 | private readonly string _databaseName; 10 | private readonly List _containers; 11 | 12 | /// 13 | /// Ctor 14 | /// 15 | /// 16 | /// 17 | /// 18 | public CosmosDbContainerFactory(CosmosClient cosmosClient, 19 | string databaseName, 20 | List containers) 21 | { 22 | _databaseName = databaseName ?? throw new ArgumentNullException(nameof(databaseName)); 23 | _containers = containers ?? throw new ArgumentNullException(nameof(containers)); 24 | _cosmosClient = cosmosClient ?? throw new ArgumentNullException(nameof(cosmosClient)); 25 | } 26 | 27 | public ICosmosDbContainer GetContainer(string containerName) 28 | { 29 | if (_containers.Where(x => x.Name == containerName) == null) 30 | { 31 | throw new ArgumentException($"Unable to find container: {containerName}"); 32 | } 33 | 34 | return new CosmosDbContainer(_cosmosClient, _databaseName, containerName); 35 | } 36 | 37 | public async Task EnsureDbSetupAsync() 38 | { 39 | Microsoft.Azure.Cosmos.DatabaseResponse database = await _cosmosClient.CreateDatabaseIfNotExistsAsync(_databaseName); 40 | 41 | foreach (ContainerInfo container in _containers) 42 | { 43 | await database.Database.CreateContainerIfNotExistsAsync(container.Name, $"{container.PartitionKey}"); 44 | } 45 | } 46 | } -------------------------------------------------------------------------------- /user.infrastructure/CosmosDbData/Interfaces/IContainerContext.cs: -------------------------------------------------------------------------------- 1 | namespace user.infrastructure.CosmosDbData.Interfaces; 2 | 3 | /// 4 | /// Defines the container level context 5 | /// 6 | /// 7 | public interface IContainerContext where T : BaseEntity 8 | { 9 | //string ContainerName { get; } 10 | string GenerateId(T entity); 11 | PartitionKey ResolvePartitionKey(string entityId); 12 | } 13 | -------------------------------------------------------------------------------- /user.infrastructure/CosmosDbData/Interfaces/ICosmosDbContainer.cs: -------------------------------------------------------------------------------- 1 | namespace user.infrastructure.CosmosDbData.Interfaces; 2 | 3 | public interface ICosmosDbContainer 4 | { 5 | /// 6 | /// Instance of Azure Cosmos DB Container class 7 | /// 8 | Container _container { get; } 9 | } -------------------------------------------------------------------------------- /user.infrastructure/CosmosDbData/Interfaces/ICosmosDbContainerFactory.cs: -------------------------------------------------------------------------------- 1 | namespace user.infrastructure.CosmosDbData.Interfaces; 2 | 3 | public interface ICosmosDbContainerFactory 4 | { 5 | /// 6 | /// Returns a CosmosDbContainer wrapper 7 | /// 8 | /// 9 | /// 10 | ICosmosDbContainer GetContainer(string containerName); 11 | 12 | /// 13 | /// Ensure the database is created 14 | /// 15 | /// 16 | Task EnsureDbSetupAsync(); 17 | } -------------------------------------------------------------------------------- /user.infrastructure/CosmosDbData/Repository/AuditRepository.cs: -------------------------------------------------------------------------------- 1 | namespace user.infrastructure.CosmosDbData.Repository; 2 | 3 | public class AuditRepository : CosmosDbRepository, IAuditRepository 4 | { 5 | public override string GenerateId(Audit entity) => GenerateAuditId(entity); 6 | public override PartitionKey ResolvePartitionKey(string entityId) => ResolveAuditPartitionKey(entityId); 7 | 8 | public AuditRepository(ICosmosDbContainerFactory factory, IConfigConstants configConstants) : base(factory, configConstants.AUDIT_CONTAINER) 9 | { } 10 | 11 | } -------------------------------------------------------------------------------- /user.infrastructure/CosmosDbData/Repository/CosmosDbRepository.cs: -------------------------------------------------------------------------------- 1 |  2 | namespace user.infrastructure.CosmosDbData.Repository; 3 | 4 | public abstract class CosmosDbRepository : IRepository, IContainerContext where T : BaseEntity 5 | { 6 | /// 7 | /// Generate id 8 | /// 9 | /// 10 | /// 11 | public abstract string GenerateId(T entity); 12 | 13 | /// 14 | /// Resolve the partition key 15 | /// 16 | /// 17 | /// 18 | public abstract PartitionKey ResolvePartitionKey(string entityId); 19 | 20 | /// 21 | /// Generate id for the audit record. 22 | /// All entities will share the same audit container, 23 | /// so we can define this method here with virtual default implementation. 24 | /// Audit records for different entities will use different partition key values, 25 | /// so we are not limited to the 20G per logical partition storage limit. 26 | /// 27 | /// 28 | /// 29 | public virtual string GenerateAuditId(Audit entity) => $"{entity.EntityId}:{Guid.NewGuid()}"; 30 | 31 | /// 32 | /// Resolve the partition key for the audit record. 33 | /// All entities will share the same audit container, 34 | /// so we can define this method here with virtual default implementation. 35 | /// Audit records for different entities will use different partition key values, 36 | /// so we are not limited to the 20G per logical partition storage limit. 37 | /// 38 | /// 39 | /// 40 | public virtual PartitionKey ResolveAuditPartitionKey(string entityId) => new PartitionKey($"{entityId.Split(':')[0]}:{entityId.Split(':')[1]}"); 41 | 42 | /// 43 | /// Cosmos DB factory 44 | /// 45 | private readonly ICosmosDbContainerFactory _cosmosDbContainerFactory; 46 | 47 | /// 48 | /// Cosmos DB container 49 | /// 50 | private readonly Container _container; 51 | /// 52 | /// Audit container that will store audit log for all entities. 53 | /// 54 | private readonly Container _auditContainer; 55 | 56 | public CosmosDbRepository(ICosmosDbContainerFactory cosmosDbContainerFactory, string containerName) 57 | { 58 | this._cosmosDbContainerFactory = cosmosDbContainerFactory 59 | ?? throw new ArgumentNullException(nameof(ICosmosDbContainerFactory)); 60 | this._container = this._cosmosDbContainerFactory.GetContainer(containerName)._container; 61 | this._auditContainer = this._cosmosDbContainerFactory.GetContainer(containerName)._container; 62 | } 63 | 64 | public async Task AddItemAsync(T item) 65 | { 66 | item.Id = GenerateId(item); 67 | var key = ResolvePartitionKey(item.Id); 68 | await _container.CreateItemAsync(item, key); 69 | } 70 | 71 | public async Task DeleteItemAsync(string id) 72 | { 73 | await this._container.DeleteItemAsync(id, ResolvePartitionKey(id)); 74 | } 75 | 76 | public async Task GetItemAsync(string id) 77 | { 78 | try 79 | { 80 | ItemResponse response = await _container.ReadItemAsync(id, ResolvePartitionKey(id)); 81 | return response.Resource; 82 | } 83 | catch (CosmosException ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound) 84 | { 85 | return null; 86 | } 87 | } 88 | 89 | public async Task> GetItemsAsync(string queryString) 90 | { 91 | FeedIterator resultSetIterator = _container.GetItemQueryIterator(new QueryDefinition(queryString)); 92 | List results = new(); 93 | while (resultSetIterator.HasMoreResults) 94 | { 95 | FeedResponse response = await resultSetIterator.ReadNextAsync(); 96 | 97 | results.AddRange(response.ToList()); 98 | } 99 | 100 | return results; 101 | } 102 | 103 | /// 104 | public async Task> GetItemsAsync(ISpecification specification) 105 | { 106 | IQueryable queryable = ApplySpecification(specification); 107 | FeedIterator iterator = queryable.ToFeedIterator(); 108 | 109 | List results = new(); 110 | while (iterator.HasMoreResults) 111 | { 112 | FeedResponse response = await iterator.ReadNextAsync(); 113 | 114 | results.AddRange(response.ToList()); 115 | } 116 | 117 | return results; 118 | } 119 | 120 | /// 121 | public Task> GetItemsCountAsync(ISpecification specification) 122 | { 123 | IQueryable queryable = ApplySpecification(specification); 124 | return queryable.CountAsync(); 125 | } 126 | 127 | public async Task UpdateItemAsync(string id, T item) 128 | { 129 | // Audit 130 | await Audit(item); 131 | // Update 132 | await this._container.UpsertItemAsync(item, ResolvePartitionKey(id)); 133 | } 134 | 135 | /// 136 | /// Evaluate specification and return IQueryable 137 | /// 138 | /// 139 | /// 140 | private IQueryable ApplySpecification(ISpecification specification) 141 | { 142 | CosmosDbSpecificationEvaluator evaluator = new(); 143 | return evaluator.GetQuery(_container.GetItemLinqQueryable(), specification); 144 | } 145 | 146 | /// 147 | /// Audit a item by adding it to the audit container 148 | /// 149 | /// 150 | /// 151 | private async Task Audit(T item) 152 | { 153 | Audit auditItem = new(item.GetType().Name, 154 | item.Id, 155 | Newtonsoft.Json.JsonConvert.SerializeObject(item)); 156 | auditItem.Id = GenerateAuditId(auditItem); 157 | await _auditContainer.CreateItemAsync(auditItem, ResolveAuditPartitionKey(auditItem.Id)); 158 | } 159 | 160 | 161 | } -------------------------------------------------------------------------------- /user.infrastructure/CosmosDbData/Repository/UserRepository.cs: -------------------------------------------------------------------------------- 1 | using User = user.domain.Entities.User; 2 | 3 | namespace user.infrastructure.CosmosDbData.Repository; 4 | 5 | public class UserRepository : CosmosDbRepository, IUserRepository 6 | { 7 | /// 8 | /// Generate Id. 9 | /// e.g. "shoppinglist:783dfe25-7ece-4f0b-885e-c0ea72135942" 10 | /// 11 | /// 12 | /// 13 | public override string GenerateId(User entity) => $"{entity.UserType}:{Guid.NewGuid()}"; 14 | 15 | /// 16 | /// Returns the value of the partition key 17 | /// 18 | /// 19 | /// 20 | public override PartitionKey ResolvePartitionKey(string entityId) => new(entityId.Split(':')[0]); 21 | 22 | public UserRepository(ICosmosDbContainerFactory factory, IConfigConstants configConstants) : base(factory, configConstants.USER_CONTAINER) 23 | { } 24 | 25 | // Use Cosmos DB Parameterized Query to avoid SQL Injection. 26 | // Get by Category is also an example of single partition read, where get by title will be a cross partition read 27 | public async Task> GetItemsAsyncByID(string Id) 28 | { 29 | var results = new List(); 30 | string query = @$"SELECT c.Name FROM c WHERE c.UserID = @Id"; 31 | 32 | QueryDefinition queryDefinition = new QueryDefinition(query) 33 | .WithParameter("@Id", Id); 34 | string queryString = queryDefinition.QueryText; 35 | 36 | var entities = await this.GetItemsAsync(queryString); 37 | 38 | return results; 39 | } 40 | 41 | // Use Cosmos DB Parameterized Query to avoid SQL Injection. 42 | // Get by Title is also an example of cross partition read, where Get by Category will be single partition read 43 | public async Task> GetItemsAsyncByEmail(string email) 44 | { 45 | List results = new(); 46 | string query = @$"SELECT c.Name FROM c WHERE c.Email = @Email"; 47 | 48 | QueryDefinition queryDefinition = new QueryDefinition(query) 49 | .WithParameter("@Email", email); 50 | string queryString = queryDefinition.QueryText; 51 | 52 | IEnumerable entities = await this.GetItemsAsync(queryString); 53 | 54 | return results; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /user.infrastructure/GlobalUsing.cs: -------------------------------------------------------------------------------- 1 | global using Ardalis.Specification; 2 | global using Microsoft.Azure.Cosmos; 3 | global using Microsoft.Azure.Cosmos.Linq; 4 | global using Microsoft.Extensions.Configuration; 5 | global using Microsoft.Extensions.DependencyInjection; 6 | global using user.application.Common.Interfaces; 7 | global using user.domain.Entities; 8 | global using user.domain.Interfaces.Persistense; 9 | global using user.domain.Specifications.Base; 10 | global using user.infrastructure.AppSettings; 11 | global using user.infrastructure.CosmosDbData; 12 | global using user.infrastructure.CosmosDbData.Interfaces; 13 | -------------------------------------------------------------------------------- /user.infrastructure/RegisterService.cs: -------------------------------------------------------------------------------- 1 | using user.infrastructure.CosmosDbData.Constants; 2 | 3 | namespace user.infrastructure; 4 | 5 | public static class RegisterService 6 | { 7 | public static IServiceCollection AddInfrastructure(this IServiceCollection services, 8 | string endpointUrl, 9 | string primaryKey, 10 | string databaseName, 11 | List containers) 12 | { 13 | var client = new CosmosClient(endpointUrl, primaryKey); 14 | var cosmosDbClientFactory = new CosmosDbContainerFactory(client, databaseName, containers); 15 | services.AddSingleton(cosmosDbClientFactory); 16 | services.AddSingleton(); 17 | return services; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /user.infrastructure/user.infrastructure.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | --------------------------------------------------------------------------------